three.module.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '167dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const DisplayP3ColorSpace = 'display-p3';
  168. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  169. const LinearTransfer = 'linear';
  170. const SRGBTransfer = 'srgb';
  171. const Rec709Primaries = 'rec709';
  172. const P3Primaries = 'p3';
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const NeverCompare = 512;
  190. const LessCompare = 513;
  191. const EqualCompare = 514;
  192. const LessEqualCompare = 515;
  193. const GreaterCompare = 516;
  194. const NotEqualCompare = 517;
  195. const GreaterEqualCompare = 518;
  196. const AlwaysCompare = 519;
  197. const StaticDrawUsage = 35044;
  198. const DynamicDrawUsage = 35048;
  199. const StreamDrawUsage = 35040;
  200. const StaticReadUsage = 35045;
  201. const DynamicReadUsage = 35049;
  202. const StreamReadUsage = 35041;
  203. const StaticCopyUsage = 35046;
  204. const DynamicCopyUsage = 35050;
  205. const StreamCopyUsage = 35042;
  206. const GLSL1 = '100';
  207. const GLSL3 = '300 es';
  208. const WebGLCoordinateSystem = 2000;
  209. const WebGPUCoordinateSystem = 2001;
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) this._listeners = {};
  216. const listeners = this._listeners;
  217. if ( listeners[ type ] === undefined ) {
  218. listeners[ type ] = [];
  219. }
  220. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  221. listeners[ type ].push( listener );
  222. }
  223. }
  224. hasEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return false;
  226. const listeners = this._listeners;
  227. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  228. }
  229. removeEventListener( type, listener ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ type ];
  233. if ( listenerArray !== undefined ) {
  234. const index = listenerArray.indexOf( listener );
  235. if ( index !== - 1 ) {
  236. listenerArray.splice( index, 1 );
  237. }
  238. }
  239. }
  240. dispatchEvent( event ) {
  241. if ( this._listeners === undefined ) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[ event.type ];
  244. if ( listenerArray !== undefined ) {
  245. event.target = this;
  246. // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice( 0 );
  248. for ( let i = 0, l = array.length; i < l; i ++ ) {
  249. array[ i ].call( this, event );
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. 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' ];
  256. let _seed = 1234567;
  257. const DEG2RAD = Math.PI / 180;
  258. const RAD2DEG = 180 / Math.PI;
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. function generateUUID() {
  261. const d0 = Math.random() * 0xffffffff | 0;
  262. const d1 = Math.random() * 0xffffffff | 0;
  263. const d2 = Math.random() * 0xffffffff | 0;
  264. const d3 = Math.random() * 0xffffffff | 0;
  265. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  266. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  267. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  268. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  269. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  270. return uuid.toLowerCase();
  271. }
  272. function clamp( value, min, max ) {
  273. return Math.max( min, Math.min( max, value ) );
  274. }
  275. // compute euclidean modulo of m % n
  276. // https://en.wikipedia.org/wiki/Modulo_operation
  277. function euclideanModulo( n, m ) {
  278. return ( ( n % m ) + m ) % m;
  279. }
  280. // Linear mapping from range <a1, a2> to range <b1, b2>
  281. function mapLinear( x, a1, a2, b1, b2 ) {
  282. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  283. }
  284. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp( x, y, value ) {
  286. if ( x !== y ) {
  287. return ( value - x ) / ( y - x );
  288. } else {
  289. return 0;
  290. }
  291. }
  292. // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp( x, y, t ) {
  294. return ( 1 - t ) * x + t * y;
  295. }
  296. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  297. function damp( x, y, lambda, dt ) {
  298. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  299. }
  300. // https://www.desmos.com/calculator/vcsjnyz7x4
  301. function pingpong( x, length = 1 ) {
  302. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  303. }
  304. // http://en.wikipedia.org/wiki/Smoothstep
  305. function smoothstep( x, min, max ) {
  306. if ( x <= min ) return 0;
  307. if ( x >= max ) return 1;
  308. x = ( x - min ) / ( max - min );
  309. return x * x * ( 3 - 2 * x );
  310. }
  311. function smootherstep( x, min, max ) {
  312. if ( x <= min ) return 0;
  313. if ( x >= max ) return 1;
  314. x = ( x - min ) / ( max - min );
  315. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  316. }
  317. // Random integer from <low, high> interval
  318. function randInt( low, high ) {
  319. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  320. }
  321. // Random float from <low, high> interval
  322. function randFloat( low, high ) {
  323. return low + Math.random() * ( high - low );
  324. }
  325. // Random float from <-range/2, range/2> interval
  326. function randFloatSpread( range ) {
  327. return range * ( 0.5 - Math.random() );
  328. }
  329. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  330. function seededRandom( s ) {
  331. if ( s !== undefined ) _seed = s;
  332. // Mulberry32 generator
  333. let t = _seed += 0x6D2B79F5;
  334. t = Math.imul( t ^ t >>> 15, t | 1 );
  335. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  336. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  337. }
  338. function degToRad( degrees ) {
  339. return degrees * DEG2RAD;
  340. }
  341. function radToDeg( radians ) {
  342. return radians * RAD2DEG;
  343. }
  344. function isPowerOfTwo( value ) {
  345. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  346. }
  347. function ceilPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function floorPowerOfTwo( value ) {
  351. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  352. }
  353. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  354. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  355. // rotations are applied to the axes in the order specified by 'order'
  356. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  357. // angles are in radians
  358. const cos = Math.cos;
  359. const sin = Math.sin;
  360. const c2 = cos( b / 2 );
  361. const s2 = sin( b / 2 );
  362. const c13 = cos( ( a + c ) / 2 );
  363. const s13 = sin( ( a + c ) / 2 );
  364. const c1_3 = cos( ( a - c ) / 2 );
  365. const s1_3 = sin( ( a - c ) / 2 );
  366. const c3_1 = cos( ( c - a ) / 2 );
  367. const s3_1 = sin( ( c - a ) / 2 );
  368. switch ( order ) {
  369. case 'XYX':
  370. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  371. break;
  372. case 'YZY':
  373. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  374. break;
  375. case 'ZXZ':
  376. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  377. break;
  378. case 'XZX':
  379. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  380. break;
  381. case 'YXY':
  382. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  383. break;
  384. case 'ZYZ':
  385. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  386. break;
  387. default:
  388. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  389. }
  390. }
  391. function denormalize( value, array ) {
  392. switch ( array.constructor ) {
  393. case Float32Array:
  394. return value;
  395. case Uint32Array:
  396. return value / 4294967295.0;
  397. case Uint16Array:
  398. return value / 65535.0;
  399. case Uint8Array:
  400. return value / 255.0;
  401. case Int32Array:
  402. return Math.max( value / 2147483647.0, - 1.0 );
  403. case Int16Array:
  404. return Math.max( value / 32767.0, - 1.0 );
  405. case Int8Array:
  406. return Math.max( value / 127.0, - 1.0 );
  407. default:
  408. throw new Error( 'Invalid component type.' );
  409. }
  410. }
  411. function normalize( value, array ) {
  412. switch ( array.constructor ) {
  413. case Float32Array:
  414. return value;
  415. case Uint32Array:
  416. return Math.round( value * 4294967295.0 );
  417. case Uint16Array:
  418. return Math.round( value * 65535.0 );
  419. case Uint8Array:
  420. return Math.round( value * 255.0 );
  421. case Int32Array:
  422. return Math.round( value * 2147483647.0 );
  423. case Int16Array:
  424. return Math.round( value * 32767.0 );
  425. case Int8Array:
  426. return Math.round( value * 127.0 );
  427. default:
  428. throw new Error( 'Invalid component type.' );
  429. }
  430. }
  431. const MathUtils = {
  432. DEG2RAD: DEG2RAD,
  433. RAD2DEG: RAD2DEG,
  434. generateUUID: generateUUID,
  435. clamp: clamp,
  436. euclideanModulo: euclideanModulo,
  437. mapLinear: mapLinear,
  438. inverseLerp: inverseLerp,
  439. lerp: lerp,
  440. damp: damp,
  441. pingpong: pingpong,
  442. smoothstep: smoothstep,
  443. smootherstep: smootherstep,
  444. randInt: randInt,
  445. randFloat: randFloat,
  446. randFloatSpread: randFloatSpread,
  447. seededRandom: seededRandom,
  448. degToRad: degToRad,
  449. radToDeg: radToDeg,
  450. isPowerOfTwo: isPowerOfTwo,
  451. ceilPowerOfTwo: ceilPowerOfTwo,
  452. floorPowerOfTwo: floorPowerOfTwo,
  453. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  454. normalize: normalize,
  455. denormalize: denormalize
  456. };
  457. class Vector2 {
  458. constructor( x = 0, y = 0 ) {
  459. Vector2.prototype.isVector2 = true;
  460. this.x = x;
  461. this.y = y;
  462. }
  463. get width() {
  464. return this.x;
  465. }
  466. set width( value ) {
  467. this.x = value;
  468. }
  469. get height() {
  470. return this.y;
  471. }
  472. set height( value ) {
  473. this.y = value;
  474. }
  475. set( x, y ) {
  476. this.x = x;
  477. this.y = y;
  478. return this;
  479. }
  480. setScalar( scalar ) {
  481. this.x = scalar;
  482. this.y = scalar;
  483. return this;
  484. }
  485. setX( x ) {
  486. this.x = x;
  487. return this;
  488. }
  489. setY( y ) {
  490. this.y = y;
  491. return this;
  492. }
  493. setComponent( index, value ) {
  494. switch ( index ) {
  495. case 0: this.x = value; break;
  496. case 1: this.y = value; break;
  497. default: throw new Error( 'index is out of range: ' + index );
  498. }
  499. return this;
  500. }
  501. getComponent( index ) {
  502. switch ( index ) {
  503. case 0: return this.x;
  504. case 1: return this.y;
  505. default: throw new Error( 'index is out of range: ' + index );
  506. }
  507. }
  508. clone() {
  509. return new this.constructor( this.x, this.y );
  510. }
  511. copy( v ) {
  512. this.x = v.x;
  513. this.y = v.y;
  514. return this;
  515. }
  516. add( v ) {
  517. this.x += v.x;
  518. this.y += v.y;
  519. return this;
  520. }
  521. addScalar( s ) {
  522. this.x += s;
  523. this.y += s;
  524. return this;
  525. }
  526. addVectors( a, b ) {
  527. this.x = a.x + b.x;
  528. this.y = a.y + b.y;
  529. return this;
  530. }
  531. addScaledVector( v, s ) {
  532. this.x += v.x * s;
  533. this.y += v.y * s;
  534. return this;
  535. }
  536. sub( v ) {
  537. this.x -= v.x;
  538. this.y -= v.y;
  539. return this;
  540. }
  541. subScalar( s ) {
  542. this.x -= s;
  543. this.y -= s;
  544. return this;
  545. }
  546. subVectors( a, b ) {
  547. this.x = a.x - b.x;
  548. this.y = a.y - b.y;
  549. return this;
  550. }
  551. multiply( v ) {
  552. this.x *= v.x;
  553. this.y *= v.y;
  554. return this;
  555. }
  556. multiplyScalar( scalar ) {
  557. this.x *= scalar;
  558. this.y *= scalar;
  559. return this;
  560. }
  561. divide( v ) {
  562. this.x /= v.x;
  563. this.y /= v.y;
  564. return this;
  565. }
  566. divideScalar( scalar ) {
  567. return this.multiplyScalar( 1 / scalar );
  568. }
  569. applyMatrix3( m ) {
  570. const x = this.x, y = this.y;
  571. const e = m.elements;
  572. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  573. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  574. return this;
  575. }
  576. min( v ) {
  577. this.x = Math.min( this.x, v.x );
  578. this.y = Math.min( this.y, v.y );
  579. return this;
  580. }
  581. max( v ) {
  582. this.x = Math.max( this.x, v.x );
  583. this.y = Math.max( this.y, v.y );
  584. return this;
  585. }
  586. clamp( min, max ) {
  587. // assumes min < max, componentwise
  588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  590. return this;
  591. }
  592. clampScalar( minVal, maxVal ) {
  593. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  594. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  595. return this;
  596. }
  597. clampLength( min, max ) {
  598. const length = this.length();
  599. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  600. }
  601. floor() {
  602. this.x = Math.floor( this.x );
  603. this.y = Math.floor( this.y );
  604. return this;
  605. }
  606. ceil() {
  607. this.x = Math.ceil( this.x );
  608. this.y = Math.ceil( this.y );
  609. return this;
  610. }
  611. round() {
  612. this.x = Math.round( this.x );
  613. this.y = Math.round( this.y );
  614. return this;
  615. }
  616. roundToZero() {
  617. this.x = Math.trunc( this.x );
  618. this.y = Math.trunc( this.y );
  619. return this;
  620. }
  621. negate() {
  622. this.x = - this.x;
  623. this.y = - this.y;
  624. return this;
  625. }
  626. dot( v ) {
  627. return this.x * v.x + this.y * v.y;
  628. }
  629. cross( v ) {
  630. return this.x * v.y - this.y * v.x;
  631. }
  632. lengthSq() {
  633. return this.x * this.x + this.y * this.y;
  634. }
  635. length() {
  636. return Math.sqrt( this.x * this.x + this.y * this.y );
  637. }
  638. manhattanLength() {
  639. return Math.abs( this.x ) + Math.abs( this.y );
  640. }
  641. normalize() {
  642. return this.divideScalar( this.length() || 1 );
  643. }
  644. angle() {
  645. // computes the angle in radians with respect to the positive x-axis
  646. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  647. return angle;
  648. }
  649. angleTo( v ) {
  650. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  651. if ( denominator === 0 ) return Math.PI / 2;
  652. const theta = this.dot( v ) / denominator;
  653. // clamp, to handle numerical problems
  654. return Math.acos( clamp( theta, - 1, 1 ) );
  655. }
  656. distanceTo( v ) {
  657. return Math.sqrt( this.distanceToSquared( v ) );
  658. }
  659. distanceToSquared( v ) {
  660. const dx = this.x - v.x, dy = this.y - v.y;
  661. return dx * dx + dy * dy;
  662. }
  663. manhattanDistanceTo( v ) {
  664. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  665. }
  666. setLength( length ) {
  667. return this.normalize().multiplyScalar( length );
  668. }
  669. lerp( v, alpha ) {
  670. this.x += ( v.x - this.x ) * alpha;
  671. this.y += ( v.y - this.y ) * alpha;
  672. return this;
  673. }
  674. lerpVectors( v1, v2, alpha ) {
  675. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  676. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  677. return this;
  678. }
  679. equals( v ) {
  680. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  681. }
  682. fromArray( array, offset = 0 ) {
  683. this.x = array[ offset ];
  684. this.y = array[ offset + 1 ];
  685. return this;
  686. }
  687. toArray( array = [], offset = 0 ) {
  688. array[ offset ] = this.x;
  689. array[ offset + 1 ] = this.y;
  690. return array;
  691. }
  692. fromBufferAttribute( attribute, index ) {
  693. this.x = attribute.getX( index );
  694. this.y = attribute.getY( index );
  695. return this;
  696. }
  697. rotateAround( center, angle ) {
  698. const c = Math.cos( angle ), s = Math.sin( angle );
  699. const x = this.x - center.x;
  700. const y = this.y - center.y;
  701. this.x = x * c - y * s + center.x;
  702. this.y = x * s + y * c + center.y;
  703. return this;
  704. }
  705. random() {
  706. this.x = Math.random();
  707. this.y = Math.random();
  708. return this;
  709. }
  710. *[ Symbol.iterator ]() {
  711. yield this.x;
  712. yield this.y;
  713. }
  714. }
  715. class Matrix3 {
  716. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  717. Matrix3.prototype.isMatrix3 = true;
  718. this.elements = [
  719. 1, 0, 0,
  720. 0, 1, 0,
  721. 0, 0, 1
  722. ];
  723. if ( n11 !== undefined ) {
  724. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  725. }
  726. }
  727. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  728. const te = this.elements;
  729. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  730. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  731. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  732. return this;
  733. }
  734. identity() {
  735. this.set(
  736. 1, 0, 0,
  737. 0, 1, 0,
  738. 0, 0, 1
  739. );
  740. return this;
  741. }
  742. copy( m ) {
  743. const te = this.elements;
  744. const me = m.elements;
  745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  746. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  747. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  748. return this;
  749. }
  750. extractBasis( xAxis, yAxis, zAxis ) {
  751. xAxis.setFromMatrix3Column( this, 0 );
  752. yAxis.setFromMatrix3Column( this, 1 );
  753. zAxis.setFromMatrix3Column( this, 2 );
  754. return this;
  755. }
  756. setFromMatrix4( m ) {
  757. const me = m.elements;
  758. this.set(
  759. me[ 0 ], me[ 4 ], me[ 8 ],
  760. me[ 1 ], me[ 5 ], me[ 9 ],
  761. me[ 2 ], me[ 6 ], me[ 10 ]
  762. );
  763. return this;
  764. }
  765. multiply( m ) {
  766. return this.multiplyMatrices( this, m );
  767. }
  768. premultiply( m ) {
  769. return this.multiplyMatrices( m, this );
  770. }
  771. multiplyMatrices( a, b ) {
  772. const ae = a.elements;
  773. const be = b.elements;
  774. const te = this.elements;
  775. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  776. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  777. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  778. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  779. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  780. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  781. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  782. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  783. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  784. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  785. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  786. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  787. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  788. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  789. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  790. return this;
  791. }
  792. multiplyScalar( s ) {
  793. const te = this.elements;
  794. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  795. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  796. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  797. return this;
  798. }
  799. determinant() {
  800. const te = this.elements;
  801. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  802. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  803. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  804. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  805. }
  806. invert() {
  807. const te = this.elements,
  808. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  809. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  810. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  811. t11 = n33 * n22 - n32 * n23,
  812. t12 = n32 * n13 - n33 * n12,
  813. t13 = n23 * n12 - n22 * n13,
  814. det = n11 * t11 + n21 * t12 + n31 * t13;
  815. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  816. const detInv = 1 / det;
  817. te[ 0 ] = t11 * detInv;
  818. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  819. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  820. te[ 3 ] = t12 * detInv;
  821. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  822. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  823. te[ 6 ] = t13 * detInv;
  824. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  825. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  826. return this;
  827. }
  828. transpose() {
  829. let tmp;
  830. const m = this.elements;
  831. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  832. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  833. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  834. return this;
  835. }
  836. getNormalMatrix( matrix4 ) {
  837. return this.setFromMatrix4( matrix4 ).invert().transpose();
  838. }
  839. transposeIntoArray( r ) {
  840. const m = this.elements;
  841. r[ 0 ] = m[ 0 ];
  842. r[ 1 ] = m[ 3 ];
  843. r[ 2 ] = m[ 6 ];
  844. r[ 3 ] = m[ 1 ];
  845. r[ 4 ] = m[ 4 ];
  846. r[ 5 ] = m[ 7 ];
  847. r[ 6 ] = m[ 2 ];
  848. r[ 7 ] = m[ 5 ];
  849. r[ 8 ] = m[ 8 ];
  850. return this;
  851. }
  852. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  853. const c = Math.cos( rotation );
  854. const s = Math.sin( rotation );
  855. this.set(
  856. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  857. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  858. 0, 0, 1
  859. );
  860. return this;
  861. }
  862. //
  863. scale( sx, sy ) {
  864. this.premultiply( _m3.makeScale( sx, sy ) );
  865. return this;
  866. }
  867. rotate( theta ) {
  868. this.premultiply( _m3.makeRotation( - theta ) );
  869. return this;
  870. }
  871. translate( tx, ty ) {
  872. this.premultiply( _m3.makeTranslation( tx, ty ) );
  873. return this;
  874. }
  875. // for 2D Transforms
  876. makeTranslation( x, y ) {
  877. if ( x.isVector2 ) {
  878. this.set(
  879. 1, 0, x.x,
  880. 0, 1, x.y,
  881. 0, 0, 1
  882. );
  883. } else {
  884. this.set(
  885. 1, 0, x,
  886. 0, 1, y,
  887. 0, 0, 1
  888. );
  889. }
  890. return this;
  891. }
  892. makeRotation( theta ) {
  893. // counterclockwise
  894. const c = Math.cos( theta );
  895. const s = Math.sin( theta );
  896. this.set(
  897. c, - s, 0,
  898. s, c, 0,
  899. 0, 0, 1
  900. );
  901. return this;
  902. }
  903. makeScale( x, y ) {
  904. this.set(
  905. x, 0, 0,
  906. 0, y, 0,
  907. 0, 0, 1
  908. );
  909. return this;
  910. }
  911. //
  912. equals( matrix ) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for ( let i = 0; i < 9; i ++ ) {
  916. if ( te[ i ] !== me[ i ] ) return false;
  917. }
  918. return true;
  919. }
  920. fromArray( array, offset = 0 ) {
  921. for ( let i = 0; i < 9; i ++ ) {
  922. this.elements[ i ] = array[ i + offset ];
  923. }
  924. return this;
  925. }
  926. toArray( array = [], offset = 0 ) {
  927. const te = this.elements;
  928. array[ offset ] = te[ 0 ];
  929. array[ offset + 1 ] = te[ 1 ];
  930. array[ offset + 2 ] = te[ 2 ];
  931. array[ offset + 3 ] = te[ 3 ];
  932. array[ offset + 4 ] = te[ 4 ];
  933. array[ offset + 5 ] = te[ 5 ];
  934. array[ offset + 6 ] = te[ 6 ];
  935. array[ offset + 7 ] = te[ 7 ];
  936. array[ offset + 8 ] = te[ 8 ];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray( this.elements );
  941. }
  942. }
  943. const _m3 = /*@__PURE__*/ new Matrix3();
  944. function arrayNeedsUint32( array ) {
  945. // assumes larger values usually on last
  946. for ( let i = array.length - 1; i >= 0; -- i ) {
  947. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  948. }
  949. return false;
  950. }
  951. const TYPED_ARRAYS = {
  952. Int8Array: Int8Array,
  953. Uint8Array: Uint8Array,
  954. Uint8ClampedArray: Uint8ClampedArray,
  955. Int16Array: Int16Array,
  956. Uint16Array: Uint16Array,
  957. Int32Array: Int32Array,
  958. Uint32Array: Uint32Array,
  959. Float32Array: Float32Array,
  960. Float64Array: Float64Array
  961. };
  962. function getTypedArray( type, buffer ) {
  963. return new TYPED_ARRAYS[ type ]( buffer );
  964. }
  965. function createElementNS( name ) {
  966. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  967. }
  968. function createCanvasElement() {
  969. const canvas = createElementNS( 'canvas' );
  970. canvas.style.display = 'block';
  971. return canvas;
  972. }
  973. const _cache = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache ) return;
  976. _cache[ message ] = true;
  977. console.warn( message );
  978. }
  979. function probeAsync( gl, sync, interval ) {
  980. return new Promise( function ( resolve, reject ) {
  981. function probe() {
  982. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  983. case gl.WAIT_FAILED:
  984. reject();
  985. break;
  986. case gl.TIMEOUT_EXPIRED:
  987. setTimeout( probe, interval );
  988. break;
  989. default:
  990. resolve();
  991. }
  992. }
  993. setTimeout( probe, interval );
  994. } );
  995. }
  996. /**
  997. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  998. * or clipping. Based on W3C specifications for sRGB and Display P3,
  999. * and ICC specifications for the D50 connection space. Values in/out
  1000. * are _linear_ sRGB and _linear_ Display P3.
  1001. *
  1002. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  1003. *
  1004. * Reference:
  1005. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  1006. */
  1007. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  1008. 0.8224621, 0.177538, 0.0,
  1009. 0.0331941, 0.9668058, 0.0,
  1010. 0.0170827, 0.0723974, 0.9105199,
  1011. );
  1012. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  1013. 1.2249401, - 0.2249404, 0.0,
  1014. - 0.0420569, 1.0420571, 0.0,
  1015. - 0.0196376, - 0.0786361, 1.0982735
  1016. );
  1017. /**
  1018. * Defines supported color spaces by transfer function and primaries,
  1019. * and provides conversions to/from the Linear-sRGB reference space.
  1020. */
  1021. const COLOR_SPACES = {
  1022. [ LinearSRGBColorSpace ]: {
  1023. transfer: LinearTransfer,
  1024. primaries: Rec709Primaries,
  1025. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1026. toReference: ( color ) => color,
  1027. fromReference: ( color ) => color,
  1028. },
  1029. [ SRGBColorSpace ]: {
  1030. transfer: SRGBTransfer,
  1031. primaries: Rec709Primaries,
  1032. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1033. toReference: ( color ) => color.convertSRGBToLinear(),
  1034. fromReference: ( color ) => color.convertLinearToSRGB(),
  1035. },
  1036. [ LinearDisplayP3ColorSpace ]: {
  1037. transfer: LinearTransfer,
  1038. primaries: P3Primaries,
  1039. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1040. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1041. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1042. },
  1043. [ DisplayP3ColorSpace ]: {
  1044. transfer: SRGBTransfer,
  1045. primaries: P3Primaries,
  1046. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1047. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1048. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1049. },
  1050. };
  1051. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1052. const ColorManagement = {
  1053. enabled: true,
  1054. _workingColorSpace: LinearSRGBColorSpace,
  1055. get workingColorSpace() {
  1056. return this._workingColorSpace;
  1057. },
  1058. set workingColorSpace( colorSpace ) {
  1059. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1060. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1061. }
  1062. this._workingColorSpace = colorSpace;
  1063. },
  1064. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1065. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1066. return color;
  1067. }
  1068. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1069. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1070. return targetFromReference( sourceToReference( color ) );
  1071. },
  1072. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1073. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1074. },
  1075. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1076. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1077. },
  1078. getPrimaries: function ( colorSpace ) {
  1079. return COLOR_SPACES[ colorSpace ].primaries;
  1080. },
  1081. getTransfer: function ( colorSpace ) {
  1082. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1083. return COLOR_SPACES[ colorSpace ].transfer;
  1084. },
  1085. getLuminanceCoefficients: function ( target, colorSpace = this._workingColorSpace ) {
  1086. return target.fromArray( COLOR_SPACES[ colorSpace ].luminanceCoefficients );
  1087. },
  1088. };
  1089. function SRGBToLinear( c ) {
  1090. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1091. }
  1092. function LinearToSRGB( c ) {
  1093. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1094. }
  1095. let _canvas;
  1096. class ImageUtils {
  1097. static getDataURL( image ) {
  1098. if ( /^data:/i.test( image.src ) ) {
  1099. return image.src;
  1100. }
  1101. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1102. return image.src;
  1103. }
  1104. let canvas;
  1105. if ( image instanceof HTMLCanvasElement ) {
  1106. canvas = image;
  1107. } else {
  1108. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1109. _canvas.width = image.width;
  1110. _canvas.height = image.height;
  1111. const context = _canvas.getContext( '2d' );
  1112. if ( image instanceof ImageData ) {
  1113. context.putImageData( image, 0, 0 );
  1114. } else {
  1115. context.drawImage( image, 0, 0, image.width, image.height );
  1116. }
  1117. canvas = _canvas;
  1118. }
  1119. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1120. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1121. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1122. } else {
  1123. return canvas.toDataURL( 'image/png' );
  1124. }
  1125. }
  1126. static sRGBToLinear( image ) {
  1127. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1128. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1129. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1130. const canvas = createElementNS( 'canvas' );
  1131. canvas.width = image.width;
  1132. canvas.height = image.height;
  1133. const context = canvas.getContext( '2d' );
  1134. context.drawImage( image, 0, 0, image.width, image.height );
  1135. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1136. const data = imageData.data;
  1137. for ( let i = 0; i < data.length; i ++ ) {
  1138. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1139. }
  1140. context.putImageData( imageData, 0, 0 );
  1141. return canvas;
  1142. } else if ( image.data ) {
  1143. const data = image.data.slice( 0 );
  1144. for ( let i = 0; i < data.length; i ++ ) {
  1145. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1146. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1147. } else {
  1148. // assuming float
  1149. data[ i ] = SRGBToLinear( data[ i ] );
  1150. }
  1151. }
  1152. return {
  1153. data: data,
  1154. width: image.width,
  1155. height: image.height
  1156. };
  1157. } else {
  1158. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1159. return image;
  1160. }
  1161. }
  1162. }
  1163. let _sourceId = 0;
  1164. class Source {
  1165. constructor( data = null ) {
  1166. this.isSource = true;
  1167. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1168. this.uuid = generateUUID();
  1169. this.data = data;
  1170. this.dataReady = true;
  1171. this.version = 0;
  1172. }
  1173. set needsUpdate( value ) {
  1174. if ( value === true ) this.version ++;
  1175. }
  1176. toJSON( meta ) {
  1177. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1178. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1179. return meta.images[ this.uuid ];
  1180. }
  1181. const output = {
  1182. uuid: this.uuid,
  1183. url: ''
  1184. };
  1185. const data = this.data;
  1186. if ( data !== null ) {
  1187. let url;
  1188. if ( Array.isArray( data ) ) {
  1189. // cube texture
  1190. url = [];
  1191. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1192. if ( data[ i ].isDataTexture ) {
  1193. url.push( serializeImage( data[ i ].image ) );
  1194. } else {
  1195. url.push( serializeImage( data[ i ] ) );
  1196. }
  1197. }
  1198. } else {
  1199. // texture
  1200. url = serializeImage( data );
  1201. }
  1202. output.url = url;
  1203. }
  1204. if ( ! isRootObject ) {
  1205. meta.images[ this.uuid ] = output;
  1206. }
  1207. return output;
  1208. }
  1209. }
  1210. function serializeImage( image ) {
  1211. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1212. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1213. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1214. // default images
  1215. return ImageUtils.getDataURL( image );
  1216. } else {
  1217. if ( image.data ) {
  1218. // images of DataTexture
  1219. return {
  1220. data: Array.from( image.data ),
  1221. width: image.width,
  1222. height: image.height,
  1223. type: image.data.constructor.name
  1224. };
  1225. } else {
  1226. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1227. return {};
  1228. }
  1229. }
  1230. }
  1231. let _textureId = 0;
  1232. class Texture extends EventDispatcher {
  1233. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1234. super();
  1235. this.isTexture = true;
  1236. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1237. this.uuid = generateUUID();
  1238. this.name = '';
  1239. this.source = new Source( image );
  1240. this.mipmaps = [];
  1241. this.mapping = mapping;
  1242. this.channel = 0;
  1243. this.wrapS = wrapS;
  1244. this.wrapT = wrapT;
  1245. this.magFilter = magFilter;
  1246. this.minFilter = minFilter;
  1247. this.anisotropy = anisotropy;
  1248. this.format = format;
  1249. this.internalFormat = null;
  1250. this.type = type;
  1251. this.offset = new Vector2( 0, 0 );
  1252. this.repeat = new Vector2( 1, 1 );
  1253. this.center = new Vector2( 0, 0 );
  1254. this.rotation = 0;
  1255. this.matrixAutoUpdate = true;
  1256. this.matrix = new Matrix3();
  1257. this.generateMipmaps = true;
  1258. this.premultiplyAlpha = false;
  1259. this.flipY = true;
  1260. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1261. this.colorSpace = colorSpace;
  1262. this.userData = {};
  1263. this.version = 0;
  1264. this.onUpdate = null;
  1265. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1266. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1267. }
  1268. get image() {
  1269. return this.source.data;
  1270. }
  1271. set image( value = null ) {
  1272. this.source.data = value;
  1273. }
  1274. updateMatrix() {
  1275. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1276. }
  1277. clone() {
  1278. return new this.constructor().copy( this );
  1279. }
  1280. copy( source ) {
  1281. this.name = source.name;
  1282. this.source = source.source;
  1283. this.mipmaps = source.mipmaps.slice( 0 );
  1284. this.mapping = source.mapping;
  1285. this.channel = source.channel;
  1286. this.wrapS = source.wrapS;
  1287. this.wrapT = source.wrapT;
  1288. this.magFilter = source.magFilter;
  1289. this.minFilter = source.minFilter;
  1290. this.anisotropy = source.anisotropy;
  1291. this.format = source.format;
  1292. this.internalFormat = source.internalFormat;
  1293. this.type = source.type;
  1294. this.offset.copy( source.offset );
  1295. this.repeat.copy( source.repeat );
  1296. this.center.copy( source.center );
  1297. this.rotation = source.rotation;
  1298. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1299. this.matrix.copy( source.matrix );
  1300. this.generateMipmaps = source.generateMipmaps;
  1301. this.premultiplyAlpha = source.premultiplyAlpha;
  1302. this.flipY = source.flipY;
  1303. this.unpackAlignment = source.unpackAlignment;
  1304. this.colorSpace = source.colorSpace;
  1305. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1306. this.needsUpdate = true;
  1307. return this;
  1308. }
  1309. toJSON( meta ) {
  1310. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1311. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1312. return meta.textures[ this.uuid ];
  1313. }
  1314. const output = {
  1315. metadata: {
  1316. version: 4.6,
  1317. type: 'Texture',
  1318. generator: 'Texture.toJSON'
  1319. },
  1320. uuid: this.uuid,
  1321. name: this.name,
  1322. image: this.source.toJSON( meta ).uuid,
  1323. mapping: this.mapping,
  1324. channel: this.channel,
  1325. repeat: [ this.repeat.x, this.repeat.y ],
  1326. offset: [ this.offset.x, this.offset.y ],
  1327. center: [ this.center.x, this.center.y ],
  1328. rotation: this.rotation,
  1329. wrap: [ this.wrapS, this.wrapT ],
  1330. format: this.format,
  1331. internalFormat: this.internalFormat,
  1332. type: this.type,
  1333. colorSpace: this.colorSpace,
  1334. minFilter: this.minFilter,
  1335. magFilter: this.magFilter,
  1336. anisotropy: this.anisotropy,
  1337. flipY: this.flipY,
  1338. generateMipmaps: this.generateMipmaps,
  1339. premultiplyAlpha: this.premultiplyAlpha,
  1340. unpackAlignment: this.unpackAlignment
  1341. };
  1342. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1343. if ( ! isRootObject ) {
  1344. meta.textures[ this.uuid ] = output;
  1345. }
  1346. return output;
  1347. }
  1348. dispose() {
  1349. this.dispatchEvent( { type: 'dispose' } );
  1350. }
  1351. transformUv( uv ) {
  1352. if ( this.mapping !== UVMapping ) return uv;
  1353. uv.applyMatrix3( this.matrix );
  1354. if ( uv.x < 0 || uv.x > 1 ) {
  1355. switch ( this.wrapS ) {
  1356. case RepeatWrapping:
  1357. uv.x = uv.x - Math.floor( uv.x );
  1358. break;
  1359. case ClampToEdgeWrapping:
  1360. uv.x = uv.x < 0 ? 0 : 1;
  1361. break;
  1362. case MirroredRepeatWrapping:
  1363. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1364. uv.x = Math.ceil( uv.x ) - uv.x;
  1365. } else {
  1366. uv.x = uv.x - Math.floor( uv.x );
  1367. }
  1368. break;
  1369. }
  1370. }
  1371. if ( uv.y < 0 || uv.y > 1 ) {
  1372. switch ( this.wrapT ) {
  1373. case RepeatWrapping:
  1374. uv.y = uv.y - Math.floor( uv.y );
  1375. break;
  1376. case ClampToEdgeWrapping:
  1377. uv.y = uv.y < 0 ? 0 : 1;
  1378. break;
  1379. case MirroredRepeatWrapping:
  1380. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1381. uv.y = Math.ceil( uv.y ) - uv.y;
  1382. } else {
  1383. uv.y = uv.y - Math.floor( uv.y );
  1384. }
  1385. break;
  1386. }
  1387. }
  1388. if ( this.flipY ) {
  1389. uv.y = 1 - uv.y;
  1390. }
  1391. return uv;
  1392. }
  1393. set needsUpdate( value ) {
  1394. if ( value === true ) {
  1395. this.version ++;
  1396. this.source.needsUpdate = true;
  1397. }
  1398. }
  1399. set needsPMREMUpdate( value ) {
  1400. if ( value === true ) {
  1401. this.pmremVersion ++;
  1402. }
  1403. }
  1404. }
  1405. Texture.DEFAULT_IMAGE = null;
  1406. Texture.DEFAULT_MAPPING = UVMapping;
  1407. Texture.DEFAULT_ANISOTROPY = 1;
  1408. class Vector4 {
  1409. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1410. Vector4.prototype.isVector4 = true;
  1411. this.x = x;
  1412. this.y = y;
  1413. this.z = z;
  1414. this.w = w;
  1415. }
  1416. get width() {
  1417. return this.z;
  1418. }
  1419. set width( value ) {
  1420. this.z = value;
  1421. }
  1422. get height() {
  1423. return this.w;
  1424. }
  1425. set height( value ) {
  1426. this.w = value;
  1427. }
  1428. set( x, y, z, w ) {
  1429. this.x = x;
  1430. this.y = y;
  1431. this.z = z;
  1432. this.w = w;
  1433. return this;
  1434. }
  1435. setScalar( scalar ) {
  1436. this.x = scalar;
  1437. this.y = scalar;
  1438. this.z = scalar;
  1439. this.w = scalar;
  1440. return this;
  1441. }
  1442. setX( x ) {
  1443. this.x = x;
  1444. return this;
  1445. }
  1446. setY( y ) {
  1447. this.y = y;
  1448. return this;
  1449. }
  1450. setZ( z ) {
  1451. this.z = z;
  1452. return this;
  1453. }
  1454. setW( w ) {
  1455. this.w = w;
  1456. return this;
  1457. }
  1458. setComponent( index, value ) {
  1459. switch ( index ) {
  1460. case 0: this.x = value; break;
  1461. case 1: this.y = value; break;
  1462. case 2: this.z = value; break;
  1463. case 3: this.w = value; break;
  1464. default: throw new Error( 'index is out of range: ' + index );
  1465. }
  1466. return this;
  1467. }
  1468. getComponent( index ) {
  1469. switch ( index ) {
  1470. case 0: return this.x;
  1471. case 1: return this.y;
  1472. case 2: return this.z;
  1473. case 3: return this.w;
  1474. default: throw new Error( 'index is out of range: ' + index );
  1475. }
  1476. }
  1477. clone() {
  1478. return new this.constructor( this.x, this.y, this.z, this.w );
  1479. }
  1480. copy( v ) {
  1481. this.x = v.x;
  1482. this.y = v.y;
  1483. this.z = v.z;
  1484. this.w = ( v.w !== undefined ) ? v.w : 1;
  1485. return this;
  1486. }
  1487. add( v ) {
  1488. this.x += v.x;
  1489. this.y += v.y;
  1490. this.z += v.z;
  1491. this.w += v.w;
  1492. return this;
  1493. }
  1494. addScalar( s ) {
  1495. this.x += s;
  1496. this.y += s;
  1497. this.z += s;
  1498. this.w += s;
  1499. return this;
  1500. }
  1501. addVectors( a, b ) {
  1502. this.x = a.x + b.x;
  1503. this.y = a.y + b.y;
  1504. this.z = a.z + b.z;
  1505. this.w = a.w + b.w;
  1506. return this;
  1507. }
  1508. addScaledVector( v, s ) {
  1509. this.x += v.x * s;
  1510. this.y += v.y * s;
  1511. this.z += v.z * s;
  1512. this.w += v.w * s;
  1513. return this;
  1514. }
  1515. sub( v ) {
  1516. this.x -= v.x;
  1517. this.y -= v.y;
  1518. this.z -= v.z;
  1519. this.w -= v.w;
  1520. return this;
  1521. }
  1522. subScalar( s ) {
  1523. this.x -= s;
  1524. this.y -= s;
  1525. this.z -= s;
  1526. this.w -= s;
  1527. return this;
  1528. }
  1529. subVectors( a, b ) {
  1530. this.x = a.x - b.x;
  1531. this.y = a.y - b.y;
  1532. this.z = a.z - b.z;
  1533. this.w = a.w - b.w;
  1534. return this;
  1535. }
  1536. multiply( v ) {
  1537. this.x *= v.x;
  1538. this.y *= v.y;
  1539. this.z *= v.z;
  1540. this.w *= v.w;
  1541. return this;
  1542. }
  1543. multiplyScalar( scalar ) {
  1544. this.x *= scalar;
  1545. this.y *= scalar;
  1546. this.z *= scalar;
  1547. this.w *= scalar;
  1548. return this;
  1549. }
  1550. applyMatrix4( m ) {
  1551. const x = this.x, y = this.y, z = this.z, w = this.w;
  1552. const e = m.elements;
  1553. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1554. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1555. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1556. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1557. return this;
  1558. }
  1559. divideScalar( scalar ) {
  1560. return this.multiplyScalar( 1 / scalar );
  1561. }
  1562. setAxisAngleFromQuaternion( q ) {
  1563. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1564. // q is assumed to be normalized
  1565. this.w = 2 * Math.acos( q.w );
  1566. const s = Math.sqrt( 1 - q.w * q.w );
  1567. if ( s < 0.0001 ) {
  1568. this.x = 1;
  1569. this.y = 0;
  1570. this.z = 0;
  1571. } else {
  1572. this.x = q.x / s;
  1573. this.y = q.y / s;
  1574. this.z = q.z / s;
  1575. }
  1576. return this;
  1577. }
  1578. setAxisAngleFromRotationMatrix( m ) {
  1579. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1580. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1581. let angle, x, y, z; // variables for result
  1582. const epsilon = 0.01, // margin to allow for rounding errors
  1583. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1584. te = m.elements,
  1585. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1586. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1587. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1588. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1589. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1590. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1591. // singularity found
  1592. // first check for identity matrix which must have +1 for all terms
  1593. // in leading diagonal and zero in other terms
  1594. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1595. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1596. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1597. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1598. // this singularity is identity matrix so angle = 0
  1599. this.set( 1, 0, 0, 0 );
  1600. return this; // zero angle, arbitrary axis
  1601. }
  1602. // otherwise this singularity is angle = 180
  1603. angle = Math.PI;
  1604. const xx = ( m11 + 1 ) / 2;
  1605. const yy = ( m22 + 1 ) / 2;
  1606. const zz = ( m33 + 1 ) / 2;
  1607. const xy = ( m12 + m21 ) / 4;
  1608. const xz = ( m13 + m31 ) / 4;
  1609. const yz = ( m23 + m32 ) / 4;
  1610. if ( ( xx > yy ) && ( xx > zz ) ) {
  1611. // m11 is the largest diagonal term
  1612. if ( xx < epsilon ) {
  1613. x = 0;
  1614. y = 0.707106781;
  1615. z = 0.707106781;
  1616. } else {
  1617. x = Math.sqrt( xx );
  1618. y = xy / x;
  1619. z = xz / x;
  1620. }
  1621. } else if ( yy > zz ) {
  1622. // m22 is the largest diagonal term
  1623. if ( yy < epsilon ) {
  1624. x = 0.707106781;
  1625. y = 0;
  1626. z = 0.707106781;
  1627. } else {
  1628. y = Math.sqrt( yy );
  1629. x = xy / y;
  1630. z = yz / y;
  1631. }
  1632. } else {
  1633. // m33 is the largest diagonal term so base result on this
  1634. if ( zz < epsilon ) {
  1635. x = 0.707106781;
  1636. y = 0.707106781;
  1637. z = 0;
  1638. } else {
  1639. z = Math.sqrt( zz );
  1640. x = xz / z;
  1641. y = yz / z;
  1642. }
  1643. }
  1644. this.set( x, y, z, angle );
  1645. return this; // return 180 deg rotation
  1646. }
  1647. // as we have reached here there are no singularities so we can handle normally
  1648. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1649. ( m13 - m31 ) * ( m13 - m31 ) +
  1650. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1651. if ( Math.abs( s ) < 0.001 ) s = 1;
  1652. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1653. // caught by singularity test above, but I've left it in just in case
  1654. this.x = ( m32 - m23 ) / s;
  1655. this.y = ( m13 - m31 ) / s;
  1656. this.z = ( m21 - m12 ) / s;
  1657. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1658. return this;
  1659. }
  1660. setFromMatrixPosition( m ) {
  1661. const e = m.elements;
  1662. this.x = e[ 12 ];
  1663. this.y = e[ 13 ];
  1664. this.z = e[ 14 ];
  1665. this.w = e[ 15 ];
  1666. return this;
  1667. }
  1668. min( v ) {
  1669. this.x = Math.min( this.x, v.x );
  1670. this.y = Math.min( this.y, v.y );
  1671. this.z = Math.min( this.z, v.z );
  1672. this.w = Math.min( this.w, v.w );
  1673. return this;
  1674. }
  1675. max( v ) {
  1676. this.x = Math.max( this.x, v.x );
  1677. this.y = Math.max( this.y, v.y );
  1678. this.z = Math.max( this.z, v.z );
  1679. this.w = Math.max( this.w, v.w );
  1680. return this;
  1681. }
  1682. clamp( min, max ) {
  1683. // assumes min < max, componentwise
  1684. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1685. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1686. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1687. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1688. return this;
  1689. }
  1690. clampScalar( minVal, maxVal ) {
  1691. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1692. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1693. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1694. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1695. return this;
  1696. }
  1697. clampLength( min, max ) {
  1698. const length = this.length();
  1699. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1700. }
  1701. floor() {
  1702. this.x = Math.floor( this.x );
  1703. this.y = Math.floor( this.y );
  1704. this.z = Math.floor( this.z );
  1705. this.w = Math.floor( this.w );
  1706. return this;
  1707. }
  1708. ceil() {
  1709. this.x = Math.ceil( this.x );
  1710. this.y = Math.ceil( this.y );
  1711. this.z = Math.ceil( this.z );
  1712. this.w = Math.ceil( this.w );
  1713. return this;
  1714. }
  1715. round() {
  1716. this.x = Math.round( this.x );
  1717. this.y = Math.round( this.y );
  1718. this.z = Math.round( this.z );
  1719. this.w = Math.round( this.w );
  1720. return this;
  1721. }
  1722. roundToZero() {
  1723. this.x = Math.trunc( this.x );
  1724. this.y = Math.trunc( this.y );
  1725. this.z = Math.trunc( this.z );
  1726. this.w = Math.trunc( this.w );
  1727. return this;
  1728. }
  1729. negate() {
  1730. this.x = - this.x;
  1731. this.y = - this.y;
  1732. this.z = - this.z;
  1733. this.w = - this.w;
  1734. return this;
  1735. }
  1736. dot( v ) {
  1737. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1738. }
  1739. lengthSq() {
  1740. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1741. }
  1742. length() {
  1743. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1744. }
  1745. manhattanLength() {
  1746. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1747. }
  1748. normalize() {
  1749. return this.divideScalar( this.length() || 1 );
  1750. }
  1751. setLength( length ) {
  1752. return this.normalize().multiplyScalar( length );
  1753. }
  1754. lerp( v, alpha ) {
  1755. this.x += ( v.x - this.x ) * alpha;
  1756. this.y += ( v.y - this.y ) * alpha;
  1757. this.z += ( v.z - this.z ) * alpha;
  1758. this.w += ( v.w - this.w ) * alpha;
  1759. return this;
  1760. }
  1761. lerpVectors( v1, v2, alpha ) {
  1762. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1763. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1764. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1765. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1766. return this;
  1767. }
  1768. equals( v ) {
  1769. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1770. }
  1771. fromArray( array, offset = 0 ) {
  1772. this.x = array[ offset ];
  1773. this.y = array[ offset + 1 ];
  1774. this.z = array[ offset + 2 ];
  1775. this.w = array[ offset + 3 ];
  1776. return this;
  1777. }
  1778. toArray( array = [], offset = 0 ) {
  1779. array[ offset ] = this.x;
  1780. array[ offset + 1 ] = this.y;
  1781. array[ offset + 2 ] = this.z;
  1782. array[ offset + 3 ] = this.w;
  1783. return array;
  1784. }
  1785. fromBufferAttribute( attribute, index ) {
  1786. this.x = attribute.getX( index );
  1787. this.y = attribute.getY( index );
  1788. this.z = attribute.getZ( index );
  1789. this.w = attribute.getW( index );
  1790. return this;
  1791. }
  1792. random() {
  1793. this.x = Math.random();
  1794. this.y = Math.random();
  1795. this.z = Math.random();
  1796. this.w = Math.random();
  1797. return this;
  1798. }
  1799. *[ Symbol.iterator ]() {
  1800. yield this.x;
  1801. yield this.y;
  1802. yield this.z;
  1803. yield this.w;
  1804. }
  1805. }
  1806. /*
  1807. In options, we can specify:
  1808. * Texture parameters for an auto-generated target texture
  1809. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1810. */
  1811. class RenderTarget extends EventDispatcher {
  1812. constructor( width = 1, height = 1, options = {} ) {
  1813. super();
  1814. this.isRenderTarget = true;
  1815. this.width = width;
  1816. this.height = height;
  1817. this.depth = 1;
  1818. this.scissor = new Vector4( 0, 0, width, height );
  1819. this.scissorTest = false;
  1820. this.viewport = new Vector4( 0, 0, width, height );
  1821. const image = { width: width, height: height, depth: 1 };
  1822. options = Object.assign( {
  1823. generateMipmaps: false,
  1824. internalFormat: null,
  1825. minFilter: LinearFilter,
  1826. depthBuffer: true,
  1827. stencilBuffer: false,
  1828. resolveDepthBuffer: true,
  1829. resolveStencilBuffer: true,
  1830. depthTexture: null,
  1831. samples: 0,
  1832. count: 1
  1833. }, options );
  1834. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1835. texture.flipY = false;
  1836. texture.generateMipmaps = options.generateMipmaps;
  1837. texture.internalFormat = options.internalFormat;
  1838. this.textures = [];
  1839. const count = options.count;
  1840. for ( let i = 0; i < count; i ++ ) {
  1841. this.textures[ i ] = texture.clone();
  1842. this.textures[ i ].isRenderTargetTexture = true;
  1843. }
  1844. this.depthBuffer = options.depthBuffer;
  1845. this.stencilBuffer = options.stencilBuffer;
  1846. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1847. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1848. this.depthTexture = options.depthTexture;
  1849. this.samples = options.samples;
  1850. }
  1851. get texture() {
  1852. return this.textures[ 0 ];
  1853. }
  1854. set texture( value ) {
  1855. this.textures[ 0 ] = value;
  1856. }
  1857. setSize( width, height, depth = 1 ) {
  1858. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1859. this.width = width;
  1860. this.height = height;
  1861. this.depth = depth;
  1862. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1863. this.textures[ i ].image.width = width;
  1864. this.textures[ i ].image.height = height;
  1865. this.textures[ i ].image.depth = depth;
  1866. }
  1867. this.dispose();
  1868. }
  1869. this.viewport.set( 0, 0, width, height );
  1870. this.scissor.set( 0, 0, width, height );
  1871. }
  1872. clone() {
  1873. return new this.constructor().copy( this );
  1874. }
  1875. copy( source ) {
  1876. this.width = source.width;
  1877. this.height = source.height;
  1878. this.depth = source.depth;
  1879. this.scissor.copy( source.scissor );
  1880. this.scissorTest = source.scissorTest;
  1881. this.viewport.copy( source.viewport );
  1882. this.textures.length = 0;
  1883. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1884. this.textures[ i ] = source.textures[ i ].clone();
  1885. this.textures[ i ].isRenderTargetTexture = true;
  1886. }
  1887. // ensure image object is not shared, see #20328
  1888. const image = Object.assign( {}, source.texture.image );
  1889. this.texture.source = new Source( image );
  1890. this.depthBuffer = source.depthBuffer;
  1891. this.stencilBuffer = source.stencilBuffer;
  1892. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1893. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1894. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1895. this.samples = source.samples;
  1896. return this;
  1897. }
  1898. dispose() {
  1899. this.dispatchEvent( { type: 'dispose' } );
  1900. }
  1901. }
  1902. class WebGLRenderTarget extends RenderTarget {
  1903. constructor( width = 1, height = 1, options = {} ) {
  1904. super( width, height, options );
  1905. this.isWebGLRenderTarget = true;
  1906. }
  1907. }
  1908. class DataArrayTexture extends Texture {
  1909. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1910. super( null );
  1911. this.isDataArrayTexture = true;
  1912. this.image = { data, width, height, depth };
  1913. this.magFilter = NearestFilter;
  1914. this.minFilter = NearestFilter;
  1915. this.wrapR = ClampToEdgeWrapping;
  1916. this.generateMipmaps = false;
  1917. this.flipY = false;
  1918. this.unpackAlignment = 1;
  1919. this.layerUpdates = new Set();
  1920. }
  1921. addLayerUpdate( layerIndex ) {
  1922. this.layerUpdates.add( layerIndex );
  1923. }
  1924. clearLayerUpdates() {
  1925. this.layerUpdates.clear();
  1926. }
  1927. }
  1928. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1929. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1930. super( width, height, options );
  1931. this.isWebGLArrayRenderTarget = true;
  1932. this.depth = depth;
  1933. this.texture = new DataArrayTexture( null, width, height, depth );
  1934. this.texture.isRenderTargetTexture = true;
  1935. }
  1936. }
  1937. class Data3DTexture extends Texture {
  1938. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1939. // We're going to add .setXXX() methods for setting properties later.
  1940. // Users can still set in DataTexture3D directly.
  1941. //
  1942. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1943. // texture.anisotropy = 16;
  1944. //
  1945. // See #14839
  1946. super( null );
  1947. this.isData3DTexture = true;
  1948. this.image = { data, width, height, depth };
  1949. this.magFilter = NearestFilter;
  1950. this.minFilter = NearestFilter;
  1951. this.wrapR = ClampToEdgeWrapping;
  1952. this.generateMipmaps = false;
  1953. this.flipY = false;
  1954. this.unpackAlignment = 1;
  1955. }
  1956. }
  1957. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1958. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1959. super( width, height, options );
  1960. this.isWebGL3DRenderTarget = true;
  1961. this.depth = depth;
  1962. this.texture = new Data3DTexture( null, width, height, depth );
  1963. this.texture.isRenderTargetTexture = true;
  1964. }
  1965. }
  1966. class Quaternion {
  1967. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1968. this.isQuaternion = true;
  1969. this._x = x;
  1970. this._y = y;
  1971. this._z = z;
  1972. this._w = w;
  1973. }
  1974. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1975. // fuzz-free, array-based Quaternion SLERP operation
  1976. let x0 = src0[ srcOffset0 + 0 ],
  1977. y0 = src0[ srcOffset0 + 1 ],
  1978. z0 = src0[ srcOffset0 + 2 ],
  1979. w0 = src0[ srcOffset0 + 3 ];
  1980. const x1 = src1[ srcOffset1 + 0 ],
  1981. y1 = src1[ srcOffset1 + 1 ],
  1982. z1 = src1[ srcOffset1 + 2 ],
  1983. w1 = src1[ srcOffset1 + 3 ];
  1984. if ( t === 0 ) {
  1985. dst[ dstOffset + 0 ] = x0;
  1986. dst[ dstOffset + 1 ] = y0;
  1987. dst[ dstOffset + 2 ] = z0;
  1988. dst[ dstOffset + 3 ] = w0;
  1989. return;
  1990. }
  1991. if ( t === 1 ) {
  1992. dst[ dstOffset + 0 ] = x1;
  1993. dst[ dstOffset + 1 ] = y1;
  1994. dst[ dstOffset + 2 ] = z1;
  1995. dst[ dstOffset + 3 ] = w1;
  1996. return;
  1997. }
  1998. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1999. let s = 1 - t;
  2000. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2001. dir = ( cos >= 0 ? 1 : - 1 ),
  2002. sqrSin = 1 - cos * cos;
  2003. // Skip the Slerp for tiny steps to avoid numeric problems:
  2004. if ( sqrSin > Number.EPSILON ) {
  2005. const sin = Math.sqrt( sqrSin ),
  2006. len = Math.atan2( sin, cos * dir );
  2007. s = Math.sin( s * len ) / sin;
  2008. t = Math.sin( t * len ) / sin;
  2009. }
  2010. const tDir = t * dir;
  2011. x0 = x0 * s + x1 * tDir;
  2012. y0 = y0 * s + y1 * tDir;
  2013. z0 = z0 * s + z1 * tDir;
  2014. w0 = w0 * s + w1 * tDir;
  2015. // Normalize in case we just did a lerp:
  2016. if ( s === 1 - t ) {
  2017. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2018. x0 *= f;
  2019. y0 *= f;
  2020. z0 *= f;
  2021. w0 *= f;
  2022. }
  2023. }
  2024. dst[ dstOffset ] = x0;
  2025. dst[ dstOffset + 1 ] = y0;
  2026. dst[ dstOffset + 2 ] = z0;
  2027. dst[ dstOffset + 3 ] = w0;
  2028. }
  2029. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2030. const x0 = src0[ srcOffset0 ];
  2031. const y0 = src0[ srcOffset0 + 1 ];
  2032. const z0 = src0[ srcOffset0 + 2 ];
  2033. const w0 = src0[ srcOffset0 + 3 ];
  2034. const x1 = src1[ srcOffset1 ];
  2035. const y1 = src1[ srcOffset1 + 1 ];
  2036. const z1 = src1[ srcOffset1 + 2 ];
  2037. const w1 = src1[ srcOffset1 + 3 ];
  2038. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2039. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2040. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2041. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2042. return dst;
  2043. }
  2044. get x() {
  2045. return this._x;
  2046. }
  2047. set x( value ) {
  2048. this._x = value;
  2049. this._onChangeCallback();
  2050. }
  2051. get y() {
  2052. return this._y;
  2053. }
  2054. set y( value ) {
  2055. this._y = value;
  2056. this._onChangeCallback();
  2057. }
  2058. get z() {
  2059. return this._z;
  2060. }
  2061. set z( value ) {
  2062. this._z = value;
  2063. this._onChangeCallback();
  2064. }
  2065. get w() {
  2066. return this._w;
  2067. }
  2068. set w( value ) {
  2069. this._w = value;
  2070. this._onChangeCallback();
  2071. }
  2072. set( x, y, z, w ) {
  2073. this._x = x;
  2074. this._y = y;
  2075. this._z = z;
  2076. this._w = w;
  2077. this._onChangeCallback();
  2078. return this;
  2079. }
  2080. clone() {
  2081. return new this.constructor( this._x, this._y, this._z, this._w );
  2082. }
  2083. copy( quaternion ) {
  2084. this._x = quaternion.x;
  2085. this._y = quaternion.y;
  2086. this._z = quaternion.z;
  2087. this._w = quaternion.w;
  2088. this._onChangeCallback();
  2089. return this;
  2090. }
  2091. setFromEuler( euler, update = true ) {
  2092. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2093. // http://www.mathworks.com/matlabcentral/fileexchange/
  2094. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2095. // content/SpinCalc.m
  2096. const cos = Math.cos;
  2097. const sin = Math.sin;
  2098. const c1 = cos( x / 2 );
  2099. const c2 = cos( y / 2 );
  2100. const c3 = cos( z / 2 );
  2101. const s1 = sin( x / 2 );
  2102. const s2 = sin( y / 2 );
  2103. const s3 = sin( z / 2 );
  2104. switch ( order ) {
  2105. case 'XYZ':
  2106. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2107. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2108. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2109. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2110. break;
  2111. case 'YXZ':
  2112. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2113. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2114. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2115. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2116. break;
  2117. case 'ZXY':
  2118. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2119. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2120. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2121. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2122. break;
  2123. case 'ZYX':
  2124. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2125. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2126. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2127. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2128. break;
  2129. case 'YZX':
  2130. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2131. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2132. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2133. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2134. break;
  2135. case 'XZY':
  2136. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2137. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2138. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2139. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2140. break;
  2141. default:
  2142. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2143. }
  2144. if ( update === true ) this._onChangeCallback();
  2145. return this;
  2146. }
  2147. setFromAxisAngle( axis, angle ) {
  2148. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2149. // assumes axis is normalized
  2150. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2151. this._x = axis.x * s;
  2152. this._y = axis.y * s;
  2153. this._z = axis.z * s;
  2154. this._w = Math.cos( halfAngle );
  2155. this._onChangeCallback();
  2156. return this;
  2157. }
  2158. setFromRotationMatrix( m ) {
  2159. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2160. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2161. const te = m.elements,
  2162. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2163. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2164. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2165. trace = m11 + m22 + m33;
  2166. if ( trace > 0 ) {
  2167. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2168. this._w = 0.25 / s;
  2169. this._x = ( m32 - m23 ) * s;
  2170. this._y = ( m13 - m31 ) * s;
  2171. this._z = ( m21 - m12 ) * s;
  2172. } else if ( m11 > m22 && m11 > m33 ) {
  2173. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2174. this._w = ( m32 - m23 ) / s;
  2175. this._x = 0.25 * s;
  2176. this._y = ( m12 + m21 ) / s;
  2177. this._z = ( m13 + m31 ) / s;
  2178. } else if ( m22 > m33 ) {
  2179. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2180. this._w = ( m13 - m31 ) / s;
  2181. this._x = ( m12 + m21 ) / s;
  2182. this._y = 0.25 * s;
  2183. this._z = ( m23 + m32 ) / s;
  2184. } else {
  2185. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2186. this._w = ( m21 - m12 ) / s;
  2187. this._x = ( m13 + m31 ) / s;
  2188. this._y = ( m23 + m32 ) / s;
  2189. this._z = 0.25 * s;
  2190. }
  2191. this._onChangeCallback();
  2192. return this;
  2193. }
  2194. setFromUnitVectors( vFrom, vTo ) {
  2195. // assumes direction vectors vFrom and vTo are normalized
  2196. let r = vFrom.dot( vTo ) + 1;
  2197. if ( r < Number.EPSILON ) {
  2198. // vFrom and vTo point in opposite directions
  2199. r = 0;
  2200. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2201. this._x = - vFrom.y;
  2202. this._y = vFrom.x;
  2203. this._z = 0;
  2204. this._w = r;
  2205. } else {
  2206. this._x = 0;
  2207. this._y = - vFrom.z;
  2208. this._z = vFrom.y;
  2209. this._w = r;
  2210. }
  2211. } else {
  2212. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2213. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2214. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2215. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2216. this._w = r;
  2217. }
  2218. return this.normalize();
  2219. }
  2220. angleTo( q ) {
  2221. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2222. }
  2223. rotateTowards( q, step ) {
  2224. const angle = this.angleTo( q );
  2225. if ( angle === 0 ) return this;
  2226. const t = Math.min( 1, step / angle );
  2227. this.slerp( q, t );
  2228. return this;
  2229. }
  2230. identity() {
  2231. return this.set( 0, 0, 0, 1 );
  2232. }
  2233. invert() {
  2234. // quaternion is assumed to have unit length
  2235. return this.conjugate();
  2236. }
  2237. conjugate() {
  2238. this._x *= - 1;
  2239. this._y *= - 1;
  2240. this._z *= - 1;
  2241. this._onChangeCallback();
  2242. return this;
  2243. }
  2244. dot( v ) {
  2245. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2246. }
  2247. lengthSq() {
  2248. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2249. }
  2250. length() {
  2251. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2252. }
  2253. normalize() {
  2254. let l = this.length();
  2255. if ( l === 0 ) {
  2256. this._x = 0;
  2257. this._y = 0;
  2258. this._z = 0;
  2259. this._w = 1;
  2260. } else {
  2261. l = 1 / l;
  2262. this._x = this._x * l;
  2263. this._y = this._y * l;
  2264. this._z = this._z * l;
  2265. this._w = this._w * l;
  2266. }
  2267. this._onChangeCallback();
  2268. return this;
  2269. }
  2270. multiply( q ) {
  2271. return this.multiplyQuaternions( this, q );
  2272. }
  2273. premultiply( q ) {
  2274. return this.multiplyQuaternions( q, this );
  2275. }
  2276. multiplyQuaternions( a, b ) {
  2277. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2278. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2279. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2280. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2281. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2282. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2283. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2284. this._onChangeCallback();
  2285. return this;
  2286. }
  2287. slerp( qb, t ) {
  2288. if ( t === 0 ) return this;
  2289. if ( t === 1 ) return this.copy( qb );
  2290. const x = this._x, y = this._y, z = this._z, w = this._w;
  2291. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2292. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2293. if ( cosHalfTheta < 0 ) {
  2294. this._w = - qb._w;
  2295. this._x = - qb._x;
  2296. this._y = - qb._y;
  2297. this._z = - qb._z;
  2298. cosHalfTheta = - cosHalfTheta;
  2299. } else {
  2300. this.copy( qb );
  2301. }
  2302. if ( cosHalfTheta >= 1.0 ) {
  2303. this._w = w;
  2304. this._x = x;
  2305. this._y = y;
  2306. this._z = z;
  2307. return this;
  2308. }
  2309. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2310. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2311. const s = 1 - t;
  2312. this._w = s * w + t * this._w;
  2313. this._x = s * x + t * this._x;
  2314. this._y = s * y + t * this._y;
  2315. this._z = s * z + t * this._z;
  2316. this.normalize(); // normalize calls _onChangeCallback()
  2317. return this;
  2318. }
  2319. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2320. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2321. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2322. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2323. this._w = ( w * ratioA + this._w * ratioB );
  2324. this._x = ( x * ratioA + this._x * ratioB );
  2325. this._y = ( y * ratioA + this._y * ratioB );
  2326. this._z = ( z * ratioA + this._z * ratioB );
  2327. this._onChangeCallback();
  2328. return this;
  2329. }
  2330. slerpQuaternions( qa, qb, t ) {
  2331. return this.copy( qa ).slerp( qb, t );
  2332. }
  2333. random() {
  2334. // sets this quaternion to a uniform random unit quaternnion
  2335. // Ken Shoemake
  2336. // Uniform random rotations
  2337. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2338. const theta1 = 2 * Math.PI * Math.random();
  2339. const theta2 = 2 * Math.PI * Math.random();
  2340. const x0 = Math.random();
  2341. const r1 = Math.sqrt( 1 - x0 );
  2342. const r2 = Math.sqrt( x0 );
  2343. return this.set(
  2344. r1 * Math.sin( theta1 ),
  2345. r1 * Math.cos( theta1 ),
  2346. r2 * Math.sin( theta2 ),
  2347. r2 * Math.cos( theta2 ),
  2348. );
  2349. }
  2350. equals( quaternion ) {
  2351. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2352. }
  2353. fromArray( array, offset = 0 ) {
  2354. this._x = array[ offset ];
  2355. this._y = array[ offset + 1 ];
  2356. this._z = array[ offset + 2 ];
  2357. this._w = array[ offset + 3 ];
  2358. this._onChangeCallback();
  2359. return this;
  2360. }
  2361. toArray( array = [], offset = 0 ) {
  2362. array[ offset ] = this._x;
  2363. array[ offset + 1 ] = this._y;
  2364. array[ offset + 2 ] = this._z;
  2365. array[ offset + 3 ] = this._w;
  2366. return array;
  2367. }
  2368. fromBufferAttribute( attribute, index ) {
  2369. this._x = attribute.getX( index );
  2370. this._y = attribute.getY( index );
  2371. this._z = attribute.getZ( index );
  2372. this._w = attribute.getW( index );
  2373. this._onChangeCallback();
  2374. return this;
  2375. }
  2376. toJSON() {
  2377. return this.toArray();
  2378. }
  2379. _onChange( callback ) {
  2380. this._onChangeCallback = callback;
  2381. return this;
  2382. }
  2383. _onChangeCallback() {}
  2384. *[ Symbol.iterator ]() {
  2385. yield this._x;
  2386. yield this._y;
  2387. yield this._z;
  2388. yield this._w;
  2389. }
  2390. }
  2391. class Vector3 {
  2392. constructor( x = 0, y = 0, z = 0 ) {
  2393. Vector3.prototype.isVector3 = true;
  2394. this.x = x;
  2395. this.y = y;
  2396. this.z = z;
  2397. }
  2398. set( x, y, z ) {
  2399. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2400. this.x = x;
  2401. this.y = y;
  2402. this.z = z;
  2403. return this;
  2404. }
  2405. setScalar( scalar ) {
  2406. this.x = scalar;
  2407. this.y = scalar;
  2408. this.z = scalar;
  2409. return this;
  2410. }
  2411. setX( x ) {
  2412. this.x = x;
  2413. return this;
  2414. }
  2415. setY( y ) {
  2416. this.y = y;
  2417. return this;
  2418. }
  2419. setZ( z ) {
  2420. this.z = z;
  2421. return this;
  2422. }
  2423. setComponent( index, value ) {
  2424. switch ( index ) {
  2425. case 0: this.x = value; break;
  2426. case 1: this.y = value; break;
  2427. case 2: this.z = value; break;
  2428. default: throw new Error( 'index is out of range: ' + index );
  2429. }
  2430. return this;
  2431. }
  2432. getComponent( index ) {
  2433. switch ( index ) {
  2434. case 0: return this.x;
  2435. case 1: return this.y;
  2436. case 2: return this.z;
  2437. default: throw new Error( 'index is out of range: ' + index );
  2438. }
  2439. }
  2440. clone() {
  2441. return new this.constructor( this.x, this.y, this.z );
  2442. }
  2443. copy( v ) {
  2444. this.x = v.x;
  2445. this.y = v.y;
  2446. this.z = v.z;
  2447. return this;
  2448. }
  2449. add( v ) {
  2450. this.x += v.x;
  2451. this.y += v.y;
  2452. this.z += v.z;
  2453. return this;
  2454. }
  2455. addScalar( s ) {
  2456. this.x += s;
  2457. this.y += s;
  2458. this.z += s;
  2459. return this;
  2460. }
  2461. addVectors( a, b ) {
  2462. this.x = a.x + b.x;
  2463. this.y = a.y + b.y;
  2464. this.z = a.z + b.z;
  2465. return this;
  2466. }
  2467. addScaledVector( v, s ) {
  2468. this.x += v.x * s;
  2469. this.y += v.y * s;
  2470. this.z += v.z * s;
  2471. return this;
  2472. }
  2473. sub( v ) {
  2474. this.x -= v.x;
  2475. this.y -= v.y;
  2476. this.z -= v.z;
  2477. return this;
  2478. }
  2479. subScalar( s ) {
  2480. this.x -= s;
  2481. this.y -= s;
  2482. this.z -= s;
  2483. return this;
  2484. }
  2485. subVectors( a, b ) {
  2486. this.x = a.x - b.x;
  2487. this.y = a.y - b.y;
  2488. this.z = a.z - b.z;
  2489. return this;
  2490. }
  2491. multiply( v ) {
  2492. this.x *= v.x;
  2493. this.y *= v.y;
  2494. this.z *= v.z;
  2495. return this;
  2496. }
  2497. multiplyScalar( scalar ) {
  2498. this.x *= scalar;
  2499. this.y *= scalar;
  2500. this.z *= scalar;
  2501. return this;
  2502. }
  2503. multiplyVectors( a, b ) {
  2504. this.x = a.x * b.x;
  2505. this.y = a.y * b.y;
  2506. this.z = a.z * b.z;
  2507. return this;
  2508. }
  2509. applyEuler( euler ) {
  2510. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2511. }
  2512. applyAxisAngle( axis, angle ) {
  2513. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2514. }
  2515. applyMatrix3( m ) {
  2516. const x = this.x, y = this.y, z = this.z;
  2517. const e = m.elements;
  2518. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2519. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2520. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2521. return this;
  2522. }
  2523. applyNormalMatrix( m ) {
  2524. return this.applyMatrix3( m ).normalize();
  2525. }
  2526. applyMatrix4( m ) {
  2527. const x = this.x, y = this.y, z = this.z;
  2528. const e = m.elements;
  2529. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2530. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2531. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2532. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2533. return this;
  2534. }
  2535. applyQuaternion( q ) {
  2536. // quaternion q is assumed to have unit length
  2537. const vx = this.x, vy = this.y, vz = this.z;
  2538. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2539. // t = 2 * cross( q.xyz, v );
  2540. const tx = 2 * ( qy * vz - qz * vy );
  2541. const ty = 2 * ( qz * vx - qx * vz );
  2542. const tz = 2 * ( qx * vy - qy * vx );
  2543. // v + q.w * t + cross( q.xyz, t );
  2544. this.x = vx + qw * tx + qy * tz - qz * ty;
  2545. this.y = vy + qw * ty + qz * tx - qx * tz;
  2546. this.z = vz + qw * tz + qx * ty - qy * tx;
  2547. return this;
  2548. }
  2549. project( camera ) {
  2550. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2551. }
  2552. unproject( camera ) {
  2553. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2554. }
  2555. transformDirection( m ) {
  2556. // input: THREE.Matrix4 affine matrix
  2557. // vector interpreted as a direction
  2558. const x = this.x, y = this.y, z = this.z;
  2559. const e = m.elements;
  2560. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2561. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2562. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2563. return this.normalize();
  2564. }
  2565. divide( v ) {
  2566. this.x /= v.x;
  2567. this.y /= v.y;
  2568. this.z /= v.z;
  2569. return this;
  2570. }
  2571. divideScalar( scalar ) {
  2572. return this.multiplyScalar( 1 / scalar );
  2573. }
  2574. min( v ) {
  2575. this.x = Math.min( this.x, v.x );
  2576. this.y = Math.min( this.y, v.y );
  2577. this.z = Math.min( this.z, v.z );
  2578. return this;
  2579. }
  2580. max( v ) {
  2581. this.x = Math.max( this.x, v.x );
  2582. this.y = Math.max( this.y, v.y );
  2583. this.z = Math.max( this.z, v.z );
  2584. return this;
  2585. }
  2586. clamp( min, max ) {
  2587. // assumes min < max, componentwise
  2588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2590. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2591. return this;
  2592. }
  2593. clampScalar( minVal, maxVal ) {
  2594. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2595. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2596. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2597. return this;
  2598. }
  2599. clampLength( min, max ) {
  2600. const length = this.length();
  2601. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2602. }
  2603. floor() {
  2604. this.x = Math.floor( this.x );
  2605. this.y = Math.floor( this.y );
  2606. this.z = Math.floor( this.z );
  2607. return this;
  2608. }
  2609. ceil() {
  2610. this.x = Math.ceil( this.x );
  2611. this.y = Math.ceil( this.y );
  2612. this.z = Math.ceil( this.z );
  2613. return this;
  2614. }
  2615. round() {
  2616. this.x = Math.round( this.x );
  2617. this.y = Math.round( this.y );
  2618. this.z = Math.round( this.z );
  2619. return this;
  2620. }
  2621. roundToZero() {
  2622. this.x = Math.trunc( this.x );
  2623. this.y = Math.trunc( this.y );
  2624. this.z = Math.trunc( this.z );
  2625. return this;
  2626. }
  2627. negate() {
  2628. this.x = - this.x;
  2629. this.y = - this.y;
  2630. this.z = - this.z;
  2631. return this;
  2632. }
  2633. dot( v ) {
  2634. return this.x * v.x + this.y * v.y + this.z * v.z;
  2635. }
  2636. // TODO lengthSquared?
  2637. lengthSq() {
  2638. return this.x * this.x + this.y * this.y + this.z * this.z;
  2639. }
  2640. length() {
  2641. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2642. }
  2643. manhattanLength() {
  2644. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2645. }
  2646. normalize() {
  2647. return this.divideScalar( this.length() || 1 );
  2648. }
  2649. setLength( length ) {
  2650. return this.normalize().multiplyScalar( length );
  2651. }
  2652. lerp( v, alpha ) {
  2653. this.x += ( v.x - this.x ) * alpha;
  2654. this.y += ( v.y - this.y ) * alpha;
  2655. this.z += ( v.z - this.z ) * alpha;
  2656. return this;
  2657. }
  2658. lerpVectors( v1, v2, alpha ) {
  2659. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2660. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2661. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2662. return this;
  2663. }
  2664. cross( v ) {
  2665. return this.crossVectors( this, v );
  2666. }
  2667. crossVectors( a, b ) {
  2668. const ax = a.x, ay = a.y, az = a.z;
  2669. const bx = b.x, by = b.y, bz = b.z;
  2670. this.x = ay * bz - az * by;
  2671. this.y = az * bx - ax * bz;
  2672. this.z = ax * by - ay * bx;
  2673. return this;
  2674. }
  2675. projectOnVector( v ) {
  2676. const denominator = v.lengthSq();
  2677. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2678. const scalar = v.dot( this ) / denominator;
  2679. return this.copy( v ).multiplyScalar( scalar );
  2680. }
  2681. projectOnPlane( planeNormal ) {
  2682. _vector$c.copy( this ).projectOnVector( planeNormal );
  2683. return this.sub( _vector$c );
  2684. }
  2685. reflect( normal ) {
  2686. // reflect incident vector off plane orthogonal to normal
  2687. // normal is assumed to have unit length
  2688. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2689. }
  2690. angleTo( v ) {
  2691. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2692. if ( denominator === 0 ) return Math.PI / 2;
  2693. const theta = this.dot( v ) / denominator;
  2694. // clamp, to handle numerical problems
  2695. return Math.acos( clamp( theta, - 1, 1 ) );
  2696. }
  2697. distanceTo( v ) {
  2698. return Math.sqrt( this.distanceToSquared( v ) );
  2699. }
  2700. distanceToSquared( v ) {
  2701. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2702. return dx * dx + dy * dy + dz * dz;
  2703. }
  2704. manhattanDistanceTo( v ) {
  2705. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2706. }
  2707. setFromSpherical( s ) {
  2708. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2709. }
  2710. setFromSphericalCoords( radius, phi, theta ) {
  2711. const sinPhiRadius = Math.sin( phi ) * radius;
  2712. this.x = sinPhiRadius * Math.sin( theta );
  2713. this.y = Math.cos( phi ) * radius;
  2714. this.z = sinPhiRadius * Math.cos( theta );
  2715. return this;
  2716. }
  2717. setFromCylindrical( c ) {
  2718. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2719. }
  2720. setFromCylindricalCoords( radius, theta, y ) {
  2721. this.x = radius * Math.sin( theta );
  2722. this.y = y;
  2723. this.z = radius * Math.cos( theta );
  2724. return this;
  2725. }
  2726. setFromMatrixPosition( m ) {
  2727. const e = m.elements;
  2728. this.x = e[ 12 ];
  2729. this.y = e[ 13 ];
  2730. this.z = e[ 14 ];
  2731. return this;
  2732. }
  2733. setFromMatrixScale( m ) {
  2734. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2735. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2736. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2737. this.x = sx;
  2738. this.y = sy;
  2739. this.z = sz;
  2740. return this;
  2741. }
  2742. setFromMatrixColumn( m, index ) {
  2743. return this.fromArray( m.elements, index * 4 );
  2744. }
  2745. setFromMatrix3Column( m, index ) {
  2746. return this.fromArray( m.elements, index * 3 );
  2747. }
  2748. setFromEuler( e ) {
  2749. this.x = e._x;
  2750. this.y = e._y;
  2751. this.z = e._z;
  2752. return this;
  2753. }
  2754. setFromColor( c ) {
  2755. this.x = c.r;
  2756. this.y = c.g;
  2757. this.z = c.b;
  2758. return this;
  2759. }
  2760. equals( v ) {
  2761. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2762. }
  2763. fromArray( array, offset = 0 ) {
  2764. this.x = array[ offset ];
  2765. this.y = array[ offset + 1 ];
  2766. this.z = array[ offset + 2 ];
  2767. return this;
  2768. }
  2769. toArray( array = [], offset = 0 ) {
  2770. array[ offset ] = this.x;
  2771. array[ offset + 1 ] = this.y;
  2772. array[ offset + 2 ] = this.z;
  2773. return array;
  2774. }
  2775. fromBufferAttribute( attribute, index ) {
  2776. this.x = attribute.getX( index );
  2777. this.y = attribute.getY( index );
  2778. this.z = attribute.getZ( index );
  2779. return this;
  2780. }
  2781. random() {
  2782. this.x = Math.random();
  2783. this.y = Math.random();
  2784. this.z = Math.random();
  2785. return this;
  2786. }
  2787. randomDirection() {
  2788. // https://mathworld.wolfram.com/SpherePointPicking.html
  2789. const theta = Math.random() * Math.PI * 2;
  2790. const u = Math.random() * 2 - 1;
  2791. const c = Math.sqrt( 1 - u * u );
  2792. this.x = c * Math.cos( theta );
  2793. this.y = u;
  2794. this.z = c * Math.sin( theta );
  2795. return this;
  2796. }
  2797. *[ Symbol.iterator ]() {
  2798. yield this.x;
  2799. yield this.y;
  2800. yield this.z;
  2801. }
  2802. }
  2803. const _vector$c = /*@__PURE__*/ new Vector3();
  2804. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2805. class Box3 {
  2806. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2807. this.isBox3 = true;
  2808. this.min = min;
  2809. this.max = max;
  2810. }
  2811. set( min, max ) {
  2812. this.min.copy( min );
  2813. this.max.copy( max );
  2814. return this;
  2815. }
  2816. setFromArray( array ) {
  2817. this.makeEmpty();
  2818. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2819. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2820. }
  2821. return this;
  2822. }
  2823. setFromBufferAttribute( attribute ) {
  2824. this.makeEmpty();
  2825. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2826. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2827. }
  2828. return this;
  2829. }
  2830. setFromPoints( points ) {
  2831. this.makeEmpty();
  2832. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2833. this.expandByPoint( points[ i ] );
  2834. }
  2835. return this;
  2836. }
  2837. setFromCenterAndSize( center, size ) {
  2838. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2839. this.min.copy( center ).sub( halfSize );
  2840. this.max.copy( center ).add( halfSize );
  2841. return this;
  2842. }
  2843. setFromObject( object, precise = false ) {
  2844. this.makeEmpty();
  2845. return this.expandByObject( object, precise );
  2846. }
  2847. clone() {
  2848. return new this.constructor().copy( this );
  2849. }
  2850. copy( box ) {
  2851. this.min.copy( box.min );
  2852. this.max.copy( box.max );
  2853. return this;
  2854. }
  2855. makeEmpty() {
  2856. this.min.x = this.min.y = this.min.z = + Infinity;
  2857. this.max.x = this.max.y = this.max.z = - Infinity;
  2858. return this;
  2859. }
  2860. isEmpty() {
  2861. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2862. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2863. }
  2864. getCenter( target ) {
  2865. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2866. }
  2867. getSize( target ) {
  2868. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2869. }
  2870. expandByPoint( point ) {
  2871. this.min.min( point );
  2872. this.max.max( point );
  2873. return this;
  2874. }
  2875. expandByVector( vector ) {
  2876. this.min.sub( vector );
  2877. this.max.add( vector );
  2878. return this;
  2879. }
  2880. expandByScalar( scalar ) {
  2881. this.min.addScalar( - scalar );
  2882. this.max.addScalar( scalar );
  2883. return this;
  2884. }
  2885. expandByObject( object, precise = false ) {
  2886. // Computes the world-axis-aligned bounding box of an object (including its children),
  2887. // accounting for both the object's, and children's, world transforms
  2888. object.updateWorldMatrix( false, false );
  2889. const geometry = object.geometry;
  2890. if ( geometry !== undefined ) {
  2891. const positionAttribute = geometry.getAttribute( 'position' );
  2892. // precise AABB computation based on vertex data requires at least a position attribute.
  2893. // instancing isn't supported so far and uses the normal (conservative) code path.
  2894. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2895. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2896. if ( object.isMesh === true ) {
  2897. object.getVertexPosition( i, _vector$b );
  2898. } else {
  2899. _vector$b.fromBufferAttribute( positionAttribute, i );
  2900. }
  2901. _vector$b.applyMatrix4( object.matrixWorld );
  2902. this.expandByPoint( _vector$b );
  2903. }
  2904. } else {
  2905. if ( object.boundingBox !== undefined ) {
  2906. // object-level bounding box
  2907. if ( object.boundingBox === null ) {
  2908. object.computeBoundingBox();
  2909. }
  2910. _box$4.copy( object.boundingBox );
  2911. } else {
  2912. // geometry-level bounding box
  2913. if ( geometry.boundingBox === null ) {
  2914. geometry.computeBoundingBox();
  2915. }
  2916. _box$4.copy( geometry.boundingBox );
  2917. }
  2918. _box$4.applyMatrix4( object.matrixWorld );
  2919. this.union( _box$4 );
  2920. }
  2921. }
  2922. const children = object.children;
  2923. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2924. this.expandByObject( children[ i ], precise );
  2925. }
  2926. return this;
  2927. }
  2928. containsPoint( point ) {
  2929. return point.x >= this.min.x && point.x <= this.max.x &&
  2930. point.y >= this.min.y && point.y <= this.max.y &&
  2931. point.z >= this.min.z && point.z <= this.max.z;
  2932. }
  2933. containsBox( box ) {
  2934. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2935. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2936. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2937. }
  2938. getParameter( point, target ) {
  2939. // This can potentially have a divide by zero if the box
  2940. // has a size dimension of 0.
  2941. return target.set(
  2942. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2943. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2944. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2945. );
  2946. }
  2947. intersectsBox( box ) {
  2948. // using 6 splitting planes to rule out intersections.
  2949. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2950. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2951. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2952. }
  2953. intersectsSphere( sphere ) {
  2954. // Find the point on the AABB closest to the sphere center.
  2955. this.clampPoint( sphere.center, _vector$b );
  2956. // If that point is inside the sphere, the AABB and sphere intersect.
  2957. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2958. }
  2959. intersectsPlane( plane ) {
  2960. // We compute the minimum and maximum dot product values. If those values
  2961. // are on the same side (back or front) of the plane, then there is no intersection.
  2962. let min, max;
  2963. if ( plane.normal.x > 0 ) {
  2964. min = plane.normal.x * this.min.x;
  2965. max = plane.normal.x * this.max.x;
  2966. } else {
  2967. min = plane.normal.x * this.max.x;
  2968. max = plane.normal.x * this.min.x;
  2969. }
  2970. if ( plane.normal.y > 0 ) {
  2971. min += plane.normal.y * this.min.y;
  2972. max += plane.normal.y * this.max.y;
  2973. } else {
  2974. min += plane.normal.y * this.max.y;
  2975. max += plane.normal.y * this.min.y;
  2976. }
  2977. if ( plane.normal.z > 0 ) {
  2978. min += plane.normal.z * this.min.z;
  2979. max += plane.normal.z * this.max.z;
  2980. } else {
  2981. min += plane.normal.z * this.max.z;
  2982. max += plane.normal.z * this.min.z;
  2983. }
  2984. return ( min <= - plane.constant && max >= - plane.constant );
  2985. }
  2986. intersectsTriangle( triangle ) {
  2987. if ( this.isEmpty() ) {
  2988. return false;
  2989. }
  2990. // compute box center and extents
  2991. this.getCenter( _center );
  2992. _extents.subVectors( this.max, _center );
  2993. // translate triangle to aabb origin
  2994. _v0$3.subVectors( triangle.a, _center );
  2995. _v1$7.subVectors( triangle.b, _center );
  2996. _v2$4.subVectors( triangle.c, _center );
  2997. // compute edge vectors for triangle
  2998. _f0.subVectors( _v1$7, _v0$3 );
  2999. _f1.subVectors( _v2$4, _v1$7 );
  3000. _f2.subVectors( _v0$3, _v2$4 );
  3001. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3002. // 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
  3003. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3004. let axes = [
  3005. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3006. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3007. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3008. ];
  3009. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3010. return false;
  3011. }
  3012. // test 3 face normals from the aabb
  3013. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3014. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3015. return false;
  3016. }
  3017. // finally testing the face normal of the triangle
  3018. // use already existing triangle edge vectors here
  3019. _triangleNormal.crossVectors( _f0, _f1 );
  3020. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3021. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  3022. }
  3023. clampPoint( point, target ) {
  3024. return target.copy( point ).clamp( this.min, this.max );
  3025. }
  3026. distanceToPoint( point ) {
  3027. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3028. }
  3029. getBoundingSphere( target ) {
  3030. if ( this.isEmpty() ) {
  3031. target.makeEmpty();
  3032. } else {
  3033. this.getCenter( target.center );
  3034. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3035. }
  3036. return target;
  3037. }
  3038. intersect( box ) {
  3039. this.min.max( box.min );
  3040. this.max.min( box.max );
  3041. // 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.
  3042. if ( this.isEmpty() ) this.makeEmpty();
  3043. return this;
  3044. }
  3045. union( box ) {
  3046. this.min.min( box.min );
  3047. this.max.max( box.max );
  3048. return this;
  3049. }
  3050. applyMatrix4( matrix ) {
  3051. // transform of empty box is an empty box.
  3052. if ( this.isEmpty() ) return this;
  3053. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3054. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3055. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3056. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3057. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3058. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3059. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3060. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3061. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3062. this.setFromPoints( _points );
  3063. return this;
  3064. }
  3065. translate( offset ) {
  3066. this.min.add( offset );
  3067. this.max.add( offset );
  3068. return this;
  3069. }
  3070. equals( box ) {
  3071. return box.min.equals( this.min ) && box.max.equals( this.max );
  3072. }
  3073. }
  3074. const _points = [
  3075. /*@__PURE__*/ new Vector3(),
  3076. /*@__PURE__*/ new Vector3(),
  3077. /*@__PURE__*/ new Vector3(),
  3078. /*@__PURE__*/ new Vector3(),
  3079. /*@__PURE__*/ new Vector3(),
  3080. /*@__PURE__*/ new Vector3(),
  3081. /*@__PURE__*/ new Vector3(),
  3082. /*@__PURE__*/ new Vector3()
  3083. ];
  3084. const _vector$b = /*@__PURE__*/ new Vector3();
  3085. const _box$4 = /*@__PURE__*/ new Box3();
  3086. // triangle centered vertices
  3087. const _v0$3 = /*@__PURE__*/ new Vector3();
  3088. const _v1$7 = /*@__PURE__*/ new Vector3();
  3089. const _v2$4 = /*@__PURE__*/ new Vector3();
  3090. // triangle edge vectors
  3091. const _f0 = /*@__PURE__*/ new Vector3();
  3092. const _f1 = /*@__PURE__*/ new Vector3();
  3093. const _f2 = /*@__PURE__*/ new Vector3();
  3094. const _center = /*@__PURE__*/ new Vector3();
  3095. const _extents = /*@__PURE__*/ new Vector3();
  3096. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3097. const _testAxis = /*@__PURE__*/ new Vector3();
  3098. function satForAxes( axes, v0, v1, v2, extents ) {
  3099. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3100. _testAxis.fromArray( axes, i );
  3101. // project the aabb onto the separating axis
  3102. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3103. // project all 3 vertices of the triangle onto the separating axis
  3104. const p0 = v0.dot( _testAxis );
  3105. const p1 = v1.dot( _testAxis );
  3106. const p2 = v2.dot( _testAxis );
  3107. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3108. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3109. // points of the projected triangle are outside the projected half-length of the aabb
  3110. // the axis is separating and we can exit
  3111. return false;
  3112. }
  3113. }
  3114. return true;
  3115. }
  3116. const _box$3 = /*@__PURE__*/ new Box3();
  3117. const _v1$6 = /*@__PURE__*/ new Vector3();
  3118. const _v2$3 = /*@__PURE__*/ new Vector3();
  3119. class Sphere {
  3120. constructor( center = new Vector3(), radius = - 1 ) {
  3121. this.isSphere = true;
  3122. this.center = center;
  3123. this.radius = radius;
  3124. }
  3125. set( center, radius ) {
  3126. this.center.copy( center );
  3127. this.radius = radius;
  3128. return this;
  3129. }
  3130. setFromPoints( points, optionalCenter ) {
  3131. const center = this.center;
  3132. if ( optionalCenter !== undefined ) {
  3133. center.copy( optionalCenter );
  3134. } else {
  3135. _box$3.setFromPoints( points ).getCenter( center );
  3136. }
  3137. let maxRadiusSq = 0;
  3138. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3139. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3140. }
  3141. this.radius = Math.sqrt( maxRadiusSq );
  3142. return this;
  3143. }
  3144. copy( sphere ) {
  3145. this.center.copy( sphere.center );
  3146. this.radius = sphere.radius;
  3147. return this;
  3148. }
  3149. isEmpty() {
  3150. return ( this.radius < 0 );
  3151. }
  3152. makeEmpty() {
  3153. this.center.set( 0, 0, 0 );
  3154. this.radius = - 1;
  3155. return this;
  3156. }
  3157. containsPoint( point ) {
  3158. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3159. }
  3160. distanceToPoint( point ) {
  3161. return ( point.distanceTo( this.center ) - this.radius );
  3162. }
  3163. intersectsSphere( sphere ) {
  3164. const radiusSum = this.radius + sphere.radius;
  3165. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3166. }
  3167. intersectsBox( box ) {
  3168. return box.intersectsSphere( this );
  3169. }
  3170. intersectsPlane( plane ) {
  3171. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3172. }
  3173. clampPoint( point, target ) {
  3174. const deltaLengthSq = this.center.distanceToSquared( point );
  3175. target.copy( point );
  3176. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3177. target.sub( this.center ).normalize();
  3178. target.multiplyScalar( this.radius ).add( this.center );
  3179. }
  3180. return target;
  3181. }
  3182. getBoundingBox( target ) {
  3183. if ( this.isEmpty() ) {
  3184. // Empty sphere produces empty bounding box
  3185. target.makeEmpty();
  3186. return target;
  3187. }
  3188. target.set( this.center, this.center );
  3189. target.expandByScalar( this.radius );
  3190. return target;
  3191. }
  3192. applyMatrix4( matrix ) {
  3193. this.center.applyMatrix4( matrix );
  3194. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3195. return this;
  3196. }
  3197. translate( offset ) {
  3198. this.center.add( offset );
  3199. return this;
  3200. }
  3201. expandByPoint( point ) {
  3202. if ( this.isEmpty() ) {
  3203. this.center.copy( point );
  3204. this.radius = 0;
  3205. return this;
  3206. }
  3207. _v1$6.subVectors( point, this.center );
  3208. const lengthSq = _v1$6.lengthSq();
  3209. if ( lengthSq > ( this.radius * this.radius ) ) {
  3210. // calculate the minimal sphere
  3211. const length = Math.sqrt( lengthSq );
  3212. const delta = ( length - this.radius ) * 0.5;
  3213. this.center.addScaledVector( _v1$6, delta / length );
  3214. this.radius += delta;
  3215. }
  3216. return this;
  3217. }
  3218. union( sphere ) {
  3219. if ( sphere.isEmpty() ) {
  3220. return this;
  3221. }
  3222. if ( this.isEmpty() ) {
  3223. this.copy( sphere );
  3224. return this;
  3225. }
  3226. if ( this.center.equals( sphere.center ) === true ) {
  3227. this.radius = Math.max( this.radius, sphere.radius );
  3228. } else {
  3229. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3230. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3231. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3232. }
  3233. return this;
  3234. }
  3235. equals( sphere ) {
  3236. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3237. }
  3238. clone() {
  3239. return new this.constructor().copy( this );
  3240. }
  3241. }
  3242. const _vector$a = /*@__PURE__*/ new Vector3();
  3243. const _segCenter = /*@__PURE__*/ new Vector3();
  3244. const _segDir = /*@__PURE__*/ new Vector3();
  3245. const _diff = /*@__PURE__*/ new Vector3();
  3246. const _edge1 = /*@__PURE__*/ new Vector3();
  3247. const _edge2 = /*@__PURE__*/ new Vector3();
  3248. const _normal$1 = /*@__PURE__*/ new Vector3();
  3249. class Ray {
  3250. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3251. this.origin = origin;
  3252. this.direction = direction;
  3253. }
  3254. set( origin, direction ) {
  3255. this.origin.copy( origin );
  3256. this.direction.copy( direction );
  3257. return this;
  3258. }
  3259. copy( ray ) {
  3260. this.origin.copy( ray.origin );
  3261. this.direction.copy( ray.direction );
  3262. return this;
  3263. }
  3264. at( t, target ) {
  3265. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3266. }
  3267. lookAt( v ) {
  3268. this.direction.copy( v ).sub( this.origin ).normalize();
  3269. return this;
  3270. }
  3271. recast( t ) {
  3272. this.origin.copy( this.at( t, _vector$a ) );
  3273. return this;
  3274. }
  3275. closestPointToPoint( point, target ) {
  3276. target.subVectors( point, this.origin );
  3277. const directionDistance = target.dot( this.direction );
  3278. if ( directionDistance < 0 ) {
  3279. return target.copy( this.origin );
  3280. }
  3281. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3282. }
  3283. distanceToPoint( point ) {
  3284. return Math.sqrt( this.distanceSqToPoint( point ) );
  3285. }
  3286. distanceSqToPoint( point ) {
  3287. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3288. // point behind the ray
  3289. if ( directionDistance < 0 ) {
  3290. return this.origin.distanceToSquared( point );
  3291. }
  3292. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3293. return _vector$a.distanceToSquared( point );
  3294. }
  3295. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3296. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3297. // It returns the min distance between the ray and the segment
  3298. // defined by v0 and v1
  3299. // It can also set two optional targets :
  3300. // - The closest point on the ray
  3301. // - The closest point on the segment
  3302. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3303. _segDir.copy( v1 ).sub( v0 ).normalize();
  3304. _diff.copy( this.origin ).sub( _segCenter );
  3305. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3306. const a01 = - this.direction.dot( _segDir );
  3307. const b0 = _diff.dot( this.direction );
  3308. const b1 = - _diff.dot( _segDir );
  3309. const c = _diff.lengthSq();
  3310. const det = Math.abs( 1 - a01 * a01 );
  3311. let s0, s1, sqrDist, extDet;
  3312. if ( det > 0 ) {
  3313. // The ray and segment are not parallel.
  3314. s0 = a01 * b1 - b0;
  3315. s1 = a01 * b0 - b1;
  3316. extDet = segExtent * det;
  3317. if ( s0 >= 0 ) {
  3318. if ( s1 >= - extDet ) {
  3319. if ( s1 <= extDet ) {
  3320. // region 0
  3321. // Minimum at interior points of ray and segment.
  3322. const invDet = 1 / det;
  3323. s0 *= invDet;
  3324. s1 *= invDet;
  3325. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3326. } else {
  3327. // region 1
  3328. s1 = segExtent;
  3329. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3330. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3331. }
  3332. } else {
  3333. // region 5
  3334. s1 = - segExtent;
  3335. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3337. }
  3338. } else {
  3339. if ( s1 <= - extDet ) {
  3340. // region 4
  3341. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3342. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3344. } else if ( s1 <= extDet ) {
  3345. // region 3
  3346. s0 = 0;
  3347. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3348. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3349. } else {
  3350. // region 2
  3351. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3352. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3353. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3354. }
  3355. }
  3356. } else {
  3357. // Ray and segment are parallel.
  3358. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3359. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3360. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3361. }
  3362. if ( optionalPointOnRay ) {
  3363. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3364. }
  3365. if ( optionalPointOnSegment ) {
  3366. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3367. }
  3368. return sqrDist;
  3369. }
  3370. intersectSphere( sphere, target ) {
  3371. _vector$a.subVectors( sphere.center, this.origin );
  3372. const tca = _vector$a.dot( this.direction );
  3373. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3374. const radius2 = sphere.radius * sphere.radius;
  3375. if ( d2 > radius2 ) return null;
  3376. const thc = Math.sqrt( radius2 - d2 );
  3377. // t0 = first intersect point - entrance on front of sphere
  3378. const t0 = tca - thc;
  3379. // t1 = second intersect point - exit point on back of sphere
  3380. const t1 = tca + thc;
  3381. // test to see if t1 is behind the ray - if so, return null
  3382. if ( t1 < 0 ) return null;
  3383. // test to see if t0 is behind the ray:
  3384. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3385. // in order to always return an intersect point that is in front of the ray.
  3386. if ( t0 < 0 ) return this.at( t1, target );
  3387. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3388. return this.at( t0, target );
  3389. }
  3390. intersectsSphere( sphere ) {
  3391. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3392. }
  3393. distanceToPlane( plane ) {
  3394. const denominator = plane.normal.dot( this.direction );
  3395. if ( denominator === 0 ) {
  3396. // line is coplanar, return origin
  3397. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3398. return 0;
  3399. }
  3400. // Null is preferable to undefined since undefined means.... it is undefined
  3401. return null;
  3402. }
  3403. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3404. // Return if the ray never intersects the plane
  3405. return t >= 0 ? t : null;
  3406. }
  3407. intersectPlane( plane, target ) {
  3408. const t = this.distanceToPlane( plane );
  3409. if ( t === null ) {
  3410. return null;
  3411. }
  3412. return this.at( t, target );
  3413. }
  3414. intersectsPlane( plane ) {
  3415. // check if the ray lies on the plane first
  3416. const distToPoint = plane.distanceToPoint( this.origin );
  3417. if ( distToPoint === 0 ) {
  3418. return true;
  3419. }
  3420. const denominator = plane.normal.dot( this.direction );
  3421. if ( denominator * distToPoint < 0 ) {
  3422. return true;
  3423. }
  3424. // ray origin is behind the plane (and is pointing behind it)
  3425. return false;
  3426. }
  3427. intersectBox( box, target ) {
  3428. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3429. const invdirx = 1 / this.direction.x,
  3430. invdiry = 1 / this.direction.y,
  3431. invdirz = 1 / this.direction.z;
  3432. const origin = this.origin;
  3433. if ( invdirx >= 0 ) {
  3434. tmin = ( box.min.x - origin.x ) * invdirx;
  3435. tmax = ( box.max.x - origin.x ) * invdirx;
  3436. } else {
  3437. tmin = ( box.max.x - origin.x ) * invdirx;
  3438. tmax = ( box.min.x - origin.x ) * invdirx;
  3439. }
  3440. if ( invdiry >= 0 ) {
  3441. tymin = ( box.min.y - origin.y ) * invdiry;
  3442. tymax = ( box.max.y - origin.y ) * invdiry;
  3443. } else {
  3444. tymin = ( box.max.y - origin.y ) * invdiry;
  3445. tymax = ( box.min.y - origin.y ) * invdiry;
  3446. }
  3447. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3448. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3449. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3450. if ( invdirz >= 0 ) {
  3451. tzmin = ( box.min.z - origin.z ) * invdirz;
  3452. tzmax = ( box.max.z - origin.z ) * invdirz;
  3453. } else {
  3454. tzmin = ( box.max.z - origin.z ) * invdirz;
  3455. tzmax = ( box.min.z - origin.z ) * invdirz;
  3456. }
  3457. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3458. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3459. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3460. //return point closest to the ray (positive side)
  3461. if ( tmax < 0 ) return null;
  3462. return this.at( tmin >= 0 ? tmin : tmax, target );
  3463. }
  3464. intersectsBox( box ) {
  3465. return this.intersectBox( box, _vector$a ) !== null;
  3466. }
  3467. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3468. // Compute the offset origin, edges, and normal.
  3469. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3470. _edge1.subVectors( b, a );
  3471. _edge2.subVectors( c, a );
  3472. _normal$1.crossVectors( _edge1, _edge2 );
  3473. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3474. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3475. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3476. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3477. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3478. let DdN = this.direction.dot( _normal$1 );
  3479. let sign;
  3480. if ( DdN > 0 ) {
  3481. if ( backfaceCulling ) return null;
  3482. sign = 1;
  3483. } else if ( DdN < 0 ) {
  3484. sign = - 1;
  3485. DdN = - DdN;
  3486. } else {
  3487. return null;
  3488. }
  3489. _diff.subVectors( this.origin, a );
  3490. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3491. // b1 < 0, no intersection
  3492. if ( DdQxE2 < 0 ) {
  3493. return null;
  3494. }
  3495. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3496. // b2 < 0, no intersection
  3497. if ( DdE1xQ < 0 ) {
  3498. return null;
  3499. }
  3500. // b1+b2 > 1, no intersection
  3501. if ( DdQxE2 + DdE1xQ > DdN ) {
  3502. return null;
  3503. }
  3504. // Line intersects triangle, check if ray does.
  3505. const QdN = - sign * _diff.dot( _normal$1 );
  3506. // t < 0, no intersection
  3507. if ( QdN < 0 ) {
  3508. return null;
  3509. }
  3510. // Ray intersects triangle.
  3511. return this.at( QdN / DdN, target );
  3512. }
  3513. applyMatrix4( matrix4 ) {
  3514. this.origin.applyMatrix4( matrix4 );
  3515. this.direction.transformDirection( matrix4 );
  3516. return this;
  3517. }
  3518. equals( ray ) {
  3519. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3520. }
  3521. clone() {
  3522. return new this.constructor().copy( this );
  3523. }
  3524. }
  3525. class Matrix4 {
  3526. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3527. Matrix4.prototype.isMatrix4 = true;
  3528. this.elements = [
  3529. 1, 0, 0, 0,
  3530. 0, 1, 0, 0,
  3531. 0, 0, 1, 0,
  3532. 0, 0, 0, 1
  3533. ];
  3534. if ( n11 !== undefined ) {
  3535. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3536. }
  3537. }
  3538. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3539. const te = this.elements;
  3540. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3541. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3542. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3543. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3544. return this;
  3545. }
  3546. identity() {
  3547. this.set(
  3548. 1, 0, 0, 0,
  3549. 0, 1, 0, 0,
  3550. 0, 0, 1, 0,
  3551. 0, 0, 0, 1
  3552. );
  3553. return this;
  3554. }
  3555. clone() {
  3556. return new Matrix4().fromArray( this.elements );
  3557. }
  3558. copy( m ) {
  3559. const te = this.elements;
  3560. const me = m.elements;
  3561. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3562. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3563. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3564. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3565. return this;
  3566. }
  3567. copyPosition( m ) {
  3568. const te = this.elements, me = m.elements;
  3569. te[ 12 ] = me[ 12 ];
  3570. te[ 13 ] = me[ 13 ];
  3571. te[ 14 ] = me[ 14 ];
  3572. return this;
  3573. }
  3574. setFromMatrix3( m ) {
  3575. const me = m.elements;
  3576. this.set(
  3577. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3578. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3579. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3580. 0, 0, 0, 1
  3581. );
  3582. return this;
  3583. }
  3584. extractBasis( xAxis, yAxis, zAxis ) {
  3585. xAxis.setFromMatrixColumn( this, 0 );
  3586. yAxis.setFromMatrixColumn( this, 1 );
  3587. zAxis.setFromMatrixColumn( this, 2 );
  3588. return this;
  3589. }
  3590. makeBasis( xAxis, yAxis, zAxis ) {
  3591. this.set(
  3592. xAxis.x, yAxis.x, zAxis.x, 0,
  3593. xAxis.y, yAxis.y, zAxis.y, 0,
  3594. xAxis.z, yAxis.z, zAxis.z, 0,
  3595. 0, 0, 0, 1
  3596. );
  3597. return this;
  3598. }
  3599. extractRotation( m ) {
  3600. // this method does not support reflection matrices
  3601. const te = this.elements;
  3602. const me = m.elements;
  3603. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3604. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3605. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3606. te[ 0 ] = me[ 0 ] * scaleX;
  3607. te[ 1 ] = me[ 1 ] * scaleX;
  3608. te[ 2 ] = me[ 2 ] * scaleX;
  3609. te[ 3 ] = 0;
  3610. te[ 4 ] = me[ 4 ] * scaleY;
  3611. te[ 5 ] = me[ 5 ] * scaleY;
  3612. te[ 6 ] = me[ 6 ] * scaleY;
  3613. te[ 7 ] = 0;
  3614. te[ 8 ] = me[ 8 ] * scaleZ;
  3615. te[ 9 ] = me[ 9 ] * scaleZ;
  3616. te[ 10 ] = me[ 10 ] * scaleZ;
  3617. te[ 11 ] = 0;
  3618. te[ 12 ] = 0;
  3619. te[ 13 ] = 0;
  3620. te[ 14 ] = 0;
  3621. te[ 15 ] = 1;
  3622. return this;
  3623. }
  3624. makeRotationFromEuler( euler ) {
  3625. const te = this.elements;
  3626. const x = euler.x, y = euler.y, z = euler.z;
  3627. const a = Math.cos( x ), b = Math.sin( x );
  3628. const c = Math.cos( y ), d = Math.sin( y );
  3629. const e = Math.cos( z ), f = Math.sin( z );
  3630. if ( euler.order === 'XYZ' ) {
  3631. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3632. te[ 0 ] = c * e;
  3633. te[ 4 ] = - c * f;
  3634. te[ 8 ] = d;
  3635. te[ 1 ] = af + be * d;
  3636. te[ 5 ] = ae - bf * d;
  3637. te[ 9 ] = - b * c;
  3638. te[ 2 ] = bf - ae * d;
  3639. te[ 6 ] = be + af * d;
  3640. te[ 10 ] = a * c;
  3641. } else if ( euler.order === 'YXZ' ) {
  3642. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3643. te[ 0 ] = ce + df * b;
  3644. te[ 4 ] = de * b - cf;
  3645. te[ 8 ] = a * d;
  3646. te[ 1 ] = a * f;
  3647. te[ 5 ] = a * e;
  3648. te[ 9 ] = - b;
  3649. te[ 2 ] = cf * b - de;
  3650. te[ 6 ] = df + ce * b;
  3651. te[ 10 ] = a * c;
  3652. } else if ( euler.order === 'ZXY' ) {
  3653. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3654. te[ 0 ] = ce - df * b;
  3655. te[ 4 ] = - a * f;
  3656. te[ 8 ] = de + cf * b;
  3657. te[ 1 ] = cf + de * b;
  3658. te[ 5 ] = a * e;
  3659. te[ 9 ] = df - ce * b;
  3660. te[ 2 ] = - a * d;
  3661. te[ 6 ] = b;
  3662. te[ 10 ] = a * c;
  3663. } else if ( euler.order === 'ZYX' ) {
  3664. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3665. te[ 0 ] = c * e;
  3666. te[ 4 ] = be * d - af;
  3667. te[ 8 ] = ae * d + bf;
  3668. te[ 1 ] = c * f;
  3669. te[ 5 ] = bf * d + ae;
  3670. te[ 9 ] = af * d - be;
  3671. te[ 2 ] = - d;
  3672. te[ 6 ] = b * c;
  3673. te[ 10 ] = a * c;
  3674. } else if ( euler.order === 'YZX' ) {
  3675. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3676. te[ 0 ] = c * e;
  3677. te[ 4 ] = bd - ac * f;
  3678. te[ 8 ] = bc * f + ad;
  3679. te[ 1 ] = f;
  3680. te[ 5 ] = a * e;
  3681. te[ 9 ] = - b * e;
  3682. te[ 2 ] = - d * e;
  3683. te[ 6 ] = ad * f + bc;
  3684. te[ 10 ] = ac - bd * f;
  3685. } else if ( euler.order === 'XZY' ) {
  3686. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3687. te[ 0 ] = c * e;
  3688. te[ 4 ] = - f;
  3689. te[ 8 ] = d * e;
  3690. te[ 1 ] = ac * f + bd;
  3691. te[ 5 ] = a * e;
  3692. te[ 9 ] = ad * f - bc;
  3693. te[ 2 ] = bc * f - ad;
  3694. te[ 6 ] = b * e;
  3695. te[ 10 ] = bd * f + ac;
  3696. }
  3697. // bottom row
  3698. te[ 3 ] = 0;
  3699. te[ 7 ] = 0;
  3700. te[ 11 ] = 0;
  3701. // last column
  3702. te[ 12 ] = 0;
  3703. te[ 13 ] = 0;
  3704. te[ 14 ] = 0;
  3705. te[ 15 ] = 1;
  3706. return this;
  3707. }
  3708. makeRotationFromQuaternion( q ) {
  3709. return this.compose( _zero, q, _one );
  3710. }
  3711. lookAt( eye, target, up ) {
  3712. const te = this.elements;
  3713. _z.subVectors( eye, target );
  3714. if ( _z.lengthSq() === 0 ) {
  3715. // eye and target are in the same position
  3716. _z.z = 1;
  3717. }
  3718. _z.normalize();
  3719. _x.crossVectors( up, _z );
  3720. if ( _x.lengthSq() === 0 ) {
  3721. // up and z are parallel
  3722. if ( Math.abs( up.z ) === 1 ) {
  3723. _z.x += 0.0001;
  3724. } else {
  3725. _z.z += 0.0001;
  3726. }
  3727. _z.normalize();
  3728. _x.crossVectors( up, _z );
  3729. }
  3730. _x.normalize();
  3731. _y.crossVectors( _z, _x );
  3732. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3733. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3734. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3735. return this;
  3736. }
  3737. multiply( m ) {
  3738. return this.multiplyMatrices( this, m );
  3739. }
  3740. premultiply( m ) {
  3741. return this.multiplyMatrices( m, this );
  3742. }
  3743. multiplyMatrices( a, b ) {
  3744. const ae = a.elements;
  3745. const be = b.elements;
  3746. const te = this.elements;
  3747. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3748. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3749. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3750. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3751. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3752. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3753. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3754. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3755. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3756. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3757. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3758. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3759. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3760. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3761. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3762. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3763. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3764. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3765. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3766. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3767. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3768. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3769. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3770. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3771. return this;
  3772. }
  3773. multiplyScalar( s ) {
  3774. const te = this.elements;
  3775. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3776. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3777. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3778. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3779. return this;
  3780. }
  3781. determinant() {
  3782. const te = this.elements;
  3783. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3784. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3785. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3786. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3787. //TODO: make this more efficient
  3788. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3789. return (
  3790. n41 * (
  3791. + n14 * n23 * n32
  3792. - n13 * n24 * n32
  3793. - n14 * n22 * n33
  3794. + n12 * n24 * n33
  3795. + n13 * n22 * n34
  3796. - n12 * n23 * n34
  3797. ) +
  3798. n42 * (
  3799. + n11 * n23 * n34
  3800. - n11 * n24 * n33
  3801. + n14 * n21 * n33
  3802. - n13 * n21 * n34
  3803. + n13 * n24 * n31
  3804. - n14 * n23 * n31
  3805. ) +
  3806. n43 * (
  3807. + n11 * n24 * n32
  3808. - n11 * n22 * n34
  3809. - n14 * n21 * n32
  3810. + n12 * n21 * n34
  3811. + n14 * n22 * n31
  3812. - n12 * n24 * n31
  3813. ) +
  3814. n44 * (
  3815. - n13 * n22 * n31
  3816. - n11 * n23 * n32
  3817. + n11 * n22 * n33
  3818. + n13 * n21 * n32
  3819. - n12 * n21 * n33
  3820. + n12 * n23 * n31
  3821. )
  3822. );
  3823. }
  3824. transpose() {
  3825. const te = this.elements;
  3826. let tmp;
  3827. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3828. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3829. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3830. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3831. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3832. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3833. return this;
  3834. }
  3835. setPosition( x, y, z ) {
  3836. const te = this.elements;
  3837. if ( x.isVector3 ) {
  3838. te[ 12 ] = x.x;
  3839. te[ 13 ] = x.y;
  3840. te[ 14 ] = x.z;
  3841. } else {
  3842. te[ 12 ] = x;
  3843. te[ 13 ] = y;
  3844. te[ 14 ] = z;
  3845. }
  3846. return this;
  3847. }
  3848. invert() {
  3849. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3850. const te = this.elements,
  3851. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3852. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3853. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3854. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3855. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3856. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3857. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3858. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3859. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3860. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3861. const detInv = 1 / det;
  3862. te[ 0 ] = t11 * detInv;
  3863. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3864. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3865. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3866. te[ 4 ] = t12 * detInv;
  3867. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3868. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3869. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3870. te[ 8 ] = t13 * detInv;
  3871. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3872. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3873. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3874. te[ 12 ] = t14 * detInv;
  3875. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3876. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3877. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3878. return this;
  3879. }
  3880. scale( v ) {
  3881. const te = this.elements;
  3882. const x = v.x, y = v.y, z = v.z;
  3883. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3884. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3885. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3886. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3887. return this;
  3888. }
  3889. getMaxScaleOnAxis() {
  3890. const te = this.elements;
  3891. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3892. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3893. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3894. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3895. }
  3896. makeTranslation( x, y, z ) {
  3897. if ( x.isVector3 ) {
  3898. this.set(
  3899. 1, 0, 0, x.x,
  3900. 0, 1, 0, x.y,
  3901. 0, 0, 1, x.z,
  3902. 0, 0, 0, 1
  3903. );
  3904. } else {
  3905. this.set(
  3906. 1, 0, 0, x,
  3907. 0, 1, 0, y,
  3908. 0, 0, 1, z,
  3909. 0, 0, 0, 1
  3910. );
  3911. }
  3912. return this;
  3913. }
  3914. makeRotationX( theta ) {
  3915. const c = Math.cos( theta ), s = Math.sin( theta );
  3916. this.set(
  3917. 1, 0, 0, 0,
  3918. 0, c, - s, 0,
  3919. 0, s, c, 0,
  3920. 0, 0, 0, 1
  3921. );
  3922. return this;
  3923. }
  3924. makeRotationY( theta ) {
  3925. const c = Math.cos( theta ), s = Math.sin( theta );
  3926. this.set(
  3927. c, 0, s, 0,
  3928. 0, 1, 0, 0,
  3929. - s, 0, c, 0,
  3930. 0, 0, 0, 1
  3931. );
  3932. return this;
  3933. }
  3934. makeRotationZ( theta ) {
  3935. const c = Math.cos( theta ), s = Math.sin( theta );
  3936. this.set(
  3937. c, - s, 0, 0,
  3938. s, c, 0, 0,
  3939. 0, 0, 1, 0,
  3940. 0, 0, 0, 1
  3941. );
  3942. return this;
  3943. }
  3944. makeRotationAxis( axis, angle ) {
  3945. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3946. const c = Math.cos( angle );
  3947. const s = Math.sin( angle );
  3948. const t = 1 - c;
  3949. const x = axis.x, y = axis.y, z = axis.z;
  3950. const tx = t * x, ty = t * y;
  3951. this.set(
  3952. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3953. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3954. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3955. 0, 0, 0, 1
  3956. );
  3957. return this;
  3958. }
  3959. makeScale( x, y, z ) {
  3960. this.set(
  3961. x, 0, 0, 0,
  3962. 0, y, 0, 0,
  3963. 0, 0, z, 0,
  3964. 0, 0, 0, 1
  3965. );
  3966. return this;
  3967. }
  3968. makeShear( xy, xz, yx, yz, zx, zy ) {
  3969. this.set(
  3970. 1, yx, zx, 0,
  3971. xy, 1, zy, 0,
  3972. xz, yz, 1, 0,
  3973. 0, 0, 0, 1
  3974. );
  3975. return this;
  3976. }
  3977. compose( position, quaternion, scale ) {
  3978. const te = this.elements;
  3979. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3980. const x2 = x + x, y2 = y + y, z2 = z + z;
  3981. const xx = x * x2, xy = x * y2, xz = x * z2;
  3982. const yy = y * y2, yz = y * z2, zz = z * z2;
  3983. const wx = w * x2, wy = w * y2, wz = w * z2;
  3984. const sx = scale.x, sy = scale.y, sz = scale.z;
  3985. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3986. te[ 1 ] = ( xy + wz ) * sx;
  3987. te[ 2 ] = ( xz - wy ) * sx;
  3988. te[ 3 ] = 0;
  3989. te[ 4 ] = ( xy - wz ) * sy;
  3990. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3991. te[ 6 ] = ( yz + wx ) * sy;
  3992. te[ 7 ] = 0;
  3993. te[ 8 ] = ( xz + wy ) * sz;
  3994. te[ 9 ] = ( yz - wx ) * sz;
  3995. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3996. te[ 11 ] = 0;
  3997. te[ 12 ] = position.x;
  3998. te[ 13 ] = position.y;
  3999. te[ 14 ] = position.z;
  4000. te[ 15 ] = 1;
  4001. return this;
  4002. }
  4003. decompose( position, quaternion, scale ) {
  4004. const te = this.elements;
  4005. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4006. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4007. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4008. // if determine is negative, we need to invert one scale
  4009. const det = this.determinant();
  4010. if ( det < 0 ) sx = - sx;
  4011. position.x = te[ 12 ];
  4012. position.y = te[ 13 ];
  4013. position.z = te[ 14 ];
  4014. // scale the rotation part
  4015. _m1$4.copy( this );
  4016. const invSX = 1 / sx;
  4017. const invSY = 1 / sy;
  4018. const invSZ = 1 / sz;
  4019. _m1$4.elements[ 0 ] *= invSX;
  4020. _m1$4.elements[ 1 ] *= invSX;
  4021. _m1$4.elements[ 2 ] *= invSX;
  4022. _m1$4.elements[ 4 ] *= invSY;
  4023. _m1$4.elements[ 5 ] *= invSY;
  4024. _m1$4.elements[ 6 ] *= invSY;
  4025. _m1$4.elements[ 8 ] *= invSZ;
  4026. _m1$4.elements[ 9 ] *= invSZ;
  4027. _m1$4.elements[ 10 ] *= invSZ;
  4028. quaternion.setFromRotationMatrix( _m1$4 );
  4029. scale.x = sx;
  4030. scale.y = sy;
  4031. scale.z = sz;
  4032. return this;
  4033. }
  4034. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4035. const te = this.elements;
  4036. const x = 2 * near / ( right - left );
  4037. const y = 2 * near / ( top - bottom );
  4038. const a = ( right + left ) / ( right - left );
  4039. const b = ( top + bottom ) / ( top - bottom );
  4040. let c, d;
  4041. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4042. c = - ( far + near ) / ( far - near );
  4043. d = ( - 2 * far * near ) / ( far - near );
  4044. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4045. c = - far / ( far - near );
  4046. d = ( - far * near ) / ( far - near );
  4047. } else {
  4048. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4049. }
  4050. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4051. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4052. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4053. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4054. return this;
  4055. }
  4056. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4057. const te = this.elements;
  4058. const w = 1.0 / ( right - left );
  4059. const h = 1.0 / ( top - bottom );
  4060. const p = 1.0 / ( far - near );
  4061. const x = ( right + left ) * w;
  4062. const y = ( top + bottom ) * h;
  4063. let z, zInv;
  4064. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4065. z = ( far + near ) * p;
  4066. zInv = - 2 * p;
  4067. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4068. z = near * p;
  4069. zInv = - 1 * p;
  4070. } else {
  4071. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4072. }
  4073. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4074. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4075. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4076. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4077. return this;
  4078. }
  4079. equals( matrix ) {
  4080. const te = this.elements;
  4081. const me = matrix.elements;
  4082. for ( let i = 0; i < 16; i ++ ) {
  4083. if ( te[ i ] !== me[ i ] ) return false;
  4084. }
  4085. return true;
  4086. }
  4087. fromArray( array, offset = 0 ) {
  4088. for ( let i = 0; i < 16; i ++ ) {
  4089. this.elements[ i ] = array[ i + offset ];
  4090. }
  4091. return this;
  4092. }
  4093. toArray( array = [], offset = 0 ) {
  4094. const te = this.elements;
  4095. array[ offset ] = te[ 0 ];
  4096. array[ offset + 1 ] = te[ 1 ];
  4097. array[ offset + 2 ] = te[ 2 ];
  4098. array[ offset + 3 ] = te[ 3 ];
  4099. array[ offset + 4 ] = te[ 4 ];
  4100. array[ offset + 5 ] = te[ 5 ];
  4101. array[ offset + 6 ] = te[ 6 ];
  4102. array[ offset + 7 ] = te[ 7 ];
  4103. array[ offset + 8 ] = te[ 8 ];
  4104. array[ offset + 9 ] = te[ 9 ];
  4105. array[ offset + 10 ] = te[ 10 ];
  4106. array[ offset + 11 ] = te[ 11 ];
  4107. array[ offset + 12 ] = te[ 12 ];
  4108. array[ offset + 13 ] = te[ 13 ];
  4109. array[ offset + 14 ] = te[ 14 ];
  4110. array[ offset + 15 ] = te[ 15 ];
  4111. return array;
  4112. }
  4113. }
  4114. const _v1$5 = /*@__PURE__*/ new Vector3();
  4115. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4116. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4117. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4118. const _x = /*@__PURE__*/ new Vector3();
  4119. const _y = /*@__PURE__*/ new Vector3();
  4120. const _z = /*@__PURE__*/ new Vector3();
  4121. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4122. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4123. class Euler {
  4124. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4125. this.isEuler = true;
  4126. this._x = x;
  4127. this._y = y;
  4128. this._z = z;
  4129. this._order = order;
  4130. }
  4131. get x() {
  4132. return this._x;
  4133. }
  4134. set x( value ) {
  4135. this._x = value;
  4136. this._onChangeCallback();
  4137. }
  4138. get y() {
  4139. return this._y;
  4140. }
  4141. set y( value ) {
  4142. this._y = value;
  4143. this._onChangeCallback();
  4144. }
  4145. get z() {
  4146. return this._z;
  4147. }
  4148. set z( value ) {
  4149. this._z = value;
  4150. this._onChangeCallback();
  4151. }
  4152. get order() {
  4153. return this._order;
  4154. }
  4155. set order( value ) {
  4156. this._order = value;
  4157. this._onChangeCallback();
  4158. }
  4159. set( x, y, z, order = this._order ) {
  4160. this._x = x;
  4161. this._y = y;
  4162. this._z = z;
  4163. this._order = order;
  4164. this._onChangeCallback();
  4165. return this;
  4166. }
  4167. clone() {
  4168. return new this.constructor( this._x, this._y, this._z, this._order );
  4169. }
  4170. copy( euler ) {
  4171. this._x = euler._x;
  4172. this._y = euler._y;
  4173. this._z = euler._z;
  4174. this._order = euler._order;
  4175. this._onChangeCallback();
  4176. return this;
  4177. }
  4178. setFromRotationMatrix( m, order = this._order, update = true ) {
  4179. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4180. const te = m.elements;
  4181. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4182. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4183. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4184. switch ( order ) {
  4185. case 'XYZ':
  4186. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4187. if ( Math.abs( m13 ) < 0.9999999 ) {
  4188. this._x = Math.atan2( - m23, m33 );
  4189. this._z = Math.atan2( - m12, m11 );
  4190. } else {
  4191. this._x = Math.atan2( m32, m22 );
  4192. this._z = 0;
  4193. }
  4194. break;
  4195. case 'YXZ':
  4196. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4197. if ( Math.abs( m23 ) < 0.9999999 ) {
  4198. this._y = Math.atan2( m13, m33 );
  4199. this._z = Math.atan2( m21, m22 );
  4200. } else {
  4201. this._y = Math.atan2( - m31, m11 );
  4202. this._z = 0;
  4203. }
  4204. break;
  4205. case 'ZXY':
  4206. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4207. if ( Math.abs( m32 ) < 0.9999999 ) {
  4208. this._y = Math.atan2( - m31, m33 );
  4209. this._z = Math.atan2( - m12, m22 );
  4210. } else {
  4211. this._y = 0;
  4212. this._z = Math.atan2( m21, m11 );
  4213. }
  4214. break;
  4215. case 'ZYX':
  4216. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4217. if ( Math.abs( m31 ) < 0.9999999 ) {
  4218. this._x = Math.atan2( m32, m33 );
  4219. this._z = Math.atan2( m21, m11 );
  4220. } else {
  4221. this._x = 0;
  4222. this._z = Math.atan2( - m12, m22 );
  4223. }
  4224. break;
  4225. case 'YZX':
  4226. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4227. if ( Math.abs( m21 ) < 0.9999999 ) {
  4228. this._x = Math.atan2( - m23, m22 );
  4229. this._y = Math.atan2( - m31, m11 );
  4230. } else {
  4231. this._x = 0;
  4232. this._y = Math.atan2( m13, m33 );
  4233. }
  4234. break;
  4235. case 'XZY':
  4236. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4237. if ( Math.abs( m12 ) < 0.9999999 ) {
  4238. this._x = Math.atan2( m32, m22 );
  4239. this._y = Math.atan2( m13, m11 );
  4240. } else {
  4241. this._x = Math.atan2( - m23, m33 );
  4242. this._y = 0;
  4243. }
  4244. break;
  4245. default:
  4246. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4247. }
  4248. this._order = order;
  4249. if ( update === true ) this._onChangeCallback();
  4250. return this;
  4251. }
  4252. setFromQuaternion( q, order, update ) {
  4253. _matrix$2.makeRotationFromQuaternion( q );
  4254. return this.setFromRotationMatrix( _matrix$2, order, update );
  4255. }
  4256. setFromVector3( v, order = this._order ) {
  4257. return this.set( v.x, v.y, v.z, order );
  4258. }
  4259. reorder( newOrder ) {
  4260. // WARNING: this discards revolution information -bhouston
  4261. _quaternion$3.setFromEuler( this );
  4262. return this.setFromQuaternion( _quaternion$3, newOrder );
  4263. }
  4264. equals( euler ) {
  4265. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4266. }
  4267. fromArray( array ) {
  4268. this._x = array[ 0 ];
  4269. this._y = array[ 1 ];
  4270. this._z = array[ 2 ];
  4271. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4272. this._onChangeCallback();
  4273. return this;
  4274. }
  4275. toArray( array = [], offset = 0 ) {
  4276. array[ offset ] = this._x;
  4277. array[ offset + 1 ] = this._y;
  4278. array[ offset + 2 ] = this._z;
  4279. array[ offset + 3 ] = this._order;
  4280. return array;
  4281. }
  4282. _onChange( callback ) {
  4283. this._onChangeCallback = callback;
  4284. return this;
  4285. }
  4286. _onChangeCallback() {}
  4287. *[ Symbol.iterator ]() {
  4288. yield this._x;
  4289. yield this._y;
  4290. yield this._z;
  4291. yield this._order;
  4292. }
  4293. }
  4294. Euler.DEFAULT_ORDER = 'XYZ';
  4295. class Layers {
  4296. constructor() {
  4297. this.mask = 1 | 0;
  4298. }
  4299. set( channel ) {
  4300. this.mask = ( 1 << channel | 0 ) >>> 0;
  4301. }
  4302. enable( channel ) {
  4303. this.mask |= 1 << channel | 0;
  4304. }
  4305. enableAll() {
  4306. this.mask = 0xffffffff | 0;
  4307. }
  4308. toggle( channel ) {
  4309. this.mask ^= 1 << channel | 0;
  4310. }
  4311. disable( channel ) {
  4312. this.mask &= ~ ( 1 << channel | 0 );
  4313. }
  4314. disableAll() {
  4315. this.mask = 0;
  4316. }
  4317. test( layers ) {
  4318. return ( this.mask & layers.mask ) !== 0;
  4319. }
  4320. isEnabled( channel ) {
  4321. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4322. }
  4323. }
  4324. let _object3DId = 0;
  4325. const _v1$4 = /*@__PURE__*/ new Vector3();
  4326. const _q1 = /*@__PURE__*/ new Quaternion();
  4327. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4328. const _target = /*@__PURE__*/ new Vector3();
  4329. const _position$3 = /*@__PURE__*/ new Vector3();
  4330. const _scale$2 = /*@__PURE__*/ new Vector3();
  4331. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4332. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4333. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4334. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4335. const _addedEvent = { type: 'added' };
  4336. const _removedEvent = { type: 'removed' };
  4337. const _childaddedEvent = { type: 'childadded', child: null };
  4338. const _childremovedEvent = { type: 'childremoved', child: null };
  4339. class Object3D extends EventDispatcher {
  4340. constructor() {
  4341. super();
  4342. this.isObject3D = true;
  4343. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4344. this.uuid = generateUUID();
  4345. this.name = '';
  4346. this.type = 'Object3D';
  4347. this.parent = null;
  4348. this.children = [];
  4349. this.up = Object3D.DEFAULT_UP.clone();
  4350. const position = new Vector3();
  4351. const rotation = new Euler();
  4352. const quaternion = new Quaternion();
  4353. const scale = new Vector3( 1, 1, 1 );
  4354. function onRotationChange() {
  4355. quaternion.setFromEuler( rotation, false );
  4356. }
  4357. function onQuaternionChange() {
  4358. rotation.setFromQuaternion( quaternion, undefined, false );
  4359. }
  4360. rotation._onChange( onRotationChange );
  4361. quaternion._onChange( onQuaternionChange );
  4362. Object.defineProperties( this, {
  4363. position: {
  4364. configurable: true,
  4365. enumerable: true,
  4366. value: position
  4367. },
  4368. rotation: {
  4369. configurable: true,
  4370. enumerable: true,
  4371. value: rotation
  4372. },
  4373. quaternion: {
  4374. configurable: true,
  4375. enumerable: true,
  4376. value: quaternion
  4377. },
  4378. scale: {
  4379. configurable: true,
  4380. enumerable: true,
  4381. value: scale
  4382. },
  4383. modelViewMatrix: {
  4384. value: new Matrix4()
  4385. },
  4386. normalMatrix: {
  4387. value: new Matrix3()
  4388. }
  4389. } );
  4390. this.matrix = new Matrix4();
  4391. this.matrixWorld = new Matrix4();
  4392. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4393. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4394. this.matrixWorldNeedsUpdate = false;
  4395. this.layers = new Layers();
  4396. this.visible = true;
  4397. this.castShadow = false;
  4398. this.receiveShadow = false;
  4399. this.frustumCulled = true;
  4400. this.renderOrder = 0;
  4401. this.animations = [];
  4402. this.userData = {};
  4403. }
  4404. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4405. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4406. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4407. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4408. applyMatrix4( matrix ) {
  4409. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4410. this.matrix.premultiply( matrix );
  4411. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4412. }
  4413. applyQuaternion( q ) {
  4414. this.quaternion.premultiply( q );
  4415. return this;
  4416. }
  4417. setRotationFromAxisAngle( axis, angle ) {
  4418. // assumes axis is normalized
  4419. this.quaternion.setFromAxisAngle( axis, angle );
  4420. }
  4421. setRotationFromEuler( euler ) {
  4422. this.quaternion.setFromEuler( euler, true );
  4423. }
  4424. setRotationFromMatrix( m ) {
  4425. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4426. this.quaternion.setFromRotationMatrix( m );
  4427. }
  4428. setRotationFromQuaternion( q ) {
  4429. // assumes q is normalized
  4430. this.quaternion.copy( q );
  4431. }
  4432. rotateOnAxis( axis, angle ) {
  4433. // rotate object on axis in object space
  4434. // axis is assumed to be normalized
  4435. _q1.setFromAxisAngle( axis, angle );
  4436. this.quaternion.multiply( _q1 );
  4437. return this;
  4438. }
  4439. rotateOnWorldAxis( axis, angle ) {
  4440. // rotate object on axis in world space
  4441. // axis is assumed to be normalized
  4442. // method assumes no rotated parent
  4443. _q1.setFromAxisAngle( axis, angle );
  4444. this.quaternion.premultiply( _q1 );
  4445. return this;
  4446. }
  4447. rotateX( angle ) {
  4448. return this.rotateOnAxis( _xAxis, angle );
  4449. }
  4450. rotateY( angle ) {
  4451. return this.rotateOnAxis( _yAxis, angle );
  4452. }
  4453. rotateZ( angle ) {
  4454. return this.rotateOnAxis( _zAxis, angle );
  4455. }
  4456. translateOnAxis( axis, distance ) {
  4457. // translate object by distance along axis in object space
  4458. // axis is assumed to be normalized
  4459. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4460. this.position.add( _v1$4.multiplyScalar( distance ) );
  4461. return this;
  4462. }
  4463. translateX( distance ) {
  4464. return this.translateOnAxis( _xAxis, distance );
  4465. }
  4466. translateY( distance ) {
  4467. return this.translateOnAxis( _yAxis, distance );
  4468. }
  4469. translateZ( distance ) {
  4470. return this.translateOnAxis( _zAxis, distance );
  4471. }
  4472. localToWorld( vector ) {
  4473. this.updateWorldMatrix( true, false );
  4474. return vector.applyMatrix4( this.matrixWorld );
  4475. }
  4476. worldToLocal( vector ) {
  4477. this.updateWorldMatrix( true, false );
  4478. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  4479. }
  4480. lookAt( x, y, z ) {
  4481. // This method does not support objects having non-uniformly-scaled parent(s)
  4482. if ( x.isVector3 ) {
  4483. _target.copy( x );
  4484. } else {
  4485. _target.set( x, y, z );
  4486. }
  4487. const parent = this.parent;
  4488. this.updateWorldMatrix( true, false );
  4489. _position$3.setFromMatrixPosition( this.matrixWorld );
  4490. if ( this.isCamera || this.isLight ) {
  4491. _m1$3.lookAt( _position$3, _target, this.up );
  4492. } else {
  4493. _m1$3.lookAt( _target, _position$3, this.up );
  4494. }
  4495. this.quaternion.setFromRotationMatrix( _m1$3 );
  4496. if ( parent ) {
  4497. _m1$3.extractRotation( parent.matrixWorld );
  4498. _q1.setFromRotationMatrix( _m1$3 );
  4499. this.quaternion.premultiply( _q1.invert() );
  4500. }
  4501. }
  4502. add( object ) {
  4503. if ( arguments.length > 1 ) {
  4504. for ( let i = 0; i < arguments.length; i ++ ) {
  4505. this.add( arguments[ i ] );
  4506. }
  4507. return this;
  4508. }
  4509. if ( object === this ) {
  4510. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4511. return this;
  4512. }
  4513. if ( object && object.isObject3D ) {
  4514. object.removeFromParent();
  4515. object.parent = this;
  4516. this.children.push( object );
  4517. object.dispatchEvent( _addedEvent );
  4518. _childaddedEvent.child = object;
  4519. this.dispatchEvent( _childaddedEvent );
  4520. _childaddedEvent.child = null;
  4521. } else {
  4522. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4523. }
  4524. return this;
  4525. }
  4526. remove( object ) {
  4527. if ( arguments.length > 1 ) {
  4528. for ( let i = 0; i < arguments.length; i ++ ) {
  4529. this.remove( arguments[ i ] );
  4530. }
  4531. return this;
  4532. }
  4533. const index = this.children.indexOf( object );
  4534. if ( index !== - 1 ) {
  4535. object.parent = null;
  4536. this.children.splice( index, 1 );
  4537. object.dispatchEvent( _removedEvent );
  4538. _childremovedEvent.child = object;
  4539. this.dispatchEvent( _childremovedEvent );
  4540. _childremovedEvent.child = null;
  4541. }
  4542. return this;
  4543. }
  4544. removeFromParent() {
  4545. const parent = this.parent;
  4546. if ( parent !== null ) {
  4547. parent.remove( this );
  4548. }
  4549. return this;
  4550. }
  4551. clear() {
  4552. return this.remove( ... this.children );
  4553. }
  4554. attach( object ) {
  4555. // adds object as a child of this, while maintaining the object's world transform
  4556. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4557. this.updateWorldMatrix( true, false );
  4558. _m1$3.copy( this.matrixWorld ).invert();
  4559. if ( object.parent !== null ) {
  4560. object.parent.updateWorldMatrix( true, false );
  4561. _m1$3.multiply( object.parent.matrixWorld );
  4562. }
  4563. object.applyMatrix4( _m1$3 );
  4564. object.removeFromParent();
  4565. object.parent = this;
  4566. this.children.push( object );
  4567. object.updateWorldMatrix( false, true );
  4568. object.dispatchEvent( _addedEvent );
  4569. _childaddedEvent.child = object;
  4570. this.dispatchEvent( _childaddedEvent );
  4571. _childaddedEvent.child = null;
  4572. return this;
  4573. }
  4574. getObjectById( id ) {
  4575. return this.getObjectByProperty( 'id', id );
  4576. }
  4577. getObjectByName( name ) {
  4578. return this.getObjectByProperty( 'name', name );
  4579. }
  4580. getObjectByProperty( name, value ) {
  4581. if ( this[ name ] === value ) return this;
  4582. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4583. const child = this.children[ i ];
  4584. const object = child.getObjectByProperty( name, value );
  4585. if ( object !== undefined ) {
  4586. return object;
  4587. }
  4588. }
  4589. return undefined;
  4590. }
  4591. getObjectsByProperty( name, value, result = [] ) {
  4592. if ( this[ name ] === value ) result.push( this );
  4593. const children = this.children;
  4594. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4595. children[ i ].getObjectsByProperty( name, value, result );
  4596. }
  4597. return result;
  4598. }
  4599. getWorldPosition( target ) {
  4600. this.updateWorldMatrix( true, false );
  4601. return target.setFromMatrixPosition( this.matrixWorld );
  4602. }
  4603. getWorldQuaternion( target ) {
  4604. this.updateWorldMatrix( true, false );
  4605. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4606. return target;
  4607. }
  4608. getWorldScale( target ) {
  4609. this.updateWorldMatrix( true, false );
  4610. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4611. return target;
  4612. }
  4613. getWorldDirection( target ) {
  4614. this.updateWorldMatrix( true, false );
  4615. const e = this.matrixWorld.elements;
  4616. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4617. }
  4618. raycast( /* raycaster, intersects */ ) {}
  4619. traverse( callback ) {
  4620. callback( this );
  4621. const children = this.children;
  4622. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4623. children[ i ].traverse( callback );
  4624. }
  4625. }
  4626. traverseVisible( callback ) {
  4627. if ( this.visible === false ) return;
  4628. callback( this );
  4629. const children = this.children;
  4630. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4631. children[ i ].traverseVisible( callback );
  4632. }
  4633. }
  4634. traverseAncestors( callback ) {
  4635. const parent = this.parent;
  4636. if ( parent !== null ) {
  4637. callback( parent );
  4638. parent.traverseAncestors( callback );
  4639. }
  4640. }
  4641. updateMatrix() {
  4642. this.matrix.compose( this.position, this.quaternion, this.scale );
  4643. this.matrixWorldNeedsUpdate = true;
  4644. }
  4645. updateMatrixWorld( force ) {
  4646. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4647. if ( this.matrixWorldNeedsUpdate || force ) {
  4648. if ( this.matrixWorldAutoUpdate === true ) {
  4649. if ( this.parent === null ) {
  4650. this.matrixWorld.copy( this.matrix );
  4651. } else {
  4652. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4653. }
  4654. }
  4655. this.matrixWorldNeedsUpdate = false;
  4656. force = true;
  4657. }
  4658. // make sure descendants are updated if required
  4659. const children = this.children;
  4660. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4661. const child = children[ i ];
  4662. child.updateMatrixWorld( force );
  4663. }
  4664. }
  4665. updateWorldMatrix( updateParents, updateChildren ) {
  4666. const parent = this.parent;
  4667. if ( updateParents === true && parent !== null ) {
  4668. parent.updateWorldMatrix( true, false );
  4669. }
  4670. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4671. if ( this.matrixWorldAutoUpdate === true ) {
  4672. if ( this.parent === null ) {
  4673. this.matrixWorld.copy( this.matrix );
  4674. } else {
  4675. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4676. }
  4677. }
  4678. // make sure descendants are updated
  4679. if ( updateChildren === true ) {
  4680. const children = this.children;
  4681. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4682. const child = children[ i ];
  4683. child.updateWorldMatrix( false, true );
  4684. }
  4685. }
  4686. }
  4687. toJSON( meta ) {
  4688. // meta is a string when called from JSON.stringify
  4689. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4690. const output = {};
  4691. // meta is a hash used to collect geometries, materials.
  4692. // not providing it implies that this is the root object
  4693. // being serialized.
  4694. if ( isRootObject ) {
  4695. // initialize meta obj
  4696. meta = {
  4697. geometries: {},
  4698. materials: {},
  4699. textures: {},
  4700. images: {},
  4701. shapes: {},
  4702. skeletons: {},
  4703. animations: {},
  4704. nodes: {}
  4705. };
  4706. output.metadata = {
  4707. version: 4.6,
  4708. type: 'Object',
  4709. generator: 'Object3D.toJSON'
  4710. };
  4711. }
  4712. // standard Object3D serialization
  4713. const object = {};
  4714. object.uuid = this.uuid;
  4715. object.type = this.type;
  4716. if ( this.name !== '' ) object.name = this.name;
  4717. if ( this.castShadow === true ) object.castShadow = true;
  4718. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4719. if ( this.visible === false ) object.visible = false;
  4720. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4721. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4722. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4723. object.layers = this.layers.mask;
  4724. object.matrix = this.matrix.toArray();
  4725. object.up = this.up.toArray();
  4726. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4727. // object specific properties
  4728. if ( this.isInstancedMesh ) {
  4729. object.type = 'InstancedMesh';
  4730. object.count = this.count;
  4731. object.instanceMatrix = this.instanceMatrix.toJSON();
  4732. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4733. }
  4734. if ( this.isBatchedMesh ) {
  4735. object.type = 'BatchedMesh';
  4736. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4737. object.sortObjects = this.sortObjects;
  4738. object.drawRanges = this._drawRanges;
  4739. object.reservedRanges = this._reservedRanges;
  4740. object.visibility = this._visibility;
  4741. object.active = this._active;
  4742. object.bounds = this._bounds.map( bound => ( {
  4743. boxInitialized: bound.boxInitialized,
  4744. boxMin: bound.box.min.toArray(),
  4745. boxMax: bound.box.max.toArray(),
  4746. sphereInitialized: bound.sphereInitialized,
  4747. sphereRadius: bound.sphere.radius,
  4748. sphereCenter: bound.sphere.center.toArray()
  4749. } ) );
  4750. object.maxInstanceCount = this._maxInstanceCount;
  4751. object.maxVertexCount = this._maxVertexCount;
  4752. object.maxIndexCount = this._maxIndexCount;
  4753. object.geometryInitialized = this._geometryInitialized;
  4754. object.geometryCount = this._geometryCount;
  4755. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4756. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4757. if ( this.boundingSphere !== null ) {
  4758. object.boundingSphere = {
  4759. center: object.boundingSphere.center.toArray(),
  4760. radius: object.boundingSphere.radius
  4761. };
  4762. }
  4763. if ( this.boundingBox !== null ) {
  4764. object.boundingBox = {
  4765. min: object.boundingBox.min.toArray(),
  4766. max: object.boundingBox.max.toArray()
  4767. };
  4768. }
  4769. }
  4770. //
  4771. function serialize( library, element ) {
  4772. if ( library[ element.uuid ] === undefined ) {
  4773. library[ element.uuid ] = element.toJSON( meta );
  4774. }
  4775. return element.uuid;
  4776. }
  4777. if ( this.isScene ) {
  4778. if ( this.background ) {
  4779. if ( this.background.isColor ) {
  4780. object.background = this.background.toJSON();
  4781. } else if ( this.background.isTexture ) {
  4782. object.background = this.background.toJSON( meta ).uuid;
  4783. }
  4784. }
  4785. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4786. object.environment = this.environment.toJSON( meta ).uuid;
  4787. }
  4788. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4789. object.geometry = serialize( meta.geometries, this.geometry );
  4790. const parameters = this.geometry.parameters;
  4791. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4792. const shapes = parameters.shapes;
  4793. if ( Array.isArray( shapes ) ) {
  4794. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4795. const shape = shapes[ i ];
  4796. serialize( meta.shapes, shape );
  4797. }
  4798. } else {
  4799. serialize( meta.shapes, shapes );
  4800. }
  4801. }
  4802. }
  4803. if ( this.isSkinnedMesh ) {
  4804. object.bindMode = this.bindMode;
  4805. object.bindMatrix = this.bindMatrix.toArray();
  4806. if ( this.skeleton !== undefined ) {
  4807. serialize( meta.skeletons, this.skeleton );
  4808. object.skeleton = this.skeleton.uuid;
  4809. }
  4810. }
  4811. if ( this.material !== undefined ) {
  4812. if ( Array.isArray( this.material ) ) {
  4813. const uuids = [];
  4814. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4815. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4816. }
  4817. object.material = uuids;
  4818. } else {
  4819. object.material = serialize( meta.materials, this.material );
  4820. }
  4821. }
  4822. //
  4823. if ( this.children.length > 0 ) {
  4824. object.children = [];
  4825. for ( let i = 0; i < this.children.length; i ++ ) {
  4826. object.children.push( this.children[ i ].toJSON( meta ).object );
  4827. }
  4828. }
  4829. //
  4830. if ( this.animations.length > 0 ) {
  4831. object.animations = [];
  4832. for ( let i = 0; i < this.animations.length; i ++ ) {
  4833. const animation = this.animations[ i ];
  4834. object.animations.push( serialize( meta.animations, animation ) );
  4835. }
  4836. }
  4837. if ( isRootObject ) {
  4838. const geometries = extractFromCache( meta.geometries );
  4839. const materials = extractFromCache( meta.materials );
  4840. const textures = extractFromCache( meta.textures );
  4841. const images = extractFromCache( meta.images );
  4842. const shapes = extractFromCache( meta.shapes );
  4843. const skeletons = extractFromCache( meta.skeletons );
  4844. const animations = extractFromCache( meta.animations );
  4845. const nodes = extractFromCache( meta.nodes );
  4846. if ( geometries.length > 0 ) output.geometries = geometries;
  4847. if ( materials.length > 0 ) output.materials = materials;
  4848. if ( textures.length > 0 ) output.textures = textures;
  4849. if ( images.length > 0 ) output.images = images;
  4850. if ( shapes.length > 0 ) output.shapes = shapes;
  4851. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4852. if ( animations.length > 0 ) output.animations = animations;
  4853. if ( nodes.length > 0 ) output.nodes = nodes;
  4854. }
  4855. output.object = object;
  4856. return output;
  4857. // extract data from the cache hash
  4858. // remove metadata on each item
  4859. // and return as array
  4860. function extractFromCache( cache ) {
  4861. const values = [];
  4862. for ( const key in cache ) {
  4863. const data = cache[ key ];
  4864. delete data.metadata;
  4865. values.push( data );
  4866. }
  4867. return values;
  4868. }
  4869. }
  4870. clone( recursive ) {
  4871. return new this.constructor().copy( this, recursive );
  4872. }
  4873. copy( source, recursive = true ) {
  4874. this.name = source.name;
  4875. this.up.copy( source.up );
  4876. this.position.copy( source.position );
  4877. this.rotation.order = source.rotation.order;
  4878. this.quaternion.copy( source.quaternion );
  4879. this.scale.copy( source.scale );
  4880. this.matrix.copy( source.matrix );
  4881. this.matrixWorld.copy( source.matrixWorld );
  4882. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4883. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4884. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4885. this.layers.mask = source.layers.mask;
  4886. this.visible = source.visible;
  4887. this.castShadow = source.castShadow;
  4888. this.receiveShadow = source.receiveShadow;
  4889. this.frustumCulled = source.frustumCulled;
  4890. this.renderOrder = source.renderOrder;
  4891. this.animations = source.animations.slice();
  4892. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4893. if ( recursive === true ) {
  4894. for ( let i = 0; i < source.children.length; i ++ ) {
  4895. const child = source.children[ i ];
  4896. this.add( child.clone() );
  4897. }
  4898. }
  4899. return this;
  4900. }
  4901. }
  4902. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4903. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4904. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4905. const _v0$2 = /*@__PURE__*/ new Vector3();
  4906. const _v1$3 = /*@__PURE__*/ new Vector3();
  4907. const _v2$2 = /*@__PURE__*/ new Vector3();
  4908. const _v3$2 = /*@__PURE__*/ new Vector3();
  4909. const _vab = /*@__PURE__*/ new Vector3();
  4910. const _vac = /*@__PURE__*/ new Vector3();
  4911. const _vbc = /*@__PURE__*/ new Vector3();
  4912. const _vap = /*@__PURE__*/ new Vector3();
  4913. const _vbp = /*@__PURE__*/ new Vector3();
  4914. const _vcp = /*@__PURE__*/ new Vector3();
  4915. class Triangle {
  4916. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4917. this.a = a;
  4918. this.b = b;
  4919. this.c = c;
  4920. }
  4921. static getNormal( a, b, c, target ) {
  4922. target.subVectors( c, b );
  4923. _v0$2.subVectors( a, b );
  4924. target.cross( _v0$2 );
  4925. const targetLengthSq = target.lengthSq();
  4926. if ( targetLengthSq > 0 ) {
  4927. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4928. }
  4929. return target.set( 0, 0, 0 );
  4930. }
  4931. // static/instance method to calculate barycentric coordinates
  4932. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4933. static getBarycoord( point, a, b, c, target ) {
  4934. _v0$2.subVectors( c, a );
  4935. _v1$3.subVectors( b, a );
  4936. _v2$2.subVectors( point, a );
  4937. const dot00 = _v0$2.dot( _v0$2 );
  4938. const dot01 = _v0$2.dot( _v1$3 );
  4939. const dot02 = _v0$2.dot( _v2$2 );
  4940. const dot11 = _v1$3.dot( _v1$3 );
  4941. const dot12 = _v1$3.dot( _v2$2 );
  4942. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4943. // collinear or singular triangle
  4944. if ( denom === 0 ) {
  4945. target.set( 0, 0, 0 );
  4946. return null;
  4947. }
  4948. const invDenom = 1 / denom;
  4949. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4950. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4951. // barycentric coordinates must always sum to 1
  4952. return target.set( 1 - u - v, v, u );
  4953. }
  4954. static containsPoint( point, a, b, c ) {
  4955. // if the triangle is degenerate then we can't contain a point
  4956. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4957. return false;
  4958. }
  4959. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4960. }
  4961. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4962. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4963. target.x = 0;
  4964. target.y = 0;
  4965. if ( 'z' in target ) target.z = 0;
  4966. if ( 'w' in target ) target.w = 0;
  4967. return null;
  4968. }
  4969. target.setScalar( 0 );
  4970. target.addScaledVector( v1, _v3$2.x );
  4971. target.addScaledVector( v2, _v3$2.y );
  4972. target.addScaledVector( v3, _v3$2.z );
  4973. return target;
  4974. }
  4975. static isFrontFacing( a, b, c, direction ) {
  4976. _v0$2.subVectors( c, b );
  4977. _v1$3.subVectors( a, b );
  4978. // strictly front facing
  4979. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4980. }
  4981. set( a, b, c ) {
  4982. this.a.copy( a );
  4983. this.b.copy( b );
  4984. this.c.copy( c );
  4985. return this;
  4986. }
  4987. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4988. this.a.copy( points[ i0 ] );
  4989. this.b.copy( points[ i1 ] );
  4990. this.c.copy( points[ i2 ] );
  4991. return this;
  4992. }
  4993. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4994. this.a.fromBufferAttribute( attribute, i0 );
  4995. this.b.fromBufferAttribute( attribute, i1 );
  4996. this.c.fromBufferAttribute( attribute, i2 );
  4997. return this;
  4998. }
  4999. clone() {
  5000. return new this.constructor().copy( this );
  5001. }
  5002. copy( triangle ) {
  5003. this.a.copy( triangle.a );
  5004. this.b.copy( triangle.b );
  5005. this.c.copy( triangle.c );
  5006. return this;
  5007. }
  5008. getArea() {
  5009. _v0$2.subVectors( this.c, this.b );
  5010. _v1$3.subVectors( this.a, this.b );
  5011. return _v0$2.cross( _v1$3 ).length() * 0.5;
  5012. }
  5013. getMidpoint( target ) {
  5014. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5015. }
  5016. getNormal( target ) {
  5017. return Triangle.getNormal( this.a, this.b, this.c, target );
  5018. }
  5019. getPlane( target ) {
  5020. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5021. }
  5022. getBarycoord( point, target ) {
  5023. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5024. }
  5025. getInterpolation( point, v1, v2, v3, target ) {
  5026. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5027. }
  5028. containsPoint( point ) {
  5029. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5030. }
  5031. isFrontFacing( direction ) {
  5032. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5033. }
  5034. intersectsBox( box ) {
  5035. return box.intersectsTriangle( this );
  5036. }
  5037. closestPointToPoint( p, target ) {
  5038. const a = this.a, b = this.b, c = this.c;
  5039. let v, w;
  5040. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5041. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5042. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5043. // basically, we're distinguishing which of the voronoi regions of the triangle
  5044. // the point lies in with the minimum amount of redundant computation.
  5045. _vab.subVectors( b, a );
  5046. _vac.subVectors( c, a );
  5047. _vap.subVectors( p, a );
  5048. const d1 = _vab.dot( _vap );
  5049. const d2 = _vac.dot( _vap );
  5050. if ( d1 <= 0 && d2 <= 0 ) {
  5051. // vertex region of A; barycentric coords (1, 0, 0)
  5052. return target.copy( a );
  5053. }
  5054. _vbp.subVectors( p, b );
  5055. const d3 = _vab.dot( _vbp );
  5056. const d4 = _vac.dot( _vbp );
  5057. if ( d3 >= 0 && d4 <= d3 ) {
  5058. // vertex region of B; barycentric coords (0, 1, 0)
  5059. return target.copy( b );
  5060. }
  5061. const vc = d1 * d4 - d3 * d2;
  5062. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5063. v = d1 / ( d1 - d3 );
  5064. // edge region of AB; barycentric coords (1-v, v, 0)
  5065. return target.copy( a ).addScaledVector( _vab, v );
  5066. }
  5067. _vcp.subVectors( p, c );
  5068. const d5 = _vab.dot( _vcp );
  5069. const d6 = _vac.dot( _vcp );
  5070. if ( d6 >= 0 && d5 <= d6 ) {
  5071. // vertex region of C; barycentric coords (0, 0, 1)
  5072. return target.copy( c );
  5073. }
  5074. const vb = d5 * d2 - d1 * d6;
  5075. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5076. w = d2 / ( d2 - d6 );
  5077. // edge region of AC; barycentric coords (1-w, 0, w)
  5078. return target.copy( a ).addScaledVector( _vac, w );
  5079. }
  5080. const va = d3 * d6 - d5 * d4;
  5081. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5082. _vbc.subVectors( c, b );
  5083. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5084. // edge region of BC; barycentric coords (0, 1-w, w)
  5085. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5086. }
  5087. // face region
  5088. const denom = 1 / ( va + vb + vc );
  5089. // u = va * denom
  5090. v = vb * denom;
  5091. w = vc * denom;
  5092. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5093. }
  5094. equals( triangle ) {
  5095. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5096. }
  5097. }
  5098. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5099. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5100. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5101. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5102. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5103. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5104. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5105. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5106. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5107. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5108. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5109. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5110. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5111. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5112. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5113. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5114. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5115. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5116. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5117. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5118. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5119. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5120. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5121. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5122. const _hslA = { h: 0, s: 0, l: 0 };
  5123. const _hslB = { h: 0, s: 0, l: 0 };
  5124. function hue2rgb( p, q, t ) {
  5125. if ( t < 0 ) t += 1;
  5126. if ( t > 1 ) t -= 1;
  5127. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5128. if ( t < 1 / 2 ) return q;
  5129. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5130. return p;
  5131. }
  5132. class Color {
  5133. constructor( r, g, b ) {
  5134. this.isColor = true;
  5135. this.r = 1;
  5136. this.g = 1;
  5137. this.b = 1;
  5138. return this.set( r, g, b );
  5139. }
  5140. set( r, g, b ) {
  5141. if ( g === undefined && b === undefined ) {
  5142. // r is THREE.Color, hex or string
  5143. const value = r;
  5144. if ( value && value.isColor ) {
  5145. this.copy( value );
  5146. } else if ( typeof value === 'number' ) {
  5147. this.setHex( value );
  5148. } else if ( typeof value === 'string' ) {
  5149. this.setStyle( value );
  5150. }
  5151. } else {
  5152. this.setRGB( r, g, b );
  5153. }
  5154. return this;
  5155. }
  5156. setScalar( scalar ) {
  5157. this.r = scalar;
  5158. this.g = scalar;
  5159. this.b = scalar;
  5160. return this;
  5161. }
  5162. setHex( hex, colorSpace = SRGBColorSpace ) {
  5163. hex = Math.floor( hex );
  5164. this.r = ( hex >> 16 & 255 ) / 255;
  5165. this.g = ( hex >> 8 & 255 ) / 255;
  5166. this.b = ( hex & 255 ) / 255;
  5167. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5168. return this;
  5169. }
  5170. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5171. this.r = r;
  5172. this.g = g;
  5173. this.b = b;
  5174. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5175. return this;
  5176. }
  5177. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5178. // h,s,l ranges are in 0.0 - 1.0
  5179. h = euclideanModulo( h, 1 );
  5180. s = clamp( s, 0, 1 );
  5181. l = clamp( l, 0, 1 );
  5182. if ( s === 0 ) {
  5183. this.r = this.g = this.b = l;
  5184. } else {
  5185. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5186. const q = ( 2 * l ) - p;
  5187. this.r = hue2rgb( q, p, h + 1 / 3 );
  5188. this.g = hue2rgb( q, p, h );
  5189. this.b = hue2rgb( q, p, h - 1 / 3 );
  5190. }
  5191. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5192. return this;
  5193. }
  5194. setStyle( style, colorSpace = SRGBColorSpace ) {
  5195. function handleAlpha( string ) {
  5196. if ( string === undefined ) return;
  5197. if ( parseFloat( string ) < 1 ) {
  5198. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5199. }
  5200. }
  5201. let m;
  5202. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5203. // rgb / hsl
  5204. let color;
  5205. const name = m[ 1 ];
  5206. const components = m[ 2 ];
  5207. switch ( name ) {
  5208. case 'rgb':
  5209. case 'rgba':
  5210. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5211. // rgb(255,0,0) rgba(255,0,0,0.5)
  5212. handleAlpha( color[ 4 ] );
  5213. return this.setRGB(
  5214. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5215. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5216. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5217. colorSpace
  5218. );
  5219. }
  5220. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5221. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5222. handleAlpha( color[ 4 ] );
  5223. return this.setRGB(
  5224. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5225. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5226. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5227. colorSpace
  5228. );
  5229. }
  5230. break;
  5231. case 'hsl':
  5232. case 'hsla':
  5233. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5234. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5235. handleAlpha( color[ 4 ] );
  5236. return this.setHSL(
  5237. parseFloat( color[ 1 ] ) / 360,
  5238. parseFloat( color[ 2 ] ) / 100,
  5239. parseFloat( color[ 3 ] ) / 100,
  5240. colorSpace
  5241. );
  5242. }
  5243. break;
  5244. default:
  5245. console.warn( 'THREE.Color: Unknown color model ' + style );
  5246. }
  5247. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5248. // hex color
  5249. const hex = m[ 1 ];
  5250. const size = hex.length;
  5251. if ( size === 3 ) {
  5252. // #ff0
  5253. return this.setRGB(
  5254. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5255. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5256. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5257. colorSpace
  5258. );
  5259. } else if ( size === 6 ) {
  5260. // #ff0000
  5261. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5262. } else {
  5263. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5264. }
  5265. } else if ( style && style.length > 0 ) {
  5266. return this.setColorName( style, colorSpace );
  5267. }
  5268. return this;
  5269. }
  5270. setColorName( style, colorSpace = SRGBColorSpace ) {
  5271. // color keywords
  5272. const hex = _colorKeywords[ style.toLowerCase() ];
  5273. if ( hex !== undefined ) {
  5274. // red
  5275. this.setHex( hex, colorSpace );
  5276. } else {
  5277. // unknown color
  5278. console.warn( 'THREE.Color: Unknown color ' + style );
  5279. }
  5280. return this;
  5281. }
  5282. clone() {
  5283. return new this.constructor( this.r, this.g, this.b );
  5284. }
  5285. copy( color ) {
  5286. this.r = color.r;
  5287. this.g = color.g;
  5288. this.b = color.b;
  5289. return this;
  5290. }
  5291. copySRGBToLinear( color ) {
  5292. this.r = SRGBToLinear( color.r );
  5293. this.g = SRGBToLinear( color.g );
  5294. this.b = SRGBToLinear( color.b );
  5295. return this;
  5296. }
  5297. copyLinearToSRGB( color ) {
  5298. this.r = LinearToSRGB( color.r );
  5299. this.g = LinearToSRGB( color.g );
  5300. this.b = LinearToSRGB( color.b );
  5301. return this;
  5302. }
  5303. convertSRGBToLinear() {
  5304. this.copySRGBToLinear( this );
  5305. return this;
  5306. }
  5307. convertLinearToSRGB() {
  5308. this.copyLinearToSRGB( this );
  5309. return this;
  5310. }
  5311. getHex( colorSpace = SRGBColorSpace ) {
  5312. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5313. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  5314. }
  5315. getHexString( colorSpace = SRGBColorSpace ) {
  5316. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5317. }
  5318. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5319. // h,s,l ranges are in 0.0 - 1.0
  5320. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5321. const r = _color.r, g = _color.g, b = _color.b;
  5322. const max = Math.max( r, g, b );
  5323. const min = Math.min( r, g, b );
  5324. let hue, saturation;
  5325. const lightness = ( min + max ) / 2.0;
  5326. if ( min === max ) {
  5327. hue = 0;
  5328. saturation = 0;
  5329. } else {
  5330. const delta = max - min;
  5331. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5332. switch ( max ) {
  5333. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5334. case g: hue = ( b - r ) / delta + 2; break;
  5335. case b: hue = ( r - g ) / delta + 4; break;
  5336. }
  5337. hue /= 6;
  5338. }
  5339. target.h = hue;
  5340. target.s = saturation;
  5341. target.l = lightness;
  5342. return target;
  5343. }
  5344. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5345. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5346. target.r = _color.r;
  5347. target.g = _color.g;
  5348. target.b = _color.b;
  5349. return target;
  5350. }
  5351. getStyle( colorSpace = SRGBColorSpace ) {
  5352. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5353. const r = _color.r, g = _color.g, b = _color.b;
  5354. if ( colorSpace !== SRGBColorSpace ) {
  5355. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5356. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5357. }
  5358. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5359. }
  5360. offsetHSL( h, s, l ) {
  5361. this.getHSL( _hslA );
  5362. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5363. }
  5364. add( color ) {
  5365. this.r += color.r;
  5366. this.g += color.g;
  5367. this.b += color.b;
  5368. return this;
  5369. }
  5370. addColors( color1, color2 ) {
  5371. this.r = color1.r + color2.r;
  5372. this.g = color1.g + color2.g;
  5373. this.b = color1.b + color2.b;
  5374. return this;
  5375. }
  5376. addScalar( s ) {
  5377. this.r += s;
  5378. this.g += s;
  5379. this.b += s;
  5380. return this;
  5381. }
  5382. sub( color ) {
  5383. this.r = Math.max( 0, this.r - color.r );
  5384. this.g = Math.max( 0, this.g - color.g );
  5385. this.b = Math.max( 0, this.b - color.b );
  5386. return this;
  5387. }
  5388. multiply( color ) {
  5389. this.r *= color.r;
  5390. this.g *= color.g;
  5391. this.b *= color.b;
  5392. return this;
  5393. }
  5394. multiplyScalar( s ) {
  5395. this.r *= s;
  5396. this.g *= s;
  5397. this.b *= s;
  5398. return this;
  5399. }
  5400. lerp( color, alpha ) {
  5401. this.r += ( color.r - this.r ) * alpha;
  5402. this.g += ( color.g - this.g ) * alpha;
  5403. this.b += ( color.b - this.b ) * alpha;
  5404. return this;
  5405. }
  5406. lerpColors( color1, color2, alpha ) {
  5407. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5408. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5409. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5410. return this;
  5411. }
  5412. lerpHSL( color, alpha ) {
  5413. this.getHSL( _hslA );
  5414. color.getHSL( _hslB );
  5415. const h = lerp( _hslA.h, _hslB.h, alpha );
  5416. const s = lerp( _hslA.s, _hslB.s, alpha );
  5417. const l = lerp( _hslA.l, _hslB.l, alpha );
  5418. this.setHSL( h, s, l );
  5419. return this;
  5420. }
  5421. setFromVector3( v ) {
  5422. this.r = v.x;
  5423. this.g = v.y;
  5424. this.b = v.z;
  5425. return this;
  5426. }
  5427. applyMatrix3( m ) {
  5428. const r = this.r, g = this.g, b = this.b;
  5429. const e = m.elements;
  5430. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5431. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5432. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5433. return this;
  5434. }
  5435. equals( c ) {
  5436. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5437. }
  5438. fromArray( array, offset = 0 ) {
  5439. this.r = array[ offset ];
  5440. this.g = array[ offset + 1 ];
  5441. this.b = array[ offset + 2 ];
  5442. return this;
  5443. }
  5444. toArray( array = [], offset = 0 ) {
  5445. array[ offset ] = this.r;
  5446. array[ offset + 1 ] = this.g;
  5447. array[ offset + 2 ] = this.b;
  5448. return array;
  5449. }
  5450. fromBufferAttribute( attribute, index ) {
  5451. this.r = attribute.getX( index );
  5452. this.g = attribute.getY( index );
  5453. this.b = attribute.getZ( index );
  5454. return this;
  5455. }
  5456. toJSON() {
  5457. return this.getHex();
  5458. }
  5459. *[ Symbol.iterator ]() {
  5460. yield this.r;
  5461. yield this.g;
  5462. yield this.b;
  5463. }
  5464. }
  5465. const _color = /*@__PURE__*/ new Color();
  5466. Color.NAMES = _colorKeywords;
  5467. let _materialId = 0;
  5468. class Material extends EventDispatcher {
  5469. constructor() {
  5470. super();
  5471. this.isMaterial = true;
  5472. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5473. this.uuid = generateUUID();
  5474. this.name = '';
  5475. this.type = 'Material';
  5476. this.blending = NormalBlending;
  5477. this.side = FrontSide;
  5478. this.vertexColors = false;
  5479. this.opacity = 1;
  5480. this.transparent = false;
  5481. this.alphaHash = false;
  5482. this.blendSrc = SrcAlphaFactor;
  5483. this.blendDst = OneMinusSrcAlphaFactor;
  5484. this.blendEquation = AddEquation;
  5485. this.blendSrcAlpha = null;
  5486. this.blendDstAlpha = null;
  5487. this.blendEquationAlpha = null;
  5488. this.blendColor = new Color( 0, 0, 0 );
  5489. this.blendAlpha = 0;
  5490. this.depthFunc = LessEqualDepth;
  5491. this.depthTest = true;
  5492. this.depthWrite = true;
  5493. this.stencilWriteMask = 0xff;
  5494. this.stencilFunc = AlwaysStencilFunc;
  5495. this.stencilRef = 0;
  5496. this.stencilFuncMask = 0xff;
  5497. this.stencilFail = KeepStencilOp;
  5498. this.stencilZFail = KeepStencilOp;
  5499. this.stencilZPass = KeepStencilOp;
  5500. this.stencilWrite = false;
  5501. this.clippingPlanes = null;
  5502. this.clipIntersection = false;
  5503. this.clipShadows = false;
  5504. this.shadowSide = null;
  5505. this.colorWrite = true;
  5506. this.precision = null; // override the renderer's default precision for this material
  5507. this.polygonOffset = false;
  5508. this.polygonOffsetFactor = 0;
  5509. this.polygonOffsetUnits = 0;
  5510. this.dithering = false;
  5511. this.alphaToCoverage = false;
  5512. this.premultipliedAlpha = false;
  5513. this.forceSinglePass = false;
  5514. this.visible = true;
  5515. this.toneMapped = true;
  5516. this.userData = {};
  5517. this.version = 0;
  5518. this._alphaTest = 0;
  5519. }
  5520. get alphaTest() {
  5521. return this._alphaTest;
  5522. }
  5523. set alphaTest( value ) {
  5524. if ( this._alphaTest > 0 !== value > 0 ) {
  5525. this.version ++;
  5526. }
  5527. this._alphaTest = value;
  5528. }
  5529. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5530. customProgramCacheKey() {
  5531. return this.onBeforeCompile.toString();
  5532. }
  5533. setValues( values ) {
  5534. if ( values === undefined ) return;
  5535. for ( const key in values ) {
  5536. const newValue = values[ key ];
  5537. if ( newValue === undefined ) {
  5538. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5539. continue;
  5540. }
  5541. const currentValue = this[ key ];
  5542. if ( currentValue === undefined ) {
  5543. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5544. continue;
  5545. }
  5546. if ( currentValue && currentValue.isColor ) {
  5547. currentValue.set( newValue );
  5548. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5549. currentValue.copy( newValue );
  5550. } else {
  5551. this[ key ] = newValue;
  5552. }
  5553. }
  5554. }
  5555. toJSON( meta ) {
  5556. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5557. if ( isRootObject ) {
  5558. meta = {
  5559. textures: {},
  5560. images: {}
  5561. };
  5562. }
  5563. const data = {
  5564. metadata: {
  5565. version: 4.6,
  5566. type: 'Material',
  5567. generator: 'Material.toJSON'
  5568. }
  5569. };
  5570. // standard Material serialization
  5571. data.uuid = this.uuid;
  5572. data.type = this.type;
  5573. if ( this.name !== '' ) data.name = this.name;
  5574. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5575. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5576. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5577. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5578. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5579. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5580. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5581. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5582. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5583. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5584. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5585. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5586. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5587. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5588. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5589. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5590. }
  5591. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5592. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5593. }
  5594. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5595. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5596. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5597. }
  5598. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5599. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5600. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5601. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5602. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5603. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5604. }
  5605. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5606. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5607. }
  5608. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5609. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5610. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5611. data.anisotropyMap = this.anisotropyMap.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.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5649. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5650. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5651. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5652. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5653. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5654. }
  5655. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5656. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5657. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5658. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5659. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5660. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5661. if ( this.size !== undefined ) data.size = this.size;
  5662. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5663. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5664. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5665. if ( this.side !== FrontSide ) data.side = this.side;
  5666. if ( this.vertexColors === true ) data.vertexColors = true;
  5667. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5668. if ( this.transparent === true ) data.transparent = true;
  5669. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5670. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5671. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5672. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5673. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5674. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5675. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5676. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5677. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5678. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5679. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5680. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5681. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5682. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5683. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5684. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5685. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5686. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5687. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5688. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5689. // rotation (SpriteMaterial)
  5690. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5691. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5692. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5693. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5694. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5695. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5696. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5697. if ( this.scale !== undefined ) data.scale = this.scale;
  5698. if ( this.dithering === true ) data.dithering = true;
  5699. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5700. if ( this.alphaHash === true ) data.alphaHash = true;
  5701. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5702. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5703. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5704. if ( this.wireframe === true ) data.wireframe = true;
  5705. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5706. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5707. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5708. if ( this.flatShading === true ) data.flatShading = true;
  5709. if ( this.visible === false ) data.visible = false;
  5710. if ( this.toneMapped === false ) data.toneMapped = false;
  5711. if ( this.fog === false ) data.fog = false;
  5712. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5713. // TODO: Copied from Object3D.toJSON
  5714. function extractFromCache( cache ) {
  5715. const values = [];
  5716. for ( const key in cache ) {
  5717. const data = cache[ key ];
  5718. delete data.metadata;
  5719. values.push( data );
  5720. }
  5721. return values;
  5722. }
  5723. if ( isRootObject ) {
  5724. const textures = extractFromCache( meta.textures );
  5725. const images = extractFromCache( meta.images );
  5726. if ( textures.length > 0 ) data.textures = textures;
  5727. if ( images.length > 0 ) data.images = images;
  5728. }
  5729. return data;
  5730. }
  5731. clone() {
  5732. return new this.constructor().copy( this );
  5733. }
  5734. copy( source ) {
  5735. this.name = source.name;
  5736. this.blending = source.blending;
  5737. this.side = source.side;
  5738. this.vertexColors = source.vertexColors;
  5739. this.opacity = source.opacity;
  5740. this.transparent = source.transparent;
  5741. this.blendSrc = source.blendSrc;
  5742. this.blendDst = source.blendDst;
  5743. this.blendEquation = source.blendEquation;
  5744. this.blendSrcAlpha = source.blendSrcAlpha;
  5745. this.blendDstAlpha = source.blendDstAlpha;
  5746. this.blendEquationAlpha = source.blendEquationAlpha;
  5747. this.blendColor.copy( source.blendColor );
  5748. this.blendAlpha = source.blendAlpha;
  5749. this.depthFunc = source.depthFunc;
  5750. this.depthTest = source.depthTest;
  5751. this.depthWrite = source.depthWrite;
  5752. this.stencilWriteMask = source.stencilWriteMask;
  5753. this.stencilFunc = source.stencilFunc;
  5754. this.stencilRef = source.stencilRef;
  5755. this.stencilFuncMask = source.stencilFuncMask;
  5756. this.stencilFail = source.stencilFail;
  5757. this.stencilZFail = source.stencilZFail;
  5758. this.stencilZPass = source.stencilZPass;
  5759. this.stencilWrite = source.stencilWrite;
  5760. const srcPlanes = source.clippingPlanes;
  5761. let dstPlanes = null;
  5762. if ( srcPlanes !== null ) {
  5763. const n = srcPlanes.length;
  5764. dstPlanes = new Array( n );
  5765. for ( let i = 0; i !== n; ++ i ) {
  5766. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5767. }
  5768. }
  5769. this.clippingPlanes = dstPlanes;
  5770. this.clipIntersection = source.clipIntersection;
  5771. this.clipShadows = source.clipShadows;
  5772. this.shadowSide = source.shadowSide;
  5773. this.colorWrite = source.colorWrite;
  5774. this.precision = source.precision;
  5775. this.polygonOffset = source.polygonOffset;
  5776. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5777. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5778. this.dithering = source.dithering;
  5779. this.alphaTest = source.alphaTest;
  5780. this.alphaHash = source.alphaHash;
  5781. this.alphaToCoverage = source.alphaToCoverage;
  5782. this.premultipliedAlpha = source.premultipliedAlpha;
  5783. this.forceSinglePass = source.forceSinglePass;
  5784. this.visible = source.visible;
  5785. this.toneMapped = source.toneMapped;
  5786. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5787. return this;
  5788. }
  5789. dispose() {
  5790. this.dispatchEvent( { type: 'dispose' } );
  5791. }
  5792. set needsUpdate( value ) {
  5793. if ( value === true ) this.version ++;
  5794. }
  5795. onBuild( /* shaderobject, renderer */ ) {
  5796. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5797. }
  5798. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {
  5799. console.warn( 'Material: onBeforeRender() has been removed.' ); // @deprecated, r166
  5800. }
  5801. }
  5802. class MeshBasicMaterial extends Material {
  5803. constructor( parameters ) {
  5804. super();
  5805. this.isMeshBasicMaterial = true;
  5806. this.type = 'MeshBasicMaterial';
  5807. this.color = new Color( 0xffffff ); // emissive
  5808. this.map = null;
  5809. this.lightMap = null;
  5810. this.lightMapIntensity = 1.0;
  5811. this.aoMap = null;
  5812. this.aoMapIntensity = 1.0;
  5813. this.specularMap = null;
  5814. this.alphaMap = null;
  5815. this.envMap = null;
  5816. this.envMapRotation = new Euler();
  5817. this.combine = MultiplyOperation;
  5818. this.reflectivity = 1;
  5819. this.refractionRatio = 0.98;
  5820. this.wireframe = false;
  5821. this.wireframeLinewidth = 1;
  5822. this.wireframeLinecap = 'round';
  5823. this.wireframeLinejoin = 'round';
  5824. this.fog = true;
  5825. this.setValues( parameters );
  5826. }
  5827. copy( source ) {
  5828. super.copy( source );
  5829. this.color.copy( source.color );
  5830. this.map = source.map;
  5831. this.lightMap = source.lightMap;
  5832. this.lightMapIntensity = source.lightMapIntensity;
  5833. this.aoMap = source.aoMap;
  5834. this.aoMapIntensity = source.aoMapIntensity;
  5835. this.specularMap = source.specularMap;
  5836. this.alphaMap = source.alphaMap;
  5837. this.envMap = source.envMap;
  5838. this.envMapRotation.copy( source.envMapRotation );
  5839. this.combine = source.combine;
  5840. this.reflectivity = source.reflectivity;
  5841. this.refractionRatio = source.refractionRatio;
  5842. this.wireframe = source.wireframe;
  5843. this.wireframeLinewidth = source.wireframeLinewidth;
  5844. this.wireframeLinecap = source.wireframeLinecap;
  5845. this.wireframeLinejoin = source.wireframeLinejoin;
  5846. this.fog = source.fog;
  5847. return this;
  5848. }
  5849. }
  5850. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5851. const _tables = /*@__PURE__*/ _generateTables();
  5852. function _generateTables() {
  5853. // float32 to float16 helpers
  5854. const buffer = new ArrayBuffer( 4 );
  5855. const floatView = new Float32Array( buffer );
  5856. const uint32View = new Uint32Array( buffer );
  5857. const baseTable = new Uint32Array( 512 );
  5858. const shiftTable = new Uint32Array( 512 );
  5859. for ( let i = 0; i < 256; ++ i ) {
  5860. const e = i - 127;
  5861. // very small number (0, -0)
  5862. if ( e < - 27 ) {
  5863. baseTable[ i ] = 0x0000;
  5864. baseTable[ i | 0x100 ] = 0x8000;
  5865. shiftTable[ i ] = 24;
  5866. shiftTable[ i | 0x100 ] = 24;
  5867. // small number (denorm)
  5868. } else if ( e < - 14 ) {
  5869. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5870. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5871. shiftTable[ i ] = - e - 1;
  5872. shiftTable[ i | 0x100 ] = - e - 1;
  5873. // normal number
  5874. } else if ( e <= 15 ) {
  5875. baseTable[ i ] = ( e + 15 ) << 10;
  5876. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5877. shiftTable[ i ] = 13;
  5878. shiftTable[ i | 0x100 ] = 13;
  5879. // large number (Infinity, -Infinity)
  5880. } else if ( e < 128 ) {
  5881. baseTable[ i ] = 0x7c00;
  5882. baseTable[ i | 0x100 ] = 0xfc00;
  5883. shiftTable[ i ] = 24;
  5884. shiftTable[ i | 0x100 ] = 24;
  5885. // stay (NaN, Infinity, -Infinity)
  5886. } else {
  5887. baseTable[ i ] = 0x7c00;
  5888. baseTable[ i | 0x100 ] = 0xfc00;
  5889. shiftTable[ i ] = 13;
  5890. shiftTable[ i | 0x100 ] = 13;
  5891. }
  5892. }
  5893. // float16 to float32 helpers
  5894. const mantissaTable = new Uint32Array( 2048 );
  5895. const exponentTable = new Uint32Array( 64 );
  5896. const offsetTable = new Uint32Array( 64 );
  5897. for ( let i = 1; i < 1024; ++ i ) {
  5898. let m = i << 13; // zero pad mantissa bits
  5899. let e = 0; // zero exponent
  5900. // normalized
  5901. while ( ( m & 0x00800000 ) === 0 ) {
  5902. m <<= 1;
  5903. e -= 0x00800000; // decrement exponent
  5904. }
  5905. m &= ~ 0x00800000; // clear leading 1 bit
  5906. e += 0x38800000; // adjust bias
  5907. mantissaTable[ i ] = m | e;
  5908. }
  5909. for ( let i = 1024; i < 2048; ++ i ) {
  5910. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5911. }
  5912. for ( let i = 1; i < 31; ++ i ) {
  5913. exponentTable[ i ] = i << 23;
  5914. }
  5915. exponentTable[ 31 ] = 0x47800000;
  5916. exponentTable[ 32 ] = 0x80000000;
  5917. for ( let i = 33; i < 63; ++ i ) {
  5918. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5919. }
  5920. exponentTable[ 63 ] = 0xc7800000;
  5921. for ( let i = 1; i < 64; ++ i ) {
  5922. if ( i !== 32 ) {
  5923. offsetTable[ i ] = 1024;
  5924. }
  5925. }
  5926. return {
  5927. floatView: floatView,
  5928. uint32View: uint32View,
  5929. baseTable: baseTable,
  5930. shiftTable: shiftTable,
  5931. mantissaTable: mantissaTable,
  5932. exponentTable: exponentTable,
  5933. offsetTable: offsetTable
  5934. };
  5935. }
  5936. // float32 to float16
  5937. function toHalfFloat( val ) {
  5938. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5939. val = clamp( val, - 65504, 65504 );
  5940. _tables.floatView[ 0 ] = val;
  5941. const f = _tables.uint32View[ 0 ];
  5942. const e = ( f >> 23 ) & 0x1ff;
  5943. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5944. }
  5945. // float16 to float32
  5946. function fromHalfFloat( val ) {
  5947. const m = val >> 10;
  5948. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5949. return _tables.floatView[ 0 ];
  5950. }
  5951. const DataUtils = {
  5952. toHalfFloat: toHalfFloat,
  5953. fromHalfFloat: fromHalfFloat,
  5954. };
  5955. const _vector$9 = /*@__PURE__*/ new Vector3();
  5956. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5957. class BufferAttribute {
  5958. constructor( array, itemSize, normalized = false ) {
  5959. if ( Array.isArray( array ) ) {
  5960. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5961. }
  5962. this.isBufferAttribute = true;
  5963. this.name = '';
  5964. this.array = array;
  5965. this.itemSize = itemSize;
  5966. this.count = array !== undefined ? array.length / itemSize : 0;
  5967. this.normalized = normalized;
  5968. this.usage = StaticDrawUsage;
  5969. this._updateRange = { offset: 0, count: - 1 };
  5970. this.updateRanges = [];
  5971. this.gpuType = FloatType;
  5972. this.version = 0;
  5973. }
  5974. onUploadCallback() {}
  5975. set needsUpdate( value ) {
  5976. if ( value === true ) this.version ++;
  5977. }
  5978. get updateRange() {
  5979. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5980. return this._updateRange;
  5981. }
  5982. setUsage( value ) {
  5983. this.usage = value;
  5984. return this;
  5985. }
  5986. addUpdateRange( start, count ) {
  5987. this.updateRanges.push( { start, count } );
  5988. }
  5989. clearUpdateRanges() {
  5990. this.updateRanges.length = 0;
  5991. }
  5992. copy( source ) {
  5993. this.name = source.name;
  5994. this.array = new source.array.constructor( source.array );
  5995. this.itemSize = source.itemSize;
  5996. this.count = source.count;
  5997. this.normalized = source.normalized;
  5998. this.usage = source.usage;
  5999. this.gpuType = source.gpuType;
  6000. return this;
  6001. }
  6002. copyAt( index1, attribute, index2 ) {
  6003. index1 *= this.itemSize;
  6004. index2 *= attribute.itemSize;
  6005. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6006. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6007. }
  6008. return this;
  6009. }
  6010. copyArray( array ) {
  6011. this.array.set( array );
  6012. return this;
  6013. }
  6014. applyMatrix3( m ) {
  6015. if ( this.itemSize === 2 ) {
  6016. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6017. _vector2$1.fromBufferAttribute( this, i );
  6018. _vector2$1.applyMatrix3( m );
  6019. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6020. }
  6021. } else if ( this.itemSize === 3 ) {
  6022. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6023. _vector$9.fromBufferAttribute( this, i );
  6024. _vector$9.applyMatrix3( m );
  6025. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6026. }
  6027. }
  6028. return this;
  6029. }
  6030. applyMatrix4( m ) {
  6031. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6032. _vector$9.fromBufferAttribute( this, i );
  6033. _vector$9.applyMatrix4( m );
  6034. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6035. }
  6036. return this;
  6037. }
  6038. applyNormalMatrix( m ) {
  6039. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6040. _vector$9.fromBufferAttribute( this, i );
  6041. _vector$9.applyNormalMatrix( m );
  6042. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6043. }
  6044. return this;
  6045. }
  6046. transformDirection( m ) {
  6047. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6048. _vector$9.fromBufferAttribute( this, i );
  6049. _vector$9.transformDirection( m );
  6050. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6051. }
  6052. return this;
  6053. }
  6054. set( value, offset = 0 ) {
  6055. // Matching BufferAttribute constructor, do not normalize the array.
  6056. this.array.set( value, offset );
  6057. return this;
  6058. }
  6059. getComponent( index, component ) {
  6060. let value = this.array[ index * this.itemSize + component ];
  6061. if ( this.normalized ) value = denormalize( value, this.array );
  6062. return value;
  6063. }
  6064. setComponent( index, component, value ) {
  6065. if ( this.normalized ) value = normalize( value, this.array );
  6066. this.array[ index * this.itemSize + component ] = value;
  6067. return this;
  6068. }
  6069. getX( index ) {
  6070. let x = this.array[ index * this.itemSize ];
  6071. if ( this.normalized ) x = denormalize( x, this.array );
  6072. return x;
  6073. }
  6074. setX( index, x ) {
  6075. if ( this.normalized ) x = normalize( x, this.array );
  6076. this.array[ index * this.itemSize ] = x;
  6077. return this;
  6078. }
  6079. getY( index ) {
  6080. let y = this.array[ index * this.itemSize + 1 ];
  6081. if ( this.normalized ) y = denormalize( y, this.array );
  6082. return y;
  6083. }
  6084. setY( index, y ) {
  6085. if ( this.normalized ) y = normalize( y, this.array );
  6086. this.array[ index * this.itemSize + 1 ] = y;
  6087. return this;
  6088. }
  6089. getZ( index ) {
  6090. let z = this.array[ index * this.itemSize + 2 ];
  6091. if ( this.normalized ) z = denormalize( z, this.array );
  6092. return z;
  6093. }
  6094. setZ( index, z ) {
  6095. if ( this.normalized ) z = normalize( z, this.array );
  6096. this.array[ index * this.itemSize + 2 ] = z;
  6097. return this;
  6098. }
  6099. getW( index ) {
  6100. let w = this.array[ index * this.itemSize + 3 ];
  6101. if ( this.normalized ) w = denormalize( w, this.array );
  6102. return w;
  6103. }
  6104. setW( index, w ) {
  6105. if ( this.normalized ) w = normalize( w, this.array );
  6106. this.array[ index * this.itemSize + 3 ] = w;
  6107. return this;
  6108. }
  6109. setXY( index, x, y ) {
  6110. index *= this.itemSize;
  6111. if ( this.normalized ) {
  6112. x = normalize( x, this.array );
  6113. y = normalize( y, this.array );
  6114. }
  6115. this.array[ index + 0 ] = x;
  6116. this.array[ index + 1 ] = y;
  6117. return this;
  6118. }
  6119. setXYZ( index, x, y, z ) {
  6120. index *= this.itemSize;
  6121. if ( this.normalized ) {
  6122. x = normalize( x, this.array );
  6123. y = normalize( y, this.array );
  6124. z = normalize( z, this.array );
  6125. }
  6126. this.array[ index + 0 ] = x;
  6127. this.array[ index + 1 ] = y;
  6128. this.array[ index + 2 ] = z;
  6129. return this;
  6130. }
  6131. setXYZW( index, x, y, z, w ) {
  6132. index *= this.itemSize;
  6133. if ( this.normalized ) {
  6134. x = normalize( x, this.array );
  6135. y = normalize( y, this.array );
  6136. z = normalize( z, this.array );
  6137. w = normalize( w, this.array );
  6138. }
  6139. this.array[ index + 0 ] = x;
  6140. this.array[ index + 1 ] = y;
  6141. this.array[ index + 2 ] = z;
  6142. this.array[ index + 3 ] = w;
  6143. return this;
  6144. }
  6145. onUpload( callback ) {
  6146. this.onUploadCallback = callback;
  6147. return this;
  6148. }
  6149. clone() {
  6150. return new this.constructor( this.array, this.itemSize ).copy( this );
  6151. }
  6152. toJSON() {
  6153. const data = {
  6154. itemSize: this.itemSize,
  6155. type: this.array.constructor.name,
  6156. array: Array.from( this.array ),
  6157. normalized: this.normalized
  6158. };
  6159. if ( this.name !== '' ) data.name = this.name;
  6160. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6161. return data;
  6162. }
  6163. }
  6164. //
  6165. class Int8BufferAttribute extends BufferAttribute {
  6166. constructor( array, itemSize, normalized ) {
  6167. super( new Int8Array( array ), itemSize, normalized );
  6168. }
  6169. }
  6170. class Uint8BufferAttribute extends BufferAttribute {
  6171. constructor( array, itemSize, normalized ) {
  6172. super( new Uint8Array( array ), itemSize, normalized );
  6173. }
  6174. }
  6175. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6176. constructor( array, itemSize, normalized ) {
  6177. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6178. }
  6179. }
  6180. class Int16BufferAttribute extends BufferAttribute {
  6181. constructor( array, itemSize, normalized ) {
  6182. super( new Int16Array( array ), itemSize, normalized );
  6183. }
  6184. }
  6185. class Uint16BufferAttribute extends BufferAttribute {
  6186. constructor( array, itemSize, normalized ) {
  6187. super( new Uint16Array( array ), itemSize, normalized );
  6188. }
  6189. }
  6190. class Int32BufferAttribute extends BufferAttribute {
  6191. constructor( array, itemSize, normalized ) {
  6192. super( new Int32Array( array ), itemSize, normalized );
  6193. }
  6194. }
  6195. class Uint32BufferAttribute extends BufferAttribute {
  6196. constructor( array, itemSize, normalized ) {
  6197. super( new Uint32Array( array ), itemSize, normalized );
  6198. }
  6199. }
  6200. class Float16BufferAttribute extends BufferAttribute {
  6201. constructor( array, itemSize, normalized ) {
  6202. super( new Uint16Array( array ), itemSize, normalized );
  6203. this.isFloat16BufferAttribute = true;
  6204. }
  6205. getX( index ) {
  6206. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6207. if ( this.normalized ) x = denormalize( x, this.array );
  6208. return x;
  6209. }
  6210. setX( index, x ) {
  6211. if ( this.normalized ) x = normalize( x, this.array );
  6212. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6213. return this;
  6214. }
  6215. getY( index ) {
  6216. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6217. if ( this.normalized ) y = denormalize( y, this.array );
  6218. return y;
  6219. }
  6220. setY( index, y ) {
  6221. if ( this.normalized ) y = normalize( y, this.array );
  6222. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6223. return this;
  6224. }
  6225. getZ( index ) {
  6226. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6227. if ( this.normalized ) z = denormalize( z, this.array );
  6228. return z;
  6229. }
  6230. setZ( index, z ) {
  6231. if ( this.normalized ) z = normalize( z, this.array );
  6232. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6233. return this;
  6234. }
  6235. getW( index ) {
  6236. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6237. if ( this.normalized ) w = denormalize( w, this.array );
  6238. return w;
  6239. }
  6240. setW( index, w ) {
  6241. if ( this.normalized ) w = normalize( w, this.array );
  6242. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6243. return this;
  6244. }
  6245. setXY( index, x, y ) {
  6246. index *= this.itemSize;
  6247. if ( this.normalized ) {
  6248. x = normalize( x, this.array );
  6249. y = normalize( y, this.array );
  6250. }
  6251. this.array[ index + 0 ] = toHalfFloat( x );
  6252. this.array[ index + 1 ] = toHalfFloat( y );
  6253. return this;
  6254. }
  6255. setXYZ( index, x, y, z ) {
  6256. index *= this.itemSize;
  6257. if ( this.normalized ) {
  6258. x = normalize( x, this.array );
  6259. y = normalize( y, this.array );
  6260. z = normalize( z, this.array );
  6261. }
  6262. this.array[ index + 0 ] = toHalfFloat( x );
  6263. this.array[ index + 1 ] = toHalfFloat( y );
  6264. this.array[ index + 2 ] = toHalfFloat( z );
  6265. return this;
  6266. }
  6267. setXYZW( index, x, y, z, w ) {
  6268. index *= this.itemSize;
  6269. if ( this.normalized ) {
  6270. x = normalize( x, this.array );
  6271. y = normalize( y, this.array );
  6272. z = normalize( z, this.array );
  6273. w = normalize( w, this.array );
  6274. }
  6275. this.array[ index + 0 ] = toHalfFloat( x );
  6276. this.array[ index + 1 ] = toHalfFloat( y );
  6277. this.array[ index + 2 ] = toHalfFloat( z );
  6278. this.array[ index + 3 ] = toHalfFloat( w );
  6279. return this;
  6280. }
  6281. }
  6282. class Float32BufferAttribute extends BufferAttribute {
  6283. constructor( array, itemSize, normalized ) {
  6284. super( new Float32Array( array ), itemSize, normalized );
  6285. }
  6286. }
  6287. let _id$2 = 0;
  6288. const _m1$2 = /*@__PURE__*/ new Matrix4();
  6289. const _obj = /*@__PURE__*/ new Object3D();
  6290. const _offset = /*@__PURE__*/ new Vector3();
  6291. const _box$2 = /*@__PURE__*/ new Box3();
  6292. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6293. const _vector$8 = /*@__PURE__*/ new Vector3();
  6294. class BufferGeometry extends EventDispatcher {
  6295. constructor() {
  6296. super();
  6297. this.isBufferGeometry = true;
  6298. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6299. this.uuid = generateUUID();
  6300. this.name = '';
  6301. this.type = 'BufferGeometry';
  6302. this.index = null;
  6303. this.attributes = {};
  6304. this.morphAttributes = {};
  6305. this.morphTargetsRelative = false;
  6306. this.groups = [];
  6307. this.boundingBox = null;
  6308. this.boundingSphere = null;
  6309. this.drawRange = { start: 0, count: Infinity };
  6310. this.userData = {};
  6311. }
  6312. getIndex() {
  6313. return this.index;
  6314. }
  6315. setIndex( index ) {
  6316. if ( Array.isArray( index ) ) {
  6317. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6318. } else {
  6319. this.index = index;
  6320. }
  6321. return this;
  6322. }
  6323. getAttribute( name ) {
  6324. return this.attributes[ name ];
  6325. }
  6326. setAttribute( name, attribute ) {
  6327. this.attributes[ name ] = attribute;
  6328. return this;
  6329. }
  6330. deleteAttribute( name ) {
  6331. delete this.attributes[ name ];
  6332. return this;
  6333. }
  6334. hasAttribute( name ) {
  6335. return this.attributes[ name ] !== undefined;
  6336. }
  6337. addGroup( start, count, materialIndex = 0 ) {
  6338. this.groups.push( {
  6339. start: start,
  6340. count: count,
  6341. materialIndex: materialIndex
  6342. } );
  6343. }
  6344. clearGroups() {
  6345. this.groups = [];
  6346. }
  6347. setDrawRange( start, count ) {
  6348. this.drawRange.start = start;
  6349. this.drawRange.count = count;
  6350. }
  6351. applyMatrix4( matrix ) {
  6352. const position = this.attributes.position;
  6353. if ( position !== undefined ) {
  6354. position.applyMatrix4( matrix );
  6355. position.needsUpdate = true;
  6356. }
  6357. const normal = this.attributes.normal;
  6358. if ( normal !== undefined ) {
  6359. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6360. normal.applyNormalMatrix( normalMatrix );
  6361. normal.needsUpdate = true;
  6362. }
  6363. const tangent = this.attributes.tangent;
  6364. if ( tangent !== undefined ) {
  6365. tangent.transformDirection( matrix );
  6366. tangent.needsUpdate = true;
  6367. }
  6368. if ( this.boundingBox !== null ) {
  6369. this.computeBoundingBox();
  6370. }
  6371. if ( this.boundingSphere !== null ) {
  6372. this.computeBoundingSphere();
  6373. }
  6374. return this;
  6375. }
  6376. applyQuaternion( q ) {
  6377. _m1$2.makeRotationFromQuaternion( q );
  6378. this.applyMatrix4( _m1$2 );
  6379. return this;
  6380. }
  6381. rotateX( angle ) {
  6382. // rotate geometry around world x-axis
  6383. _m1$2.makeRotationX( angle );
  6384. this.applyMatrix4( _m1$2 );
  6385. return this;
  6386. }
  6387. rotateY( angle ) {
  6388. // rotate geometry around world y-axis
  6389. _m1$2.makeRotationY( angle );
  6390. this.applyMatrix4( _m1$2 );
  6391. return this;
  6392. }
  6393. rotateZ( angle ) {
  6394. // rotate geometry around world z-axis
  6395. _m1$2.makeRotationZ( angle );
  6396. this.applyMatrix4( _m1$2 );
  6397. return this;
  6398. }
  6399. translate( x, y, z ) {
  6400. // translate geometry
  6401. _m1$2.makeTranslation( x, y, z );
  6402. this.applyMatrix4( _m1$2 );
  6403. return this;
  6404. }
  6405. scale( x, y, z ) {
  6406. // scale geometry
  6407. _m1$2.makeScale( x, y, z );
  6408. this.applyMatrix4( _m1$2 );
  6409. return this;
  6410. }
  6411. lookAt( vector ) {
  6412. _obj.lookAt( vector );
  6413. _obj.updateMatrix();
  6414. this.applyMatrix4( _obj.matrix );
  6415. return this;
  6416. }
  6417. center() {
  6418. this.computeBoundingBox();
  6419. this.boundingBox.getCenter( _offset ).negate();
  6420. this.translate( _offset.x, _offset.y, _offset.z );
  6421. return this;
  6422. }
  6423. setFromPoints( points ) {
  6424. const position = [];
  6425. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6426. const point = points[ i ];
  6427. position.push( point.x, point.y, point.z || 0 );
  6428. }
  6429. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6430. return this;
  6431. }
  6432. computeBoundingBox() {
  6433. if ( this.boundingBox === null ) {
  6434. this.boundingBox = new Box3();
  6435. }
  6436. const position = this.attributes.position;
  6437. const morphAttributesPosition = this.morphAttributes.position;
  6438. if ( position && position.isGLBufferAttribute ) {
  6439. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6440. this.boundingBox.set(
  6441. new Vector3( - Infinity, - Infinity, - Infinity ),
  6442. new Vector3( + Infinity, + Infinity, + Infinity )
  6443. );
  6444. return;
  6445. }
  6446. if ( position !== undefined ) {
  6447. this.boundingBox.setFromBufferAttribute( position );
  6448. // process morph attributes if present
  6449. if ( morphAttributesPosition ) {
  6450. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6451. const morphAttribute = morphAttributesPosition[ i ];
  6452. _box$2.setFromBufferAttribute( morphAttribute );
  6453. if ( this.morphTargetsRelative ) {
  6454. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6455. this.boundingBox.expandByPoint( _vector$8 );
  6456. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6457. this.boundingBox.expandByPoint( _vector$8 );
  6458. } else {
  6459. this.boundingBox.expandByPoint( _box$2.min );
  6460. this.boundingBox.expandByPoint( _box$2.max );
  6461. }
  6462. }
  6463. }
  6464. } else {
  6465. this.boundingBox.makeEmpty();
  6466. }
  6467. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6468. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6469. }
  6470. }
  6471. computeBoundingSphere() {
  6472. if ( this.boundingSphere === null ) {
  6473. this.boundingSphere = new Sphere();
  6474. }
  6475. const position = this.attributes.position;
  6476. const morphAttributesPosition = this.morphAttributes.position;
  6477. if ( position && position.isGLBufferAttribute ) {
  6478. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6479. this.boundingSphere.set( new Vector3(), Infinity );
  6480. return;
  6481. }
  6482. if ( position ) {
  6483. // first, find the center of the bounding sphere
  6484. const center = this.boundingSphere.center;
  6485. _box$2.setFromBufferAttribute( position );
  6486. // process morph attributes if present
  6487. if ( morphAttributesPosition ) {
  6488. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6489. const morphAttribute = morphAttributesPosition[ i ];
  6490. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6491. if ( this.morphTargetsRelative ) {
  6492. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6493. _box$2.expandByPoint( _vector$8 );
  6494. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6495. _box$2.expandByPoint( _vector$8 );
  6496. } else {
  6497. _box$2.expandByPoint( _boxMorphTargets.min );
  6498. _box$2.expandByPoint( _boxMorphTargets.max );
  6499. }
  6500. }
  6501. }
  6502. _box$2.getCenter( center );
  6503. // second, try to find a boundingSphere with a radius smaller than the
  6504. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6505. let maxRadiusSq = 0;
  6506. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6507. _vector$8.fromBufferAttribute( position, i );
  6508. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6509. }
  6510. // process morph attributes if present
  6511. if ( morphAttributesPosition ) {
  6512. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6513. const morphAttribute = morphAttributesPosition[ i ];
  6514. const morphTargetsRelative = this.morphTargetsRelative;
  6515. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6516. _vector$8.fromBufferAttribute( morphAttribute, j );
  6517. if ( morphTargetsRelative ) {
  6518. _offset.fromBufferAttribute( position, j );
  6519. _vector$8.add( _offset );
  6520. }
  6521. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6522. }
  6523. }
  6524. }
  6525. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6526. if ( isNaN( this.boundingSphere.radius ) ) {
  6527. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6528. }
  6529. }
  6530. }
  6531. computeTangents() {
  6532. const index = this.index;
  6533. const attributes = this.attributes;
  6534. // based on http://www.terathon.com/code/tangent.html
  6535. // (per vertex tangents)
  6536. if ( index === null ||
  6537. attributes.position === undefined ||
  6538. attributes.normal === undefined ||
  6539. attributes.uv === undefined ) {
  6540. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6541. return;
  6542. }
  6543. const positionAttribute = attributes.position;
  6544. const normalAttribute = attributes.normal;
  6545. const uvAttribute = attributes.uv;
  6546. if ( this.hasAttribute( 'tangent' ) === false ) {
  6547. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6548. }
  6549. const tangentAttribute = this.getAttribute( 'tangent' );
  6550. const tan1 = [], tan2 = [];
  6551. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6552. tan1[ i ] = new Vector3();
  6553. tan2[ i ] = new Vector3();
  6554. }
  6555. const vA = new Vector3(),
  6556. vB = new Vector3(),
  6557. vC = new Vector3(),
  6558. uvA = new Vector2(),
  6559. uvB = new Vector2(),
  6560. uvC = new Vector2(),
  6561. sdir = new Vector3(),
  6562. tdir = new Vector3();
  6563. function handleTriangle( a, b, c ) {
  6564. vA.fromBufferAttribute( positionAttribute, a );
  6565. vB.fromBufferAttribute( positionAttribute, b );
  6566. vC.fromBufferAttribute( positionAttribute, c );
  6567. uvA.fromBufferAttribute( uvAttribute, a );
  6568. uvB.fromBufferAttribute( uvAttribute, b );
  6569. uvC.fromBufferAttribute( uvAttribute, c );
  6570. vB.sub( vA );
  6571. vC.sub( vA );
  6572. uvB.sub( uvA );
  6573. uvC.sub( uvA );
  6574. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6575. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6576. if ( ! isFinite( r ) ) return;
  6577. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6578. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6579. tan1[ a ].add( sdir );
  6580. tan1[ b ].add( sdir );
  6581. tan1[ c ].add( sdir );
  6582. tan2[ a ].add( tdir );
  6583. tan2[ b ].add( tdir );
  6584. tan2[ c ].add( tdir );
  6585. }
  6586. let groups = this.groups;
  6587. if ( groups.length === 0 ) {
  6588. groups = [ {
  6589. start: 0,
  6590. count: index.count
  6591. } ];
  6592. }
  6593. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6594. const group = groups[ i ];
  6595. const start = group.start;
  6596. const count = group.count;
  6597. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6598. handleTriangle(
  6599. index.getX( j + 0 ),
  6600. index.getX( j + 1 ),
  6601. index.getX( j + 2 )
  6602. );
  6603. }
  6604. }
  6605. const tmp = new Vector3(), tmp2 = new Vector3();
  6606. const n = new Vector3(), n2 = new Vector3();
  6607. function handleVertex( v ) {
  6608. n.fromBufferAttribute( normalAttribute, v );
  6609. n2.copy( n );
  6610. const t = tan1[ v ];
  6611. // Gram-Schmidt orthogonalize
  6612. tmp.copy( t );
  6613. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6614. // Calculate handedness
  6615. tmp2.crossVectors( n2, t );
  6616. const test = tmp2.dot( tan2[ v ] );
  6617. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6618. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6619. }
  6620. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6621. const group = groups[ i ];
  6622. const start = group.start;
  6623. const count = group.count;
  6624. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6625. handleVertex( index.getX( j + 0 ) );
  6626. handleVertex( index.getX( j + 1 ) );
  6627. handleVertex( index.getX( j + 2 ) );
  6628. }
  6629. }
  6630. }
  6631. computeVertexNormals() {
  6632. const index = this.index;
  6633. const positionAttribute = this.getAttribute( 'position' );
  6634. if ( positionAttribute !== undefined ) {
  6635. let normalAttribute = this.getAttribute( 'normal' );
  6636. if ( normalAttribute === undefined ) {
  6637. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6638. this.setAttribute( 'normal', normalAttribute );
  6639. } else {
  6640. // reset existing normals to zero
  6641. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6642. normalAttribute.setXYZ( i, 0, 0, 0 );
  6643. }
  6644. }
  6645. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6646. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6647. const cb = new Vector3(), ab = new Vector3();
  6648. // indexed elements
  6649. if ( index ) {
  6650. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6651. const vA = index.getX( i + 0 );
  6652. const vB = index.getX( i + 1 );
  6653. const vC = index.getX( i + 2 );
  6654. pA.fromBufferAttribute( positionAttribute, vA );
  6655. pB.fromBufferAttribute( positionAttribute, vB );
  6656. pC.fromBufferAttribute( positionAttribute, vC );
  6657. cb.subVectors( pC, pB );
  6658. ab.subVectors( pA, pB );
  6659. cb.cross( ab );
  6660. nA.fromBufferAttribute( normalAttribute, vA );
  6661. nB.fromBufferAttribute( normalAttribute, vB );
  6662. nC.fromBufferAttribute( normalAttribute, vC );
  6663. nA.add( cb );
  6664. nB.add( cb );
  6665. nC.add( cb );
  6666. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6667. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6668. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6669. }
  6670. } else {
  6671. // non-indexed elements (unconnected triangle soup)
  6672. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6673. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6674. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6675. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6676. cb.subVectors( pC, pB );
  6677. ab.subVectors( pA, pB );
  6678. cb.cross( ab );
  6679. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6680. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6681. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6682. }
  6683. }
  6684. this.normalizeNormals();
  6685. normalAttribute.needsUpdate = true;
  6686. }
  6687. }
  6688. normalizeNormals() {
  6689. const normals = this.attributes.normal;
  6690. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6691. _vector$8.fromBufferAttribute( normals, i );
  6692. _vector$8.normalize();
  6693. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6694. }
  6695. }
  6696. toNonIndexed() {
  6697. function convertBufferAttribute( attribute, indices ) {
  6698. const array = attribute.array;
  6699. const itemSize = attribute.itemSize;
  6700. const normalized = attribute.normalized;
  6701. const array2 = new array.constructor( indices.length * itemSize );
  6702. let index = 0, index2 = 0;
  6703. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6704. if ( attribute.isInterleavedBufferAttribute ) {
  6705. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6706. } else {
  6707. index = indices[ i ] * itemSize;
  6708. }
  6709. for ( let j = 0; j < itemSize; j ++ ) {
  6710. array2[ index2 ++ ] = array[ index ++ ];
  6711. }
  6712. }
  6713. return new BufferAttribute( array2, itemSize, normalized );
  6714. }
  6715. //
  6716. if ( this.index === null ) {
  6717. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6718. return this;
  6719. }
  6720. const geometry2 = new BufferGeometry();
  6721. const indices = this.index.array;
  6722. const attributes = this.attributes;
  6723. // attributes
  6724. for ( const name in attributes ) {
  6725. const attribute = attributes[ name ];
  6726. const newAttribute = convertBufferAttribute( attribute, indices );
  6727. geometry2.setAttribute( name, newAttribute );
  6728. }
  6729. // morph attributes
  6730. const morphAttributes = this.morphAttributes;
  6731. for ( const name in morphAttributes ) {
  6732. const morphArray = [];
  6733. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6734. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6735. const attribute = morphAttribute[ i ];
  6736. const newAttribute = convertBufferAttribute( attribute, indices );
  6737. morphArray.push( newAttribute );
  6738. }
  6739. geometry2.morphAttributes[ name ] = morphArray;
  6740. }
  6741. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6742. // groups
  6743. const groups = this.groups;
  6744. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6745. const group = groups[ i ];
  6746. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6747. }
  6748. return geometry2;
  6749. }
  6750. toJSON() {
  6751. const data = {
  6752. metadata: {
  6753. version: 4.6,
  6754. type: 'BufferGeometry',
  6755. generator: 'BufferGeometry.toJSON'
  6756. }
  6757. };
  6758. // standard BufferGeometry serialization
  6759. data.uuid = this.uuid;
  6760. data.type = this.type;
  6761. if ( this.name !== '' ) data.name = this.name;
  6762. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6763. if ( this.parameters !== undefined ) {
  6764. const parameters = this.parameters;
  6765. for ( const key in parameters ) {
  6766. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6767. }
  6768. return data;
  6769. }
  6770. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6771. data.data = { attributes: {} };
  6772. const index = this.index;
  6773. if ( index !== null ) {
  6774. data.data.index = {
  6775. type: index.array.constructor.name,
  6776. array: Array.prototype.slice.call( index.array )
  6777. };
  6778. }
  6779. const attributes = this.attributes;
  6780. for ( const key in attributes ) {
  6781. const attribute = attributes[ key ];
  6782. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6783. }
  6784. const morphAttributes = {};
  6785. let hasMorphAttributes = false;
  6786. for ( const key in this.morphAttributes ) {
  6787. const attributeArray = this.morphAttributes[ key ];
  6788. const array = [];
  6789. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6790. const attribute = attributeArray[ i ];
  6791. array.push( attribute.toJSON( data.data ) );
  6792. }
  6793. if ( array.length > 0 ) {
  6794. morphAttributes[ key ] = array;
  6795. hasMorphAttributes = true;
  6796. }
  6797. }
  6798. if ( hasMorphAttributes ) {
  6799. data.data.morphAttributes = morphAttributes;
  6800. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6801. }
  6802. const groups = this.groups;
  6803. if ( groups.length > 0 ) {
  6804. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6805. }
  6806. const boundingSphere = this.boundingSphere;
  6807. if ( boundingSphere !== null ) {
  6808. data.data.boundingSphere = {
  6809. center: boundingSphere.center.toArray(),
  6810. radius: boundingSphere.radius
  6811. };
  6812. }
  6813. return data;
  6814. }
  6815. clone() {
  6816. return new this.constructor().copy( this );
  6817. }
  6818. copy( source ) {
  6819. // reset
  6820. this.index = null;
  6821. this.attributes = {};
  6822. this.morphAttributes = {};
  6823. this.groups = [];
  6824. this.boundingBox = null;
  6825. this.boundingSphere = null;
  6826. // used for storing cloned, shared data
  6827. const data = {};
  6828. // name
  6829. this.name = source.name;
  6830. // index
  6831. const index = source.index;
  6832. if ( index !== null ) {
  6833. this.setIndex( index.clone( data ) );
  6834. }
  6835. // attributes
  6836. const attributes = source.attributes;
  6837. for ( const name in attributes ) {
  6838. const attribute = attributes[ name ];
  6839. this.setAttribute( name, attribute.clone( data ) );
  6840. }
  6841. // morph attributes
  6842. const morphAttributes = source.morphAttributes;
  6843. for ( const name in morphAttributes ) {
  6844. const array = [];
  6845. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6846. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6847. array.push( morphAttribute[ i ].clone( data ) );
  6848. }
  6849. this.morphAttributes[ name ] = array;
  6850. }
  6851. this.morphTargetsRelative = source.morphTargetsRelative;
  6852. // groups
  6853. const groups = source.groups;
  6854. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6855. const group = groups[ i ];
  6856. this.addGroup( group.start, group.count, group.materialIndex );
  6857. }
  6858. // bounding box
  6859. const boundingBox = source.boundingBox;
  6860. if ( boundingBox !== null ) {
  6861. this.boundingBox = boundingBox.clone();
  6862. }
  6863. // bounding sphere
  6864. const boundingSphere = source.boundingSphere;
  6865. if ( boundingSphere !== null ) {
  6866. this.boundingSphere = boundingSphere.clone();
  6867. }
  6868. // draw range
  6869. this.drawRange.start = source.drawRange.start;
  6870. this.drawRange.count = source.drawRange.count;
  6871. // user data
  6872. this.userData = source.userData;
  6873. return this;
  6874. }
  6875. dispose() {
  6876. this.dispatchEvent( { type: 'dispose' } );
  6877. }
  6878. }
  6879. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6880. const _ray$3 = /*@__PURE__*/ new Ray();
  6881. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6882. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6883. const _vA$1 = /*@__PURE__*/ new Vector3();
  6884. const _vB$1 = /*@__PURE__*/ new Vector3();
  6885. const _vC$1 = /*@__PURE__*/ new Vector3();
  6886. const _tempA = /*@__PURE__*/ new Vector3();
  6887. const _morphA = /*@__PURE__*/ new Vector3();
  6888. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6889. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6890. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6891. const _normalA = /*@__PURE__*/ new Vector3();
  6892. const _normalB = /*@__PURE__*/ new Vector3();
  6893. const _normalC = /*@__PURE__*/ new Vector3();
  6894. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6895. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6896. class Mesh extends Object3D {
  6897. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6898. super();
  6899. this.isMesh = true;
  6900. this.type = 'Mesh';
  6901. this.geometry = geometry;
  6902. this.material = material;
  6903. this.updateMorphTargets();
  6904. }
  6905. copy( source, recursive ) {
  6906. super.copy( source, recursive );
  6907. if ( source.morphTargetInfluences !== undefined ) {
  6908. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6909. }
  6910. if ( source.morphTargetDictionary !== undefined ) {
  6911. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6912. }
  6913. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6914. this.geometry = source.geometry;
  6915. return this;
  6916. }
  6917. updateMorphTargets() {
  6918. const geometry = this.geometry;
  6919. const morphAttributes = geometry.morphAttributes;
  6920. const keys = Object.keys( morphAttributes );
  6921. if ( keys.length > 0 ) {
  6922. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6923. if ( morphAttribute !== undefined ) {
  6924. this.morphTargetInfluences = [];
  6925. this.morphTargetDictionary = {};
  6926. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6927. const name = morphAttribute[ m ].name || String( m );
  6928. this.morphTargetInfluences.push( 0 );
  6929. this.morphTargetDictionary[ name ] = m;
  6930. }
  6931. }
  6932. }
  6933. }
  6934. getVertexPosition( index, target ) {
  6935. const geometry = this.geometry;
  6936. const position = geometry.attributes.position;
  6937. const morphPosition = geometry.morphAttributes.position;
  6938. const morphTargetsRelative = geometry.morphTargetsRelative;
  6939. target.fromBufferAttribute( position, index );
  6940. const morphInfluences = this.morphTargetInfluences;
  6941. if ( morphPosition && morphInfluences ) {
  6942. _morphA.set( 0, 0, 0 );
  6943. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6944. const influence = morphInfluences[ i ];
  6945. const morphAttribute = morphPosition[ i ];
  6946. if ( influence === 0 ) continue;
  6947. _tempA.fromBufferAttribute( morphAttribute, index );
  6948. if ( morphTargetsRelative ) {
  6949. _morphA.addScaledVector( _tempA, influence );
  6950. } else {
  6951. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6952. }
  6953. }
  6954. target.add( _morphA );
  6955. }
  6956. return target;
  6957. }
  6958. raycast( raycaster, intersects ) {
  6959. const geometry = this.geometry;
  6960. const material = this.material;
  6961. const matrixWorld = this.matrixWorld;
  6962. if ( material === undefined ) return;
  6963. // test with bounding sphere in world space
  6964. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6965. _sphere$6.copy( geometry.boundingSphere );
  6966. _sphere$6.applyMatrix4( matrixWorld );
  6967. // check distance from ray origin to bounding sphere
  6968. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6969. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6970. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6971. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6972. }
  6973. // convert ray to local space of mesh
  6974. _inverseMatrix$3.copy( matrixWorld ).invert();
  6975. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6976. // test with bounding box in local space
  6977. if ( geometry.boundingBox !== null ) {
  6978. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6979. }
  6980. // test for intersections with geometry
  6981. this._computeIntersections( raycaster, intersects, _ray$3 );
  6982. }
  6983. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6984. let intersection;
  6985. const geometry = this.geometry;
  6986. const material = this.material;
  6987. const index = geometry.index;
  6988. const position = geometry.attributes.position;
  6989. const uv = geometry.attributes.uv;
  6990. const uv1 = geometry.attributes.uv1;
  6991. const normal = geometry.attributes.normal;
  6992. const groups = geometry.groups;
  6993. const drawRange = geometry.drawRange;
  6994. if ( index !== null ) {
  6995. // indexed buffer geometry
  6996. if ( Array.isArray( material ) ) {
  6997. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6998. const group = groups[ i ];
  6999. const groupMaterial = material[ group.materialIndex ];
  7000. const start = Math.max( group.start, drawRange.start );
  7001. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7002. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7003. const a = index.getX( j );
  7004. const b = index.getX( j + 1 );
  7005. const c = index.getX( j + 2 );
  7006. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7007. if ( intersection ) {
  7008. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7009. intersection.face.materialIndex = group.materialIndex;
  7010. intersects.push( intersection );
  7011. }
  7012. }
  7013. }
  7014. } else {
  7015. const start = Math.max( 0, drawRange.start );
  7016. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7017. for ( let i = start, il = end; i < il; i += 3 ) {
  7018. const a = index.getX( i );
  7019. const b = index.getX( i + 1 );
  7020. const c = index.getX( i + 2 );
  7021. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7022. if ( intersection ) {
  7023. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7024. intersects.push( intersection );
  7025. }
  7026. }
  7027. }
  7028. } else if ( position !== undefined ) {
  7029. // non-indexed buffer geometry
  7030. if ( Array.isArray( material ) ) {
  7031. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7032. const group = groups[ i ];
  7033. const groupMaterial = material[ group.materialIndex ];
  7034. const start = Math.max( group.start, drawRange.start );
  7035. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7036. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7037. const a = j;
  7038. const b = j + 1;
  7039. const c = j + 2;
  7040. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7041. if ( intersection ) {
  7042. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7043. intersection.face.materialIndex = group.materialIndex;
  7044. intersects.push( intersection );
  7045. }
  7046. }
  7047. }
  7048. } else {
  7049. const start = Math.max( 0, drawRange.start );
  7050. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7051. for ( let i = start, il = end; i < il; i += 3 ) {
  7052. const a = i;
  7053. const b = i + 1;
  7054. const c = i + 2;
  7055. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7056. if ( intersection ) {
  7057. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7058. intersects.push( intersection );
  7059. }
  7060. }
  7061. }
  7062. }
  7063. }
  7064. }
  7065. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7066. let intersect;
  7067. if ( material.side === BackSide ) {
  7068. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7069. } else {
  7070. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7071. }
  7072. if ( intersect === null ) return null;
  7073. _intersectionPointWorld.copy( point );
  7074. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7075. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7076. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7077. return {
  7078. distance: distance,
  7079. point: _intersectionPointWorld.clone(),
  7080. object: object
  7081. };
  7082. }
  7083. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7084. object.getVertexPosition( a, _vA$1 );
  7085. object.getVertexPosition( b, _vB$1 );
  7086. object.getVertexPosition( c, _vC$1 );
  7087. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7088. if ( intersection ) {
  7089. if ( uv ) {
  7090. _uvA$1.fromBufferAttribute( uv, a );
  7091. _uvB$1.fromBufferAttribute( uv, b );
  7092. _uvC$1.fromBufferAttribute( uv, c );
  7093. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7094. }
  7095. if ( uv1 ) {
  7096. _uvA$1.fromBufferAttribute( uv1, a );
  7097. _uvB$1.fromBufferAttribute( uv1, b );
  7098. _uvC$1.fromBufferAttribute( uv1, c );
  7099. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7100. }
  7101. if ( normal ) {
  7102. _normalA.fromBufferAttribute( normal, a );
  7103. _normalB.fromBufferAttribute( normal, b );
  7104. _normalC.fromBufferAttribute( normal, c );
  7105. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7106. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7107. intersection.normal.multiplyScalar( - 1 );
  7108. }
  7109. }
  7110. const face = {
  7111. a: a,
  7112. b: b,
  7113. c: c,
  7114. normal: new Vector3(),
  7115. materialIndex: 0
  7116. };
  7117. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7118. intersection.face = face;
  7119. }
  7120. return intersection;
  7121. }
  7122. class BoxGeometry extends BufferGeometry {
  7123. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7124. super();
  7125. this.type = 'BoxGeometry';
  7126. this.parameters = {
  7127. width: width,
  7128. height: height,
  7129. depth: depth,
  7130. widthSegments: widthSegments,
  7131. heightSegments: heightSegments,
  7132. depthSegments: depthSegments
  7133. };
  7134. const scope = this;
  7135. // segments
  7136. widthSegments = Math.floor( widthSegments );
  7137. heightSegments = Math.floor( heightSegments );
  7138. depthSegments = Math.floor( depthSegments );
  7139. // buffers
  7140. const indices = [];
  7141. const vertices = [];
  7142. const normals = [];
  7143. const uvs = [];
  7144. // helper variables
  7145. let numberOfVertices = 0;
  7146. let groupStart = 0;
  7147. // build each side of the box geometry
  7148. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7149. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7150. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7151. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7152. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7153. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7154. // build geometry
  7155. this.setIndex( indices );
  7156. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7157. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7158. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7159. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7160. const segmentWidth = width / gridX;
  7161. const segmentHeight = height / gridY;
  7162. const widthHalf = width / 2;
  7163. const heightHalf = height / 2;
  7164. const depthHalf = depth / 2;
  7165. const gridX1 = gridX + 1;
  7166. const gridY1 = gridY + 1;
  7167. let vertexCounter = 0;
  7168. let groupCount = 0;
  7169. const vector = new Vector3();
  7170. // generate vertices, normals and uvs
  7171. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7172. const y = iy * segmentHeight - heightHalf;
  7173. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7174. const x = ix * segmentWidth - widthHalf;
  7175. // set values to correct vector component
  7176. vector[ u ] = x * udir;
  7177. vector[ v ] = y * vdir;
  7178. vector[ w ] = depthHalf;
  7179. // now apply vector to vertex buffer
  7180. vertices.push( vector.x, vector.y, vector.z );
  7181. // set values to correct vector component
  7182. vector[ u ] = 0;
  7183. vector[ v ] = 0;
  7184. vector[ w ] = depth > 0 ? 1 : - 1;
  7185. // now apply vector to normal buffer
  7186. normals.push( vector.x, vector.y, vector.z );
  7187. // uvs
  7188. uvs.push( ix / gridX );
  7189. uvs.push( 1 - ( iy / gridY ) );
  7190. // counters
  7191. vertexCounter += 1;
  7192. }
  7193. }
  7194. // indices
  7195. // 1. you need three indices to draw a single face
  7196. // 2. a single segment consists of two faces
  7197. // 3. so we need to generate six (2*3) indices per segment
  7198. for ( let iy = 0; iy < gridY; iy ++ ) {
  7199. for ( let ix = 0; ix < gridX; ix ++ ) {
  7200. const a = numberOfVertices + ix + gridX1 * iy;
  7201. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7202. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7203. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7204. // faces
  7205. indices.push( a, b, d );
  7206. indices.push( b, c, d );
  7207. // increase counter
  7208. groupCount += 6;
  7209. }
  7210. }
  7211. // add a group to the geometry. this will ensure multi material support
  7212. scope.addGroup( groupStart, groupCount, materialIndex );
  7213. // calculate new start value for groups
  7214. groupStart += groupCount;
  7215. // update total number of vertices
  7216. numberOfVertices += vertexCounter;
  7217. }
  7218. }
  7219. copy( source ) {
  7220. super.copy( source );
  7221. this.parameters = Object.assign( {}, source.parameters );
  7222. return this;
  7223. }
  7224. static fromJSON( data ) {
  7225. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7226. }
  7227. }
  7228. /**
  7229. * Uniform Utilities
  7230. */
  7231. function cloneUniforms( src ) {
  7232. const dst = {};
  7233. for ( const u in src ) {
  7234. dst[ u ] = {};
  7235. for ( const p in src[ u ] ) {
  7236. const property = src[ u ][ p ];
  7237. if ( property && ( property.isColor ||
  7238. property.isMatrix3 || property.isMatrix4 ||
  7239. property.isVector2 || property.isVector3 || property.isVector4 ||
  7240. property.isTexture || property.isQuaternion ) ) {
  7241. if ( property.isRenderTargetTexture ) {
  7242. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7243. dst[ u ][ p ] = null;
  7244. } else {
  7245. dst[ u ][ p ] = property.clone();
  7246. }
  7247. } else if ( Array.isArray( property ) ) {
  7248. dst[ u ][ p ] = property.slice();
  7249. } else {
  7250. dst[ u ][ p ] = property;
  7251. }
  7252. }
  7253. }
  7254. return dst;
  7255. }
  7256. function mergeUniforms( uniforms ) {
  7257. const merged = {};
  7258. for ( let u = 0; u < uniforms.length; u ++ ) {
  7259. const tmp = cloneUniforms( uniforms[ u ] );
  7260. for ( const p in tmp ) {
  7261. merged[ p ] = tmp[ p ];
  7262. }
  7263. }
  7264. return merged;
  7265. }
  7266. function cloneUniformsGroups( src ) {
  7267. const dst = [];
  7268. for ( let u = 0; u < src.length; u ++ ) {
  7269. dst.push( src[ u ].clone() );
  7270. }
  7271. return dst;
  7272. }
  7273. function getUnlitUniformColorSpace( renderer ) {
  7274. const currentRenderTarget = renderer.getRenderTarget();
  7275. if ( currentRenderTarget === null ) {
  7276. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7277. return renderer.outputColorSpace;
  7278. }
  7279. // https://github.com/mrdoob/three.js/issues/27868
  7280. if ( currentRenderTarget.isXRRenderTarget === true ) {
  7281. return currentRenderTarget.texture.colorSpace;
  7282. }
  7283. return ColorManagement.workingColorSpace;
  7284. }
  7285. // Legacy
  7286. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7287. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7288. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7289. class ShaderMaterial extends Material {
  7290. constructor( parameters ) {
  7291. super();
  7292. this.isShaderMaterial = true;
  7293. this.type = 'ShaderMaterial';
  7294. this.defines = {};
  7295. this.uniforms = {};
  7296. this.uniformsGroups = [];
  7297. this.vertexShader = default_vertex;
  7298. this.fragmentShader = default_fragment;
  7299. this.linewidth = 1;
  7300. this.wireframe = false;
  7301. this.wireframeLinewidth = 1;
  7302. this.fog = false; // set to use scene fog
  7303. this.lights = false; // set to use scene lights
  7304. this.clipping = false; // set to use user-defined clipping planes
  7305. this.forceSinglePass = true;
  7306. this.extensions = {
  7307. clipCullDistance: false, // set to use vertex shader clipping
  7308. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7309. };
  7310. // When rendered geometry doesn't include these attributes but the material does,
  7311. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7312. this.defaultAttributeValues = {
  7313. 'color': [ 1, 1, 1 ],
  7314. 'uv': [ 0, 0 ],
  7315. 'uv1': [ 0, 0 ]
  7316. };
  7317. this.index0AttributeName = undefined;
  7318. this.uniformsNeedUpdate = false;
  7319. this.glslVersion = null;
  7320. if ( parameters !== undefined ) {
  7321. this.setValues( parameters );
  7322. }
  7323. }
  7324. copy( source ) {
  7325. super.copy( source );
  7326. this.fragmentShader = source.fragmentShader;
  7327. this.vertexShader = source.vertexShader;
  7328. this.uniforms = cloneUniforms( source.uniforms );
  7329. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7330. this.defines = Object.assign( {}, source.defines );
  7331. this.wireframe = source.wireframe;
  7332. this.wireframeLinewidth = source.wireframeLinewidth;
  7333. this.fog = source.fog;
  7334. this.lights = source.lights;
  7335. this.clipping = source.clipping;
  7336. this.extensions = Object.assign( {}, source.extensions );
  7337. this.glslVersion = source.glslVersion;
  7338. return this;
  7339. }
  7340. toJSON( meta ) {
  7341. const data = super.toJSON( meta );
  7342. data.glslVersion = this.glslVersion;
  7343. data.uniforms = {};
  7344. for ( const name in this.uniforms ) {
  7345. const uniform = this.uniforms[ name ];
  7346. const value = uniform.value;
  7347. if ( value && value.isTexture ) {
  7348. data.uniforms[ name ] = {
  7349. type: 't',
  7350. value: value.toJSON( meta ).uuid
  7351. };
  7352. } else if ( value && value.isColor ) {
  7353. data.uniforms[ name ] = {
  7354. type: 'c',
  7355. value: value.getHex()
  7356. };
  7357. } else if ( value && value.isVector2 ) {
  7358. data.uniforms[ name ] = {
  7359. type: 'v2',
  7360. value: value.toArray()
  7361. };
  7362. } else if ( value && value.isVector3 ) {
  7363. data.uniforms[ name ] = {
  7364. type: 'v3',
  7365. value: value.toArray()
  7366. };
  7367. } else if ( value && value.isVector4 ) {
  7368. data.uniforms[ name ] = {
  7369. type: 'v4',
  7370. value: value.toArray()
  7371. };
  7372. } else if ( value && value.isMatrix3 ) {
  7373. data.uniforms[ name ] = {
  7374. type: 'm3',
  7375. value: value.toArray()
  7376. };
  7377. } else if ( value && value.isMatrix4 ) {
  7378. data.uniforms[ name ] = {
  7379. type: 'm4',
  7380. value: value.toArray()
  7381. };
  7382. } else {
  7383. data.uniforms[ name ] = {
  7384. value: value
  7385. };
  7386. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7387. }
  7388. }
  7389. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7390. data.vertexShader = this.vertexShader;
  7391. data.fragmentShader = this.fragmentShader;
  7392. data.lights = this.lights;
  7393. data.clipping = this.clipping;
  7394. const extensions = {};
  7395. for ( const key in this.extensions ) {
  7396. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7397. }
  7398. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7399. return data;
  7400. }
  7401. }
  7402. class Camera extends Object3D {
  7403. constructor() {
  7404. super();
  7405. this.isCamera = true;
  7406. this.type = 'Camera';
  7407. this.matrixWorldInverse = new Matrix4();
  7408. this.projectionMatrix = new Matrix4();
  7409. this.projectionMatrixInverse = new Matrix4();
  7410. this.coordinateSystem = WebGLCoordinateSystem;
  7411. }
  7412. copy( source, recursive ) {
  7413. super.copy( source, recursive );
  7414. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7415. this.projectionMatrix.copy( source.projectionMatrix );
  7416. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7417. this.coordinateSystem = source.coordinateSystem;
  7418. return this;
  7419. }
  7420. getWorldDirection( target ) {
  7421. return super.getWorldDirection( target ).negate();
  7422. }
  7423. updateMatrixWorld( force ) {
  7424. super.updateMatrixWorld( force );
  7425. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7426. }
  7427. updateWorldMatrix( updateParents, updateChildren ) {
  7428. super.updateWorldMatrix( updateParents, updateChildren );
  7429. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7430. }
  7431. clone() {
  7432. return new this.constructor().copy( this );
  7433. }
  7434. }
  7435. const _v3$1 = /*@__PURE__*/ new Vector3();
  7436. const _minTarget = /*@__PURE__*/ new Vector2();
  7437. const _maxTarget = /*@__PURE__*/ new Vector2();
  7438. class PerspectiveCamera extends Camera {
  7439. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7440. super();
  7441. this.isPerspectiveCamera = true;
  7442. this.type = 'PerspectiveCamera';
  7443. this.fov = fov;
  7444. this.zoom = 1;
  7445. this.near = near;
  7446. this.far = far;
  7447. this.focus = 10;
  7448. this.aspect = aspect;
  7449. this.view = null;
  7450. this.filmGauge = 35; // width of the film (default in millimeters)
  7451. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7452. this.updateProjectionMatrix();
  7453. }
  7454. copy( source, recursive ) {
  7455. super.copy( source, recursive );
  7456. this.fov = source.fov;
  7457. this.zoom = source.zoom;
  7458. this.near = source.near;
  7459. this.far = source.far;
  7460. this.focus = source.focus;
  7461. this.aspect = source.aspect;
  7462. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7463. this.filmGauge = source.filmGauge;
  7464. this.filmOffset = source.filmOffset;
  7465. return this;
  7466. }
  7467. /**
  7468. * Sets the FOV by focal length in respect to the current .filmGauge.
  7469. *
  7470. * The default film gauge is 35, so that the focal length can be specified for
  7471. * a 35mm (full frame) camera.
  7472. *
  7473. * Values for focal length and film gauge must have the same unit.
  7474. */
  7475. setFocalLength( focalLength ) {
  7476. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7477. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7478. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7479. this.updateProjectionMatrix();
  7480. }
  7481. /**
  7482. * Calculates the focal length from the current .fov and .filmGauge.
  7483. */
  7484. getFocalLength() {
  7485. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7486. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7487. }
  7488. getEffectiveFOV() {
  7489. return RAD2DEG * 2 * Math.atan(
  7490. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7491. }
  7492. getFilmWidth() {
  7493. // film not completely covered in portrait format (aspect < 1)
  7494. return this.filmGauge * Math.min( this.aspect, 1 );
  7495. }
  7496. getFilmHeight() {
  7497. // film not completely covered in landscape format (aspect > 1)
  7498. return this.filmGauge / Math.max( this.aspect, 1 );
  7499. }
  7500. /**
  7501. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7502. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7503. */
  7504. getViewBounds( distance, minTarget, maxTarget ) {
  7505. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7506. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7507. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7508. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7509. }
  7510. /**
  7511. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7512. * Copies the result into the target Vector2, where x is width and y is height.
  7513. */
  7514. getViewSize( distance, target ) {
  7515. this.getViewBounds( distance, _minTarget, _maxTarget );
  7516. return target.subVectors( _maxTarget, _minTarget );
  7517. }
  7518. /**
  7519. * Sets an offset in a larger frustum. This is useful for multi-window or
  7520. * multi-monitor/multi-machine setups.
  7521. *
  7522. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7523. * the monitors are in grid like this
  7524. *
  7525. * +---+---+---+
  7526. * | A | B | C |
  7527. * +---+---+---+
  7528. * | D | E | F |
  7529. * +---+---+---+
  7530. *
  7531. * then for each monitor you would call it like this
  7532. *
  7533. * const w = 1920;
  7534. * const h = 1080;
  7535. * const fullWidth = w * 3;
  7536. * const fullHeight = h * 2;
  7537. *
  7538. * --A--
  7539. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7540. * --B--
  7541. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7542. * --C--
  7543. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7544. * --D--
  7545. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7546. * --E--
  7547. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7548. * --F--
  7549. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7550. *
  7551. * Note there is no reason monitors have to be the same size or in a grid.
  7552. */
  7553. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7554. this.aspect = fullWidth / fullHeight;
  7555. if ( this.view === null ) {
  7556. this.view = {
  7557. enabled: true,
  7558. fullWidth: 1,
  7559. fullHeight: 1,
  7560. offsetX: 0,
  7561. offsetY: 0,
  7562. width: 1,
  7563. height: 1
  7564. };
  7565. }
  7566. this.view.enabled = true;
  7567. this.view.fullWidth = fullWidth;
  7568. this.view.fullHeight = fullHeight;
  7569. this.view.offsetX = x;
  7570. this.view.offsetY = y;
  7571. this.view.width = width;
  7572. this.view.height = height;
  7573. this.updateProjectionMatrix();
  7574. }
  7575. clearViewOffset() {
  7576. if ( this.view !== null ) {
  7577. this.view.enabled = false;
  7578. }
  7579. this.updateProjectionMatrix();
  7580. }
  7581. updateProjectionMatrix() {
  7582. const near = this.near;
  7583. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7584. let height = 2 * top;
  7585. let width = this.aspect * height;
  7586. let left = - 0.5 * width;
  7587. const view = this.view;
  7588. if ( this.view !== null && this.view.enabled ) {
  7589. const fullWidth = view.fullWidth,
  7590. fullHeight = view.fullHeight;
  7591. left += view.offsetX * width / fullWidth;
  7592. top -= view.offsetY * height / fullHeight;
  7593. width *= view.width / fullWidth;
  7594. height *= view.height / fullHeight;
  7595. }
  7596. const skew = this.filmOffset;
  7597. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7598. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7599. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7600. }
  7601. toJSON( meta ) {
  7602. const data = super.toJSON( meta );
  7603. data.object.fov = this.fov;
  7604. data.object.zoom = this.zoom;
  7605. data.object.near = this.near;
  7606. data.object.far = this.far;
  7607. data.object.focus = this.focus;
  7608. data.object.aspect = this.aspect;
  7609. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7610. data.object.filmGauge = this.filmGauge;
  7611. data.object.filmOffset = this.filmOffset;
  7612. return data;
  7613. }
  7614. }
  7615. const fov = - 90; // negative fov is not an error
  7616. const aspect = 1;
  7617. class CubeCamera extends Object3D {
  7618. constructor( near, far, renderTarget ) {
  7619. super();
  7620. this.type = 'CubeCamera';
  7621. this.renderTarget = renderTarget;
  7622. this.coordinateSystem = null;
  7623. this.activeMipmapLevel = 0;
  7624. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7625. cameraPX.layers = this.layers;
  7626. this.add( cameraPX );
  7627. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7628. cameraNX.layers = this.layers;
  7629. this.add( cameraNX );
  7630. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7631. cameraPY.layers = this.layers;
  7632. this.add( cameraPY );
  7633. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7634. cameraNY.layers = this.layers;
  7635. this.add( cameraNY );
  7636. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7637. cameraPZ.layers = this.layers;
  7638. this.add( cameraPZ );
  7639. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7640. cameraNZ.layers = this.layers;
  7641. this.add( cameraNZ );
  7642. }
  7643. updateCoordinateSystem() {
  7644. const coordinateSystem = this.coordinateSystem;
  7645. const cameras = this.children.concat();
  7646. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7647. for ( const camera of cameras ) this.remove( camera );
  7648. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7649. cameraPX.up.set( 0, 1, 0 );
  7650. cameraPX.lookAt( 1, 0, 0 );
  7651. cameraNX.up.set( 0, 1, 0 );
  7652. cameraNX.lookAt( - 1, 0, 0 );
  7653. cameraPY.up.set( 0, 0, - 1 );
  7654. cameraPY.lookAt( 0, 1, 0 );
  7655. cameraNY.up.set( 0, 0, 1 );
  7656. cameraNY.lookAt( 0, - 1, 0 );
  7657. cameraPZ.up.set( 0, 1, 0 );
  7658. cameraPZ.lookAt( 0, 0, 1 );
  7659. cameraNZ.up.set( 0, 1, 0 );
  7660. cameraNZ.lookAt( 0, 0, - 1 );
  7661. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7662. cameraPX.up.set( 0, - 1, 0 );
  7663. cameraPX.lookAt( - 1, 0, 0 );
  7664. cameraNX.up.set( 0, - 1, 0 );
  7665. cameraNX.lookAt( 1, 0, 0 );
  7666. cameraPY.up.set( 0, 0, 1 );
  7667. cameraPY.lookAt( 0, 1, 0 );
  7668. cameraNY.up.set( 0, 0, - 1 );
  7669. cameraNY.lookAt( 0, - 1, 0 );
  7670. cameraPZ.up.set( 0, - 1, 0 );
  7671. cameraPZ.lookAt( 0, 0, 1 );
  7672. cameraNZ.up.set( 0, - 1, 0 );
  7673. cameraNZ.lookAt( 0, 0, - 1 );
  7674. } else {
  7675. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7676. }
  7677. for ( const camera of cameras ) {
  7678. this.add( camera );
  7679. camera.updateMatrixWorld();
  7680. }
  7681. }
  7682. update( renderer, scene ) {
  7683. if ( this.parent === null ) this.updateMatrixWorld();
  7684. const { renderTarget, activeMipmapLevel } = this;
  7685. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7686. this.coordinateSystem = renderer.coordinateSystem;
  7687. this.updateCoordinateSystem();
  7688. }
  7689. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7690. const currentRenderTarget = renderer.getRenderTarget();
  7691. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7692. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7693. const currentXrEnabled = renderer.xr.enabled;
  7694. renderer.xr.enabled = false;
  7695. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7696. renderTarget.texture.generateMipmaps = false;
  7697. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7698. renderer.render( scene, cameraPX );
  7699. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7700. renderer.render( scene, cameraNX );
  7701. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7702. renderer.render( scene, cameraPY );
  7703. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7704. renderer.render( scene, cameraNY );
  7705. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7706. renderer.render( scene, cameraPZ );
  7707. // mipmaps are generated during the last call of render()
  7708. // at this point, all sides of the cube render target are defined
  7709. renderTarget.texture.generateMipmaps = generateMipmaps;
  7710. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7711. renderer.render( scene, cameraNZ );
  7712. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7713. renderer.xr.enabled = currentXrEnabled;
  7714. renderTarget.texture.needsPMREMUpdate = true;
  7715. }
  7716. }
  7717. class CubeTexture extends Texture {
  7718. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7719. images = images !== undefined ? images : [];
  7720. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7721. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7722. this.isCubeTexture = true;
  7723. this.flipY = false;
  7724. }
  7725. get images() {
  7726. return this.image;
  7727. }
  7728. set images( value ) {
  7729. this.image = value;
  7730. }
  7731. }
  7732. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7733. constructor( size = 1, options = {} ) {
  7734. super( size, size, options );
  7735. this.isWebGLCubeRenderTarget = true;
  7736. const image = { width: size, height: size, depth: 1 };
  7737. const images = [ image, image, image, image, image, image ];
  7738. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7739. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7740. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7741. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7742. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7743. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7744. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7745. this.texture.isRenderTargetTexture = true;
  7746. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7747. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7748. }
  7749. fromEquirectangularTexture( renderer, texture ) {
  7750. this.texture.type = texture.type;
  7751. this.texture.colorSpace = texture.colorSpace;
  7752. this.texture.generateMipmaps = texture.generateMipmaps;
  7753. this.texture.minFilter = texture.minFilter;
  7754. this.texture.magFilter = texture.magFilter;
  7755. const shader = {
  7756. uniforms: {
  7757. tEquirect: { value: null },
  7758. },
  7759. vertexShader: /* glsl */`
  7760. varying vec3 vWorldDirection;
  7761. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7762. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7763. }
  7764. void main() {
  7765. vWorldDirection = transformDirection( position, modelMatrix );
  7766. #include <begin_vertex>
  7767. #include <project_vertex>
  7768. }
  7769. `,
  7770. fragmentShader: /* glsl */`
  7771. uniform sampler2D tEquirect;
  7772. varying vec3 vWorldDirection;
  7773. #include <common>
  7774. void main() {
  7775. vec3 direction = normalize( vWorldDirection );
  7776. vec2 sampleUV = equirectUv( direction );
  7777. gl_FragColor = texture2D( tEquirect, sampleUV );
  7778. }
  7779. `
  7780. };
  7781. const geometry = new BoxGeometry( 5, 5, 5 );
  7782. const material = new ShaderMaterial( {
  7783. name: 'CubemapFromEquirect',
  7784. uniforms: cloneUniforms( shader.uniforms ),
  7785. vertexShader: shader.vertexShader,
  7786. fragmentShader: shader.fragmentShader,
  7787. side: BackSide,
  7788. blending: NoBlending
  7789. } );
  7790. material.uniforms.tEquirect.value = texture;
  7791. const mesh = new Mesh( geometry, material );
  7792. const currentMinFilter = texture.minFilter;
  7793. // Avoid blurred poles
  7794. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7795. const camera = new CubeCamera( 1, 10, this );
  7796. camera.update( renderer, mesh );
  7797. texture.minFilter = currentMinFilter;
  7798. mesh.geometry.dispose();
  7799. mesh.material.dispose();
  7800. return this;
  7801. }
  7802. clear( renderer, color, depth, stencil ) {
  7803. const currentRenderTarget = renderer.getRenderTarget();
  7804. for ( let i = 0; i < 6; i ++ ) {
  7805. renderer.setRenderTarget( this, i );
  7806. renderer.clear( color, depth, stencil );
  7807. }
  7808. renderer.setRenderTarget( currentRenderTarget );
  7809. }
  7810. }
  7811. const _vector1 = /*@__PURE__*/ new Vector3();
  7812. const _vector2 = /*@__PURE__*/ new Vector3();
  7813. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7814. class Plane {
  7815. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7816. this.isPlane = true;
  7817. // normal is assumed to be normalized
  7818. this.normal = normal;
  7819. this.constant = constant;
  7820. }
  7821. set( normal, constant ) {
  7822. this.normal.copy( normal );
  7823. this.constant = constant;
  7824. return this;
  7825. }
  7826. setComponents( x, y, z, w ) {
  7827. this.normal.set( x, y, z );
  7828. this.constant = w;
  7829. return this;
  7830. }
  7831. setFromNormalAndCoplanarPoint( normal, point ) {
  7832. this.normal.copy( normal );
  7833. this.constant = - point.dot( this.normal );
  7834. return this;
  7835. }
  7836. setFromCoplanarPoints( a, b, c ) {
  7837. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7838. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7839. this.setFromNormalAndCoplanarPoint( normal, a );
  7840. return this;
  7841. }
  7842. copy( plane ) {
  7843. this.normal.copy( plane.normal );
  7844. this.constant = plane.constant;
  7845. return this;
  7846. }
  7847. normalize() {
  7848. // Note: will lead to a divide by zero if the plane is invalid.
  7849. const inverseNormalLength = 1.0 / this.normal.length();
  7850. this.normal.multiplyScalar( inverseNormalLength );
  7851. this.constant *= inverseNormalLength;
  7852. return this;
  7853. }
  7854. negate() {
  7855. this.constant *= - 1;
  7856. this.normal.negate();
  7857. return this;
  7858. }
  7859. distanceToPoint( point ) {
  7860. return this.normal.dot( point ) + this.constant;
  7861. }
  7862. distanceToSphere( sphere ) {
  7863. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7864. }
  7865. projectPoint( point, target ) {
  7866. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7867. }
  7868. intersectLine( line, target ) {
  7869. const direction = line.delta( _vector1 );
  7870. const denominator = this.normal.dot( direction );
  7871. if ( denominator === 0 ) {
  7872. // line is coplanar, return origin
  7873. if ( this.distanceToPoint( line.start ) === 0 ) {
  7874. return target.copy( line.start );
  7875. }
  7876. // Unsure if this is the correct method to handle this case.
  7877. return null;
  7878. }
  7879. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7880. if ( t < 0 || t > 1 ) {
  7881. return null;
  7882. }
  7883. return target.copy( line.start ).addScaledVector( direction, t );
  7884. }
  7885. intersectsLine( line ) {
  7886. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7887. const startSign = this.distanceToPoint( line.start );
  7888. const endSign = this.distanceToPoint( line.end );
  7889. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7890. }
  7891. intersectsBox( box ) {
  7892. return box.intersectsPlane( this );
  7893. }
  7894. intersectsSphere( sphere ) {
  7895. return sphere.intersectsPlane( this );
  7896. }
  7897. coplanarPoint( target ) {
  7898. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7899. }
  7900. applyMatrix4( matrix, optionalNormalMatrix ) {
  7901. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7902. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7903. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7904. this.constant = - referencePoint.dot( normal );
  7905. return this;
  7906. }
  7907. translate( offset ) {
  7908. this.constant -= offset.dot( this.normal );
  7909. return this;
  7910. }
  7911. equals( plane ) {
  7912. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7913. }
  7914. clone() {
  7915. return new this.constructor().copy( this );
  7916. }
  7917. }
  7918. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7919. const _vector$7 = /*@__PURE__*/ new Vector3();
  7920. class Frustum {
  7921. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7922. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7923. }
  7924. set( p0, p1, p2, p3, p4, p5 ) {
  7925. const planes = this.planes;
  7926. planes[ 0 ].copy( p0 );
  7927. planes[ 1 ].copy( p1 );
  7928. planes[ 2 ].copy( p2 );
  7929. planes[ 3 ].copy( p3 );
  7930. planes[ 4 ].copy( p4 );
  7931. planes[ 5 ].copy( p5 );
  7932. return this;
  7933. }
  7934. copy( frustum ) {
  7935. const planes = this.planes;
  7936. for ( let i = 0; i < 6; i ++ ) {
  7937. planes[ i ].copy( frustum.planes[ i ] );
  7938. }
  7939. return this;
  7940. }
  7941. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7942. const planes = this.planes;
  7943. const me = m.elements;
  7944. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7945. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7946. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7947. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7948. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7949. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7950. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7951. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7952. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7953. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7954. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7955. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7956. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7957. } else {
  7958. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7959. }
  7960. return this;
  7961. }
  7962. intersectsObject( object ) {
  7963. if ( object.boundingSphere !== undefined ) {
  7964. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7965. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7966. } else {
  7967. const geometry = object.geometry;
  7968. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7969. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7970. }
  7971. return this.intersectsSphere( _sphere$5 );
  7972. }
  7973. intersectsSprite( sprite ) {
  7974. _sphere$5.center.set( 0, 0, 0 );
  7975. _sphere$5.radius = 0.7071067811865476;
  7976. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7977. return this.intersectsSphere( _sphere$5 );
  7978. }
  7979. intersectsSphere( sphere ) {
  7980. const planes = this.planes;
  7981. const center = sphere.center;
  7982. const negRadius = - sphere.radius;
  7983. for ( let i = 0; i < 6; i ++ ) {
  7984. const distance = planes[ i ].distanceToPoint( center );
  7985. if ( distance < negRadius ) {
  7986. return false;
  7987. }
  7988. }
  7989. return true;
  7990. }
  7991. intersectsBox( box ) {
  7992. const planes = this.planes;
  7993. for ( let i = 0; i < 6; i ++ ) {
  7994. const plane = planes[ i ];
  7995. // corner at max distance
  7996. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7997. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7998. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7999. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  8000. return false;
  8001. }
  8002. }
  8003. return true;
  8004. }
  8005. containsPoint( point ) {
  8006. const planes = this.planes;
  8007. for ( let i = 0; i < 6; i ++ ) {
  8008. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8009. return false;
  8010. }
  8011. }
  8012. return true;
  8013. }
  8014. clone() {
  8015. return new this.constructor().copy( this );
  8016. }
  8017. }
  8018. function WebGLAnimation() {
  8019. let context = null;
  8020. let isAnimating = false;
  8021. let animationLoop = null;
  8022. let requestId = null;
  8023. function onAnimationFrame( time, frame ) {
  8024. animationLoop( time, frame );
  8025. requestId = context.requestAnimationFrame( onAnimationFrame );
  8026. }
  8027. return {
  8028. start: function () {
  8029. if ( isAnimating === true ) return;
  8030. if ( animationLoop === null ) return;
  8031. requestId = context.requestAnimationFrame( onAnimationFrame );
  8032. isAnimating = true;
  8033. },
  8034. stop: function () {
  8035. context.cancelAnimationFrame( requestId );
  8036. isAnimating = false;
  8037. },
  8038. setAnimationLoop: function ( callback ) {
  8039. animationLoop = callback;
  8040. },
  8041. setContext: function ( value ) {
  8042. context = value;
  8043. }
  8044. };
  8045. }
  8046. function WebGLAttributes( gl ) {
  8047. const buffers = new WeakMap();
  8048. function createBuffer( attribute, bufferType ) {
  8049. const array = attribute.array;
  8050. const usage = attribute.usage;
  8051. const size = array.byteLength;
  8052. const buffer = gl.createBuffer();
  8053. gl.bindBuffer( bufferType, buffer );
  8054. gl.bufferData( bufferType, array, usage );
  8055. attribute.onUploadCallback();
  8056. let type;
  8057. if ( array instanceof Float32Array ) {
  8058. type = gl.FLOAT;
  8059. } else if ( array instanceof Uint16Array ) {
  8060. if ( attribute.isFloat16BufferAttribute ) {
  8061. type = gl.HALF_FLOAT;
  8062. } else {
  8063. type = gl.UNSIGNED_SHORT;
  8064. }
  8065. } else if ( array instanceof Int16Array ) {
  8066. type = gl.SHORT;
  8067. } else if ( array instanceof Uint32Array ) {
  8068. type = gl.UNSIGNED_INT;
  8069. } else if ( array instanceof Int32Array ) {
  8070. type = gl.INT;
  8071. } else if ( array instanceof Int8Array ) {
  8072. type = gl.BYTE;
  8073. } else if ( array instanceof Uint8Array ) {
  8074. type = gl.UNSIGNED_BYTE;
  8075. } else if ( array instanceof Uint8ClampedArray ) {
  8076. type = gl.UNSIGNED_BYTE;
  8077. } else {
  8078. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8079. }
  8080. return {
  8081. buffer: buffer,
  8082. type: type,
  8083. bytesPerElement: array.BYTES_PER_ELEMENT,
  8084. version: attribute.version,
  8085. size: size
  8086. };
  8087. }
  8088. function updateBuffer( buffer, attribute, bufferType ) {
  8089. const array = attribute.array;
  8090. const updateRange = attribute._updateRange; // @deprecated, r159
  8091. const updateRanges = attribute.updateRanges;
  8092. gl.bindBuffer( bufferType, buffer );
  8093. if ( updateRange.count === - 1 && updateRanges.length === 0 ) {
  8094. // Not using update ranges
  8095. gl.bufferSubData( bufferType, 0, array );
  8096. }
  8097. if ( updateRanges.length !== 0 ) {
  8098. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8099. const range = updateRanges[ i ];
  8100. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8101. array, range.start, range.count );
  8102. }
  8103. attribute.clearUpdateRanges();
  8104. }
  8105. // @deprecated, r159
  8106. if ( updateRange.count !== - 1 ) {
  8107. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8108. array, updateRange.offset, updateRange.count );
  8109. updateRange.count = - 1; // reset range
  8110. }
  8111. attribute.onUploadCallback();
  8112. }
  8113. //
  8114. function get( attribute ) {
  8115. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8116. return buffers.get( attribute );
  8117. }
  8118. function remove( attribute ) {
  8119. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8120. const data = buffers.get( attribute );
  8121. if ( data ) {
  8122. gl.deleteBuffer( data.buffer );
  8123. buffers.delete( attribute );
  8124. }
  8125. }
  8126. function update( attribute, bufferType ) {
  8127. if ( attribute.isGLBufferAttribute ) {
  8128. const cached = buffers.get( attribute );
  8129. if ( ! cached || cached.version < attribute.version ) {
  8130. buffers.set( attribute, {
  8131. buffer: attribute.buffer,
  8132. type: attribute.type,
  8133. bytesPerElement: attribute.elementSize,
  8134. version: attribute.version
  8135. } );
  8136. }
  8137. return;
  8138. }
  8139. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8140. const data = buffers.get( attribute );
  8141. if ( data === undefined ) {
  8142. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8143. } else if ( data.version < attribute.version ) {
  8144. if ( data.size !== attribute.array.byteLength ) {
  8145. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  8146. }
  8147. updateBuffer( data.buffer, attribute, bufferType );
  8148. data.version = attribute.version;
  8149. }
  8150. }
  8151. return {
  8152. get: get,
  8153. remove: remove,
  8154. update: update
  8155. };
  8156. }
  8157. class PlaneGeometry extends BufferGeometry {
  8158. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8159. super();
  8160. this.type = 'PlaneGeometry';
  8161. this.parameters = {
  8162. width: width,
  8163. height: height,
  8164. widthSegments: widthSegments,
  8165. heightSegments: heightSegments
  8166. };
  8167. const width_half = width / 2;
  8168. const height_half = height / 2;
  8169. const gridX = Math.floor( widthSegments );
  8170. const gridY = Math.floor( heightSegments );
  8171. const gridX1 = gridX + 1;
  8172. const gridY1 = gridY + 1;
  8173. const segment_width = width / gridX;
  8174. const segment_height = height / gridY;
  8175. //
  8176. const indices = [];
  8177. const vertices = [];
  8178. const normals = [];
  8179. const uvs = [];
  8180. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8181. const y = iy * segment_height - height_half;
  8182. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8183. const x = ix * segment_width - width_half;
  8184. vertices.push( x, - y, 0 );
  8185. normals.push( 0, 0, 1 );
  8186. uvs.push( ix / gridX );
  8187. uvs.push( 1 - ( iy / gridY ) );
  8188. }
  8189. }
  8190. for ( let iy = 0; iy < gridY; iy ++ ) {
  8191. for ( let ix = 0; ix < gridX; ix ++ ) {
  8192. const a = ix + gridX1 * iy;
  8193. const b = ix + gridX1 * ( iy + 1 );
  8194. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8195. const d = ( ix + 1 ) + gridX1 * iy;
  8196. indices.push( a, b, d );
  8197. indices.push( b, c, d );
  8198. }
  8199. }
  8200. this.setIndex( indices );
  8201. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8202. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8203. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8204. }
  8205. copy( source ) {
  8206. super.copy( source );
  8207. this.parameters = Object.assign( {}, source.parameters );
  8208. return this;
  8209. }
  8210. static fromJSON( data ) {
  8211. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8212. }
  8213. }
  8214. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8215. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  8216. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8217. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8218. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  8219. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8220. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  8221. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8222. var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif";
  8223. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  8224. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8225. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8226. var bsdfs = "float 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} // validated";
  8227. 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\treturn 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 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";
  8228. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + 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 = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( 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";
  8229. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  8230. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8231. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8232. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8233. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8234. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8235. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8236. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_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\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  8237. 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};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\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}\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}\nvec3 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} // validated";
  8238. 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\thighp vec2 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_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\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";
  8239. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8240. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8241. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8242. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8243. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8244. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8245. var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( 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}";
  8246. 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, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\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";
  8247. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\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";
  8248. 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";
  8249. 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";
  8250. 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";
  8251. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8252. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8253. 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";
  8254. 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";
  8255. 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}";
  8256. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8257. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8258. 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  8259. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\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\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\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, 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 vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\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 vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\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";
  8260. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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#ifdef 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, envMapRotation * 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\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  8261. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8262. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  8263. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8264. 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  8265. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\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 USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\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, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).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_DISPERSION\n\tmaterial.dispersion = dispersion;\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, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).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_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  8266. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\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\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\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}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\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 = F_Schlick( f0, f90, dotVH );\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\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.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\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\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}\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\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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, 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( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, 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}";
  8267. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\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, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, geometryPosition, 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\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : 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 *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\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 ], geometryNormal );\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";
  8268. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\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( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8269. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  8270. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8271. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8272. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8273. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  8274. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\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\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8275. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8276. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\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";
  8277. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8278. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8279. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8280. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  8281. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\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";
  8282. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  8283. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif";
  8284. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  8285. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  8286. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).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( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8287. 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";
  8288. 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";
  8289. 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";
  8290. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.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 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  8291. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8292. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  8293. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  8294. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8295. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8296. 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.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in 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( const in 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 depth, const in float near, const in float far ) {\n\treturn depth * ( 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 depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  8297. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8298. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8299. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8300. 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";
  8301. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8302. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8303. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform 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 shadowIntensity;\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 shadowIntensity;\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 shadowIntensity;\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 shadowIntensity, 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\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\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 mix( 1.0, shadow, shadowIntensity );\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 shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif";
  8304. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying 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 shadowIntensity;\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 shadowIntensity;\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 shadowIntensity;\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";
  8305. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#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 ( defined( USE_SHADOWMAP ) && 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#endif";
  8306. 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.shadowIntensity, 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.shadowIntensity, 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.shadowIntensity, 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}";
  8307. 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";
  8308. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  8309. 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";
  8310. 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";
  8311. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8312. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8313. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8314. 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 saturate( 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}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8315. 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, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  8316. 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\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\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 lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\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 dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  8317. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8318. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8319. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  8320. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8321. const vertex$h = "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}";
  8322. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8323. const vertex$g = "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}";
  8324. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8325. 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}";
  8326. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8327. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_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}";
  8328. 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 <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\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 <alphahash_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#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  8329. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_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}";
  8330. 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 <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8331. 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}";
  8332. 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 <colorspace_fragment>\n}";
  8333. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\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 <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_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}";
  8334. 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 <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8335. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8336. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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, vLightMapUv );\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8337. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8338. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8339. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\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 <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8340. 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 <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8341. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8342. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\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\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\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 ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8343. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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}";
  8344. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8345. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8346. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_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 USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\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_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8347. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8348. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8349. 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>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_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}";
  8350. 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 <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8351. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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 <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8352. 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 <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8353. 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}";
  8354. 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 <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8355. const ShaderChunk = {
  8356. alphahash_fragment: alphahash_fragment,
  8357. alphahash_pars_fragment: alphahash_pars_fragment,
  8358. alphamap_fragment: alphamap_fragment,
  8359. alphamap_pars_fragment: alphamap_pars_fragment,
  8360. alphatest_fragment: alphatest_fragment,
  8361. alphatest_pars_fragment: alphatest_pars_fragment,
  8362. aomap_fragment: aomap_fragment,
  8363. aomap_pars_fragment: aomap_pars_fragment,
  8364. batching_pars_vertex: batching_pars_vertex,
  8365. batching_vertex: batching_vertex,
  8366. begin_vertex: begin_vertex,
  8367. beginnormal_vertex: beginnormal_vertex,
  8368. bsdfs: bsdfs,
  8369. iridescence_fragment: iridescence_fragment,
  8370. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8371. clipping_planes_fragment: clipping_planes_fragment,
  8372. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8373. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8374. clipping_planes_vertex: clipping_planes_vertex,
  8375. color_fragment: color_fragment,
  8376. color_pars_fragment: color_pars_fragment,
  8377. color_pars_vertex: color_pars_vertex,
  8378. color_vertex: color_vertex,
  8379. common: common,
  8380. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8381. defaultnormal_vertex: defaultnormal_vertex,
  8382. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8383. displacementmap_vertex: displacementmap_vertex,
  8384. emissivemap_fragment: emissivemap_fragment,
  8385. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8386. colorspace_fragment: colorspace_fragment,
  8387. colorspace_pars_fragment: colorspace_pars_fragment,
  8388. envmap_fragment: envmap_fragment,
  8389. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8390. envmap_pars_fragment: envmap_pars_fragment,
  8391. envmap_pars_vertex: envmap_pars_vertex,
  8392. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8393. envmap_vertex: envmap_vertex,
  8394. fog_vertex: fog_vertex,
  8395. fog_pars_vertex: fog_pars_vertex,
  8396. fog_fragment: fog_fragment,
  8397. fog_pars_fragment: fog_pars_fragment,
  8398. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8399. lightmap_pars_fragment: lightmap_pars_fragment,
  8400. lights_lambert_fragment: lights_lambert_fragment,
  8401. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8402. lights_pars_begin: lights_pars_begin,
  8403. lights_toon_fragment: lights_toon_fragment,
  8404. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8405. lights_phong_fragment: lights_phong_fragment,
  8406. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8407. lights_physical_fragment: lights_physical_fragment,
  8408. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8409. lights_fragment_begin: lights_fragment_begin,
  8410. lights_fragment_maps: lights_fragment_maps,
  8411. lights_fragment_end: lights_fragment_end,
  8412. logdepthbuf_fragment: logdepthbuf_fragment,
  8413. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8414. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8415. logdepthbuf_vertex: logdepthbuf_vertex,
  8416. map_fragment: map_fragment,
  8417. map_pars_fragment: map_pars_fragment,
  8418. map_particle_fragment: map_particle_fragment,
  8419. map_particle_pars_fragment: map_particle_pars_fragment,
  8420. metalnessmap_fragment: metalnessmap_fragment,
  8421. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8422. morphinstance_vertex: morphinstance_vertex,
  8423. morphcolor_vertex: morphcolor_vertex,
  8424. morphnormal_vertex: morphnormal_vertex,
  8425. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8426. morphtarget_vertex: morphtarget_vertex,
  8427. normal_fragment_begin: normal_fragment_begin,
  8428. normal_fragment_maps: normal_fragment_maps,
  8429. normal_pars_fragment: normal_pars_fragment,
  8430. normal_pars_vertex: normal_pars_vertex,
  8431. normal_vertex: normal_vertex,
  8432. normalmap_pars_fragment: normalmap_pars_fragment,
  8433. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8434. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8435. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8436. iridescence_pars_fragment: iridescence_pars_fragment,
  8437. opaque_fragment: opaque_fragment,
  8438. packing: packing,
  8439. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8440. project_vertex: project_vertex,
  8441. dithering_fragment: dithering_fragment,
  8442. dithering_pars_fragment: dithering_pars_fragment,
  8443. roughnessmap_fragment: roughnessmap_fragment,
  8444. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8445. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8446. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8447. shadowmap_vertex: shadowmap_vertex,
  8448. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8449. skinbase_vertex: skinbase_vertex,
  8450. skinning_pars_vertex: skinning_pars_vertex,
  8451. skinning_vertex: skinning_vertex,
  8452. skinnormal_vertex: skinnormal_vertex,
  8453. specularmap_fragment: specularmap_fragment,
  8454. specularmap_pars_fragment: specularmap_pars_fragment,
  8455. tonemapping_fragment: tonemapping_fragment,
  8456. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8457. transmission_fragment: transmission_fragment,
  8458. transmission_pars_fragment: transmission_pars_fragment,
  8459. uv_pars_fragment: uv_pars_fragment,
  8460. uv_pars_vertex: uv_pars_vertex,
  8461. uv_vertex: uv_vertex,
  8462. worldpos_vertex: worldpos_vertex,
  8463. background_vert: vertex$h,
  8464. background_frag: fragment$h,
  8465. backgroundCube_vert: vertex$g,
  8466. backgroundCube_frag: fragment$g,
  8467. cube_vert: vertex$f,
  8468. cube_frag: fragment$f,
  8469. depth_vert: vertex$e,
  8470. depth_frag: fragment$e,
  8471. distanceRGBA_vert: vertex$d,
  8472. distanceRGBA_frag: fragment$d,
  8473. equirect_vert: vertex$c,
  8474. equirect_frag: fragment$c,
  8475. linedashed_vert: vertex$b,
  8476. linedashed_frag: fragment$b,
  8477. meshbasic_vert: vertex$a,
  8478. meshbasic_frag: fragment$a,
  8479. meshlambert_vert: vertex$9,
  8480. meshlambert_frag: fragment$9,
  8481. meshmatcap_vert: vertex$8,
  8482. meshmatcap_frag: fragment$8,
  8483. meshnormal_vert: vertex$7,
  8484. meshnormal_frag: fragment$7,
  8485. meshphong_vert: vertex$6,
  8486. meshphong_frag: fragment$6,
  8487. meshphysical_vert: vertex$5,
  8488. meshphysical_frag: fragment$5,
  8489. meshtoon_vert: vertex$4,
  8490. meshtoon_frag: fragment$4,
  8491. points_vert: vertex$3,
  8492. points_frag: fragment$3,
  8493. shadow_vert: vertex$2,
  8494. shadow_frag: fragment$2,
  8495. sprite_vert: vertex$1,
  8496. sprite_frag: fragment$1
  8497. };
  8498. /**
  8499. * Uniforms library for shared webgl shaders
  8500. */
  8501. const UniformsLib = {
  8502. common: {
  8503. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8504. opacity: { value: 1.0 },
  8505. map: { value: null },
  8506. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8507. alphaMap: { value: null },
  8508. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8509. alphaTest: { value: 0 }
  8510. },
  8511. specularmap: {
  8512. specularMap: { value: null },
  8513. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8514. },
  8515. envmap: {
  8516. envMap: { value: null },
  8517. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  8518. flipEnvMap: { value: - 1 },
  8519. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8520. ior: { value: 1.5 }, // physical
  8521. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8522. },
  8523. aomap: {
  8524. aoMap: { value: null },
  8525. aoMapIntensity: { value: 1 },
  8526. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8527. },
  8528. lightmap: {
  8529. lightMap: { value: null },
  8530. lightMapIntensity: { value: 1 },
  8531. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8532. },
  8533. bumpmap: {
  8534. bumpMap: { value: null },
  8535. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8536. bumpScale: { value: 1 }
  8537. },
  8538. normalmap: {
  8539. normalMap: { value: null },
  8540. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8541. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8542. },
  8543. displacementmap: {
  8544. displacementMap: { value: null },
  8545. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8546. displacementScale: { value: 1 },
  8547. displacementBias: { value: 0 }
  8548. },
  8549. emissivemap: {
  8550. emissiveMap: { value: null },
  8551. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8552. },
  8553. metalnessmap: {
  8554. metalnessMap: { value: null },
  8555. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8556. },
  8557. roughnessmap: {
  8558. roughnessMap: { value: null },
  8559. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8560. },
  8561. gradientmap: {
  8562. gradientMap: { value: null }
  8563. },
  8564. fog: {
  8565. fogDensity: { value: 0.00025 },
  8566. fogNear: { value: 1 },
  8567. fogFar: { value: 2000 },
  8568. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8569. },
  8570. lights: {
  8571. ambientLightColor: { value: [] },
  8572. lightProbe: { value: [] },
  8573. directionalLights: { value: [], properties: {
  8574. direction: {},
  8575. color: {}
  8576. } },
  8577. directionalLightShadows: { value: [], properties: {
  8578. shadowIntensity: 1,
  8579. shadowBias: {},
  8580. shadowNormalBias: {},
  8581. shadowRadius: {},
  8582. shadowMapSize: {}
  8583. } },
  8584. directionalShadowMap: { value: [] },
  8585. directionalShadowMatrix: { value: [] },
  8586. spotLights: { value: [], properties: {
  8587. color: {},
  8588. position: {},
  8589. direction: {},
  8590. distance: {},
  8591. coneCos: {},
  8592. penumbraCos: {},
  8593. decay: {}
  8594. } },
  8595. spotLightShadows: { value: [], properties: {
  8596. shadowIntensity: 1,
  8597. shadowBias: {},
  8598. shadowNormalBias: {},
  8599. shadowRadius: {},
  8600. shadowMapSize: {}
  8601. } },
  8602. spotLightMap: { value: [] },
  8603. spotShadowMap: { value: [] },
  8604. spotLightMatrix: { value: [] },
  8605. pointLights: { value: [], properties: {
  8606. color: {},
  8607. position: {},
  8608. decay: {},
  8609. distance: {}
  8610. } },
  8611. pointLightShadows: { value: [], properties: {
  8612. shadowIntensity: 1,
  8613. shadowBias: {},
  8614. shadowNormalBias: {},
  8615. shadowRadius: {},
  8616. shadowMapSize: {},
  8617. shadowCameraNear: {},
  8618. shadowCameraFar: {}
  8619. } },
  8620. pointShadowMap: { value: [] },
  8621. pointShadowMatrix: { value: [] },
  8622. hemisphereLights: { value: [], properties: {
  8623. direction: {},
  8624. skyColor: {},
  8625. groundColor: {}
  8626. } },
  8627. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8628. rectAreaLights: { value: [], properties: {
  8629. color: {},
  8630. position: {},
  8631. width: {},
  8632. height: {}
  8633. } },
  8634. ltc_1: { value: null },
  8635. ltc_2: { value: null }
  8636. },
  8637. points: {
  8638. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8639. opacity: { value: 1.0 },
  8640. size: { value: 1.0 },
  8641. scale: { value: 1.0 },
  8642. map: { value: null },
  8643. alphaMap: { value: null },
  8644. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8645. alphaTest: { value: 0 },
  8646. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8647. },
  8648. sprite: {
  8649. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8650. opacity: { value: 1.0 },
  8651. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8652. rotation: { value: 0.0 },
  8653. map: { value: null },
  8654. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8655. alphaMap: { value: null },
  8656. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8657. alphaTest: { value: 0 }
  8658. }
  8659. };
  8660. const ShaderLib = {
  8661. basic: {
  8662. uniforms: /*@__PURE__*/ mergeUniforms( [
  8663. UniformsLib.common,
  8664. UniformsLib.specularmap,
  8665. UniformsLib.envmap,
  8666. UniformsLib.aomap,
  8667. UniformsLib.lightmap,
  8668. UniformsLib.fog
  8669. ] ),
  8670. vertexShader: ShaderChunk.meshbasic_vert,
  8671. fragmentShader: ShaderChunk.meshbasic_frag
  8672. },
  8673. lambert: {
  8674. uniforms: /*@__PURE__*/ mergeUniforms( [
  8675. UniformsLib.common,
  8676. UniformsLib.specularmap,
  8677. UniformsLib.envmap,
  8678. UniformsLib.aomap,
  8679. UniformsLib.lightmap,
  8680. UniformsLib.emissivemap,
  8681. UniformsLib.bumpmap,
  8682. UniformsLib.normalmap,
  8683. UniformsLib.displacementmap,
  8684. UniformsLib.fog,
  8685. UniformsLib.lights,
  8686. {
  8687. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8688. }
  8689. ] ),
  8690. vertexShader: ShaderChunk.meshlambert_vert,
  8691. fragmentShader: ShaderChunk.meshlambert_frag
  8692. },
  8693. phong: {
  8694. uniforms: /*@__PURE__*/ mergeUniforms( [
  8695. UniformsLib.common,
  8696. UniformsLib.specularmap,
  8697. UniformsLib.envmap,
  8698. UniformsLib.aomap,
  8699. UniformsLib.lightmap,
  8700. UniformsLib.emissivemap,
  8701. UniformsLib.bumpmap,
  8702. UniformsLib.normalmap,
  8703. UniformsLib.displacementmap,
  8704. UniformsLib.fog,
  8705. UniformsLib.lights,
  8706. {
  8707. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8708. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8709. shininess: { value: 30 }
  8710. }
  8711. ] ),
  8712. vertexShader: ShaderChunk.meshphong_vert,
  8713. fragmentShader: ShaderChunk.meshphong_frag
  8714. },
  8715. standard: {
  8716. uniforms: /*@__PURE__*/ mergeUniforms( [
  8717. UniformsLib.common,
  8718. UniformsLib.envmap,
  8719. UniformsLib.aomap,
  8720. UniformsLib.lightmap,
  8721. UniformsLib.emissivemap,
  8722. UniformsLib.bumpmap,
  8723. UniformsLib.normalmap,
  8724. UniformsLib.displacementmap,
  8725. UniformsLib.roughnessmap,
  8726. UniformsLib.metalnessmap,
  8727. UniformsLib.fog,
  8728. UniformsLib.lights,
  8729. {
  8730. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8731. roughness: { value: 1.0 },
  8732. metalness: { value: 0.0 },
  8733. envMapIntensity: { value: 1 }
  8734. }
  8735. ] ),
  8736. vertexShader: ShaderChunk.meshphysical_vert,
  8737. fragmentShader: ShaderChunk.meshphysical_frag
  8738. },
  8739. toon: {
  8740. uniforms: /*@__PURE__*/ mergeUniforms( [
  8741. UniformsLib.common,
  8742. UniformsLib.aomap,
  8743. UniformsLib.lightmap,
  8744. UniformsLib.emissivemap,
  8745. UniformsLib.bumpmap,
  8746. UniformsLib.normalmap,
  8747. UniformsLib.displacementmap,
  8748. UniformsLib.gradientmap,
  8749. UniformsLib.fog,
  8750. UniformsLib.lights,
  8751. {
  8752. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8753. }
  8754. ] ),
  8755. vertexShader: ShaderChunk.meshtoon_vert,
  8756. fragmentShader: ShaderChunk.meshtoon_frag
  8757. },
  8758. matcap: {
  8759. uniforms: /*@__PURE__*/ mergeUniforms( [
  8760. UniformsLib.common,
  8761. UniformsLib.bumpmap,
  8762. UniformsLib.normalmap,
  8763. UniformsLib.displacementmap,
  8764. UniformsLib.fog,
  8765. {
  8766. matcap: { value: null }
  8767. }
  8768. ] ),
  8769. vertexShader: ShaderChunk.meshmatcap_vert,
  8770. fragmentShader: ShaderChunk.meshmatcap_frag
  8771. },
  8772. points: {
  8773. uniforms: /*@__PURE__*/ mergeUniforms( [
  8774. UniformsLib.points,
  8775. UniformsLib.fog
  8776. ] ),
  8777. vertexShader: ShaderChunk.points_vert,
  8778. fragmentShader: ShaderChunk.points_frag
  8779. },
  8780. dashed: {
  8781. uniforms: /*@__PURE__*/ mergeUniforms( [
  8782. UniformsLib.common,
  8783. UniformsLib.fog,
  8784. {
  8785. scale: { value: 1 },
  8786. dashSize: { value: 1 },
  8787. totalSize: { value: 2 }
  8788. }
  8789. ] ),
  8790. vertexShader: ShaderChunk.linedashed_vert,
  8791. fragmentShader: ShaderChunk.linedashed_frag
  8792. },
  8793. depth: {
  8794. uniforms: /*@__PURE__*/ mergeUniforms( [
  8795. UniformsLib.common,
  8796. UniformsLib.displacementmap
  8797. ] ),
  8798. vertexShader: ShaderChunk.depth_vert,
  8799. fragmentShader: ShaderChunk.depth_frag
  8800. },
  8801. normal: {
  8802. uniforms: /*@__PURE__*/ mergeUniforms( [
  8803. UniformsLib.common,
  8804. UniformsLib.bumpmap,
  8805. UniformsLib.normalmap,
  8806. UniformsLib.displacementmap,
  8807. {
  8808. opacity: { value: 1.0 }
  8809. }
  8810. ] ),
  8811. vertexShader: ShaderChunk.meshnormal_vert,
  8812. fragmentShader: ShaderChunk.meshnormal_frag
  8813. },
  8814. sprite: {
  8815. uniforms: /*@__PURE__*/ mergeUniforms( [
  8816. UniformsLib.sprite,
  8817. UniformsLib.fog
  8818. ] ),
  8819. vertexShader: ShaderChunk.sprite_vert,
  8820. fragmentShader: ShaderChunk.sprite_frag
  8821. },
  8822. background: {
  8823. uniforms: {
  8824. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8825. t2D: { value: null },
  8826. backgroundIntensity: { value: 1 }
  8827. },
  8828. vertexShader: ShaderChunk.background_vert,
  8829. fragmentShader: ShaderChunk.background_frag
  8830. },
  8831. backgroundCube: {
  8832. uniforms: {
  8833. envMap: { value: null },
  8834. flipEnvMap: { value: - 1 },
  8835. backgroundBlurriness: { value: 0 },
  8836. backgroundIntensity: { value: 1 },
  8837. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  8838. },
  8839. vertexShader: ShaderChunk.backgroundCube_vert,
  8840. fragmentShader: ShaderChunk.backgroundCube_frag
  8841. },
  8842. cube: {
  8843. uniforms: {
  8844. tCube: { value: null },
  8845. tFlip: { value: - 1 },
  8846. opacity: { value: 1.0 }
  8847. },
  8848. vertexShader: ShaderChunk.cube_vert,
  8849. fragmentShader: ShaderChunk.cube_frag
  8850. },
  8851. equirect: {
  8852. uniforms: {
  8853. tEquirect: { value: null },
  8854. },
  8855. vertexShader: ShaderChunk.equirect_vert,
  8856. fragmentShader: ShaderChunk.equirect_frag
  8857. },
  8858. distanceRGBA: {
  8859. uniforms: /*@__PURE__*/ mergeUniforms( [
  8860. UniformsLib.common,
  8861. UniformsLib.displacementmap,
  8862. {
  8863. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8864. nearDistance: { value: 1 },
  8865. farDistance: { value: 1000 }
  8866. }
  8867. ] ),
  8868. vertexShader: ShaderChunk.distanceRGBA_vert,
  8869. fragmentShader: ShaderChunk.distanceRGBA_frag
  8870. },
  8871. shadow: {
  8872. uniforms: /*@__PURE__*/ mergeUniforms( [
  8873. UniformsLib.lights,
  8874. UniformsLib.fog,
  8875. {
  8876. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8877. opacity: { value: 1.0 }
  8878. },
  8879. ] ),
  8880. vertexShader: ShaderChunk.shadow_vert,
  8881. fragmentShader: ShaderChunk.shadow_frag
  8882. }
  8883. };
  8884. ShaderLib.physical = {
  8885. uniforms: /*@__PURE__*/ mergeUniforms( [
  8886. ShaderLib.standard.uniforms,
  8887. {
  8888. clearcoat: { value: 0 },
  8889. clearcoatMap: { value: null },
  8890. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8891. clearcoatNormalMap: { value: null },
  8892. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8893. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8894. clearcoatRoughness: { value: 0 },
  8895. clearcoatRoughnessMap: { value: null },
  8896. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8897. dispersion: { value: 0 },
  8898. iridescence: { value: 0 },
  8899. iridescenceMap: { value: null },
  8900. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8901. iridescenceIOR: { value: 1.3 },
  8902. iridescenceThicknessMinimum: { value: 100 },
  8903. iridescenceThicknessMaximum: { value: 400 },
  8904. iridescenceThicknessMap: { value: null },
  8905. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8906. sheen: { value: 0 },
  8907. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8908. sheenColorMap: { value: null },
  8909. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8910. sheenRoughness: { value: 1 },
  8911. sheenRoughnessMap: { value: null },
  8912. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8913. transmission: { value: 0 },
  8914. transmissionMap: { value: null },
  8915. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8916. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8917. transmissionSamplerMap: { value: null },
  8918. thickness: { value: 0 },
  8919. thicknessMap: { value: null },
  8920. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8921. attenuationDistance: { value: 0 },
  8922. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8923. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8924. specularColorMap: { value: null },
  8925. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8926. specularIntensity: { value: 1 },
  8927. specularIntensityMap: { value: null },
  8928. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8929. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8930. anisotropyMap: { value: null },
  8931. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8932. }
  8933. ] ),
  8934. vertexShader: ShaderChunk.meshphysical_vert,
  8935. fragmentShader: ShaderChunk.meshphysical_frag
  8936. };
  8937. const _rgb = { r: 0, b: 0, g: 0 };
  8938. const _e1$1 = /*@__PURE__*/ new Euler();
  8939. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8940. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8941. const clearColor = new Color( 0x000000 );
  8942. let clearAlpha = alpha === true ? 0 : 1;
  8943. let planeMesh;
  8944. let boxMesh;
  8945. let currentBackground = null;
  8946. let currentBackgroundVersion = 0;
  8947. let currentTonemapping = null;
  8948. function getBackground( scene ) {
  8949. let background = scene.isScene === true ? scene.background : null;
  8950. if ( background && background.isTexture ) {
  8951. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8952. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8953. }
  8954. return background;
  8955. }
  8956. function render( scene ) {
  8957. let forceClear = false;
  8958. const background = getBackground( scene );
  8959. if ( background === null ) {
  8960. setClear( clearColor, clearAlpha );
  8961. } else if ( background && background.isColor ) {
  8962. setClear( background, 1 );
  8963. forceClear = true;
  8964. }
  8965. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8966. if ( environmentBlendMode === 'additive' ) {
  8967. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8968. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8969. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8970. }
  8971. if ( renderer.autoClear || forceClear ) {
  8972. // buffers might not be writable which is required to ensure a correct clear
  8973. state.buffers.depth.setTest( true );
  8974. state.buffers.depth.setMask( true );
  8975. state.buffers.color.setMask( true );
  8976. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8977. }
  8978. }
  8979. function addToRenderList( renderList, scene ) {
  8980. const background = getBackground( scene );
  8981. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8982. if ( boxMesh === undefined ) {
  8983. boxMesh = new Mesh(
  8984. new BoxGeometry( 1, 1, 1 ),
  8985. new ShaderMaterial( {
  8986. name: 'BackgroundCubeMaterial',
  8987. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8988. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8989. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8990. side: BackSide,
  8991. depthTest: false,
  8992. depthWrite: false,
  8993. fog: false
  8994. } )
  8995. );
  8996. boxMesh.geometry.deleteAttribute( 'normal' );
  8997. boxMesh.geometry.deleteAttribute( 'uv' );
  8998. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8999. this.matrixWorld.copyPosition( camera.matrixWorld );
  9000. };
  9001. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  9002. Object.defineProperty( boxMesh.material, 'envMap', {
  9003. get: function () {
  9004. return this.uniforms.envMap.value;
  9005. }
  9006. } );
  9007. objects.update( boxMesh );
  9008. }
  9009. _e1$1.copy( scene.backgroundRotation );
  9010. // accommodate left-handed frame
  9011. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  9012. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  9013. // environment maps which are not cube render targets or PMREMs follow a different convention
  9014. _e1$1.y *= - 1;
  9015. _e1$1.z *= - 1;
  9016. }
  9017. boxMesh.material.uniforms.envMap.value = background;
  9018. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  9019. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  9020. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  9021. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  9022. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  9023. if ( currentBackground !== background ||
  9024. currentBackgroundVersion !== background.version ||
  9025. currentTonemapping !== renderer.toneMapping ) {
  9026. boxMesh.material.needsUpdate = true;
  9027. currentBackground = background;
  9028. currentBackgroundVersion = background.version;
  9029. currentTonemapping = renderer.toneMapping;
  9030. }
  9031. boxMesh.layers.enableAll();
  9032. // push to the pre-sorted opaque render list
  9033. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9034. } else if ( background && background.isTexture ) {
  9035. if ( planeMesh === undefined ) {
  9036. planeMesh = new Mesh(
  9037. new PlaneGeometry( 2, 2 ),
  9038. new ShaderMaterial( {
  9039. name: 'BackgroundMaterial',
  9040. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9041. vertexShader: ShaderLib.background.vertexShader,
  9042. fragmentShader: ShaderLib.background.fragmentShader,
  9043. side: FrontSide,
  9044. depthTest: false,
  9045. depthWrite: false,
  9046. fog: false
  9047. } )
  9048. );
  9049. planeMesh.geometry.deleteAttribute( 'normal' );
  9050. // add "map" material property so the renderer can evaluate it like for built-in materials
  9051. Object.defineProperty( planeMesh.material, 'map', {
  9052. get: function () {
  9053. return this.uniforms.t2D.value;
  9054. }
  9055. } );
  9056. objects.update( planeMesh );
  9057. }
  9058. planeMesh.material.uniforms.t2D.value = background;
  9059. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  9060. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  9061. if ( background.matrixAutoUpdate === true ) {
  9062. background.updateMatrix();
  9063. }
  9064. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9065. if ( currentBackground !== background ||
  9066. currentBackgroundVersion !== background.version ||
  9067. currentTonemapping !== renderer.toneMapping ) {
  9068. planeMesh.material.needsUpdate = true;
  9069. currentBackground = background;
  9070. currentBackgroundVersion = background.version;
  9071. currentTonemapping = renderer.toneMapping;
  9072. }
  9073. planeMesh.layers.enableAll();
  9074. // push to the pre-sorted opaque render list
  9075. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9076. }
  9077. }
  9078. function setClear( color, alpha ) {
  9079. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9080. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9081. }
  9082. return {
  9083. getClearColor: function () {
  9084. return clearColor;
  9085. },
  9086. setClearColor: function ( color, alpha = 1 ) {
  9087. clearColor.set( color );
  9088. clearAlpha = alpha;
  9089. setClear( clearColor, clearAlpha );
  9090. },
  9091. getClearAlpha: function () {
  9092. return clearAlpha;
  9093. },
  9094. setClearAlpha: function ( alpha ) {
  9095. clearAlpha = alpha;
  9096. setClear( clearColor, clearAlpha );
  9097. },
  9098. render: render,
  9099. addToRenderList: addToRenderList
  9100. };
  9101. }
  9102. function WebGLBindingStates( gl, attributes ) {
  9103. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9104. const bindingStates = {};
  9105. const defaultState = createBindingState( null );
  9106. let currentState = defaultState;
  9107. let forceUpdate = false;
  9108. function setup( object, material, program, geometry, index ) {
  9109. let updateBuffers = false;
  9110. const state = getBindingState( geometry, program, material );
  9111. if ( currentState !== state ) {
  9112. currentState = state;
  9113. bindVertexArrayObject( currentState.object );
  9114. }
  9115. updateBuffers = needsUpdate( object, geometry, program, index );
  9116. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9117. if ( index !== null ) {
  9118. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9119. }
  9120. if ( updateBuffers || forceUpdate ) {
  9121. forceUpdate = false;
  9122. setupVertexAttributes( object, material, program, geometry );
  9123. if ( index !== null ) {
  9124. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9125. }
  9126. }
  9127. }
  9128. function createVertexArrayObject() {
  9129. return gl.createVertexArray();
  9130. }
  9131. function bindVertexArrayObject( vao ) {
  9132. return gl.bindVertexArray( vao );
  9133. }
  9134. function deleteVertexArrayObject( vao ) {
  9135. return gl.deleteVertexArray( vao );
  9136. }
  9137. function getBindingState( geometry, program, material ) {
  9138. const wireframe = ( material.wireframe === true );
  9139. let programMap = bindingStates[ geometry.id ];
  9140. if ( programMap === undefined ) {
  9141. programMap = {};
  9142. bindingStates[ geometry.id ] = programMap;
  9143. }
  9144. let stateMap = programMap[ program.id ];
  9145. if ( stateMap === undefined ) {
  9146. stateMap = {};
  9147. programMap[ program.id ] = stateMap;
  9148. }
  9149. let state = stateMap[ wireframe ];
  9150. if ( state === undefined ) {
  9151. state = createBindingState( createVertexArrayObject() );
  9152. stateMap[ wireframe ] = state;
  9153. }
  9154. return state;
  9155. }
  9156. function createBindingState( vao ) {
  9157. const newAttributes = [];
  9158. const enabledAttributes = [];
  9159. const attributeDivisors = [];
  9160. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9161. newAttributes[ i ] = 0;
  9162. enabledAttributes[ i ] = 0;
  9163. attributeDivisors[ i ] = 0;
  9164. }
  9165. return {
  9166. // for backward compatibility on non-VAO support browser
  9167. geometry: null,
  9168. program: null,
  9169. wireframe: false,
  9170. newAttributes: newAttributes,
  9171. enabledAttributes: enabledAttributes,
  9172. attributeDivisors: attributeDivisors,
  9173. object: vao,
  9174. attributes: {},
  9175. index: null
  9176. };
  9177. }
  9178. function needsUpdate( object, geometry, program, index ) {
  9179. const cachedAttributes = currentState.attributes;
  9180. const geometryAttributes = geometry.attributes;
  9181. let attributesNum = 0;
  9182. const programAttributes = program.getAttributes();
  9183. for ( const name in programAttributes ) {
  9184. const programAttribute = programAttributes[ name ];
  9185. if ( programAttribute.location >= 0 ) {
  9186. const cachedAttribute = cachedAttributes[ name ];
  9187. let geometryAttribute = geometryAttributes[ name ];
  9188. if ( geometryAttribute === undefined ) {
  9189. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9190. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9191. }
  9192. if ( cachedAttribute === undefined ) return true;
  9193. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9194. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9195. attributesNum ++;
  9196. }
  9197. }
  9198. if ( currentState.attributesNum !== attributesNum ) return true;
  9199. if ( currentState.index !== index ) return true;
  9200. return false;
  9201. }
  9202. function saveCache( object, geometry, program, index ) {
  9203. const cache = {};
  9204. const attributes = geometry.attributes;
  9205. let attributesNum = 0;
  9206. const programAttributes = program.getAttributes();
  9207. for ( const name in programAttributes ) {
  9208. const programAttribute = programAttributes[ name ];
  9209. if ( programAttribute.location >= 0 ) {
  9210. let attribute = attributes[ name ];
  9211. if ( attribute === undefined ) {
  9212. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9213. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9214. }
  9215. const data = {};
  9216. data.attribute = attribute;
  9217. if ( attribute && attribute.data ) {
  9218. data.data = attribute.data;
  9219. }
  9220. cache[ name ] = data;
  9221. attributesNum ++;
  9222. }
  9223. }
  9224. currentState.attributes = cache;
  9225. currentState.attributesNum = attributesNum;
  9226. currentState.index = index;
  9227. }
  9228. function initAttributes() {
  9229. const newAttributes = currentState.newAttributes;
  9230. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9231. newAttributes[ i ] = 0;
  9232. }
  9233. }
  9234. function enableAttribute( attribute ) {
  9235. enableAttributeAndDivisor( attribute, 0 );
  9236. }
  9237. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9238. const newAttributes = currentState.newAttributes;
  9239. const enabledAttributes = currentState.enabledAttributes;
  9240. const attributeDivisors = currentState.attributeDivisors;
  9241. newAttributes[ attribute ] = 1;
  9242. if ( enabledAttributes[ attribute ] === 0 ) {
  9243. gl.enableVertexAttribArray( attribute );
  9244. enabledAttributes[ attribute ] = 1;
  9245. }
  9246. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9247. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  9248. attributeDivisors[ attribute ] = meshPerAttribute;
  9249. }
  9250. }
  9251. function disableUnusedAttributes() {
  9252. const newAttributes = currentState.newAttributes;
  9253. const enabledAttributes = currentState.enabledAttributes;
  9254. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9255. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9256. gl.disableVertexAttribArray( i );
  9257. enabledAttributes[ i ] = 0;
  9258. }
  9259. }
  9260. }
  9261. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9262. if ( integer === true ) {
  9263. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9264. } else {
  9265. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9266. }
  9267. }
  9268. function setupVertexAttributes( object, material, program, geometry ) {
  9269. initAttributes();
  9270. const geometryAttributes = geometry.attributes;
  9271. const programAttributes = program.getAttributes();
  9272. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9273. for ( const name in programAttributes ) {
  9274. const programAttribute = programAttributes[ name ];
  9275. if ( programAttribute.location >= 0 ) {
  9276. let geometryAttribute = geometryAttributes[ name ];
  9277. if ( geometryAttribute === undefined ) {
  9278. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9279. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9280. }
  9281. if ( geometryAttribute !== undefined ) {
  9282. const normalized = geometryAttribute.normalized;
  9283. const size = geometryAttribute.itemSize;
  9284. const attribute = attributes.get( geometryAttribute );
  9285. // TODO Attribute may not be available on context restore
  9286. if ( attribute === undefined ) continue;
  9287. const buffer = attribute.buffer;
  9288. const type = attribute.type;
  9289. const bytesPerElement = attribute.bytesPerElement;
  9290. // check for integer attributes
  9291. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  9292. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9293. const data = geometryAttribute.data;
  9294. const stride = data.stride;
  9295. const offset = geometryAttribute.offset;
  9296. if ( data.isInstancedInterleavedBuffer ) {
  9297. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9298. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9299. }
  9300. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9301. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9302. }
  9303. } else {
  9304. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9305. enableAttribute( programAttribute.location + i );
  9306. }
  9307. }
  9308. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9309. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9310. vertexAttribPointer(
  9311. programAttribute.location + i,
  9312. size / programAttribute.locationSize,
  9313. type,
  9314. normalized,
  9315. stride * bytesPerElement,
  9316. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9317. integer
  9318. );
  9319. }
  9320. } else {
  9321. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9322. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9323. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9324. }
  9325. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9326. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9327. }
  9328. } else {
  9329. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9330. enableAttribute( programAttribute.location + i );
  9331. }
  9332. }
  9333. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9334. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9335. vertexAttribPointer(
  9336. programAttribute.location + i,
  9337. size / programAttribute.locationSize,
  9338. type,
  9339. normalized,
  9340. size * bytesPerElement,
  9341. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9342. integer
  9343. );
  9344. }
  9345. }
  9346. } else if ( materialDefaultAttributeValues !== undefined ) {
  9347. const value = materialDefaultAttributeValues[ name ];
  9348. if ( value !== undefined ) {
  9349. switch ( value.length ) {
  9350. case 2:
  9351. gl.vertexAttrib2fv( programAttribute.location, value );
  9352. break;
  9353. case 3:
  9354. gl.vertexAttrib3fv( programAttribute.location, value );
  9355. break;
  9356. case 4:
  9357. gl.vertexAttrib4fv( programAttribute.location, value );
  9358. break;
  9359. default:
  9360. gl.vertexAttrib1fv( programAttribute.location, value );
  9361. }
  9362. }
  9363. }
  9364. }
  9365. }
  9366. disableUnusedAttributes();
  9367. }
  9368. function dispose() {
  9369. reset();
  9370. for ( const geometryId in bindingStates ) {
  9371. const programMap = bindingStates[ geometryId ];
  9372. for ( const programId in programMap ) {
  9373. const stateMap = programMap[ programId ];
  9374. for ( const wireframe in stateMap ) {
  9375. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9376. delete stateMap[ wireframe ];
  9377. }
  9378. delete programMap[ programId ];
  9379. }
  9380. delete bindingStates[ geometryId ];
  9381. }
  9382. }
  9383. function releaseStatesOfGeometry( geometry ) {
  9384. if ( bindingStates[ geometry.id ] === undefined ) return;
  9385. const programMap = bindingStates[ geometry.id ];
  9386. for ( const programId in programMap ) {
  9387. const stateMap = programMap[ programId ];
  9388. for ( const wireframe in stateMap ) {
  9389. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9390. delete stateMap[ wireframe ];
  9391. }
  9392. delete programMap[ programId ];
  9393. }
  9394. delete bindingStates[ geometry.id ];
  9395. }
  9396. function releaseStatesOfProgram( program ) {
  9397. for ( const geometryId in bindingStates ) {
  9398. const programMap = bindingStates[ geometryId ];
  9399. if ( programMap[ program.id ] === undefined ) continue;
  9400. const stateMap = programMap[ program.id ];
  9401. for ( const wireframe in stateMap ) {
  9402. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9403. delete stateMap[ wireframe ];
  9404. }
  9405. delete programMap[ program.id ];
  9406. }
  9407. }
  9408. function reset() {
  9409. resetDefaultState();
  9410. forceUpdate = true;
  9411. if ( currentState === defaultState ) return;
  9412. currentState = defaultState;
  9413. bindVertexArrayObject( currentState.object );
  9414. }
  9415. // for backward-compatibility
  9416. function resetDefaultState() {
  9417. defaultState.geometry = null;
  9418. defaultState.program = null;
  9419. defaultState.wireframe = false;
  9420. }
  9421. return {
  9422. setup: setup,
  9423. reset: reset,
  9424. resetDefaultState: resetDefaultState,
  9425. dispose: dispose,
  9426. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9427. releaseStatesOfProgram: releaseStatesOfProgram,
  9428. initAttributes: initAttributes,
  9429. enableAttribute: enableAttribute,
  9430. disableUnusedAttributes: disableUnusedAttributes
  9431. };
  9432. }
  9433. function WebGLBufferRenderer( gl, extensions, info ) {
  9434. let mode;
  9435. function setMode( value ) {
  9436. mode = value;
  9437. }
  9438. function render( start, count ) {
  9439. gl.drawArrays( mode, start, count );
  9440. info.update( count, mode, 1 );
  9441. }
  9442. function renderInstances( start, count, primcount ) {
  9443. if ( primcount === 0 ) return;
  9444. gl.drawArraysInstanced( mode, start, count, primcount );
  9445. info.update( count, mode, primcount );
  9446. }
  9447. function renderMultiDraw( starts, counts, drawCount ) {
  9448. if ( drawCount === 0 ) return;
  9449. const extension = extensions.get( 'WEBGL_multi_draw' );
  9450. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9451. let elementCount = 0;
  9452. for ( let i = 0; i < drawCount; i ++ ) {
  9453. elementCount += counts[ i ];
  9454. }
  9455. info.update( elementCount, mode, 1 );
  9456. }
  9457. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  9458. if ( drawCount === 0 ) return;
  9459. const extension = extensions.get( 'WEBGL_multi_draw' );
  9460. if ( extension === null ) {
  9461. for ( let i = 0; i < starts.length; i ++ ) {
  9462. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  9463. }
  9464. } else {
  9465. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  9466. let elementCount = 0;
  9467. for ( let i = 0; i < drawCount; i ++ ) {
  9468. elementCount += counts[ i ];
  9469. }
  9470. for ( let i = 0; i < primcount.length; i ++ ) {
  9471. info.update( elementCount, mode, primcount[ i ] );
  9472. }
  9473. }
  9474. }
  9475. //
  9476. this.setMode = setMode;
  9477. this.render = render;
  9478. this.renderInstances = renderInstances;
  9479. this.renderMultiDraw = renderMultiDraw;
  9480. this.renderMultiDrawInstances = renderMultiDrawInstances;
  9481. }
  9482. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  9483. let maxAnisotropy;
  9484. function getMaxAnisotropy() {
  9485. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9486. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9487. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9488. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9489. } else {
  9490. maxAnisotropy = 0;
  9491. }
  9492. return maxAnisotropy;
  9493. }
  9494. function textureFormatReadable( textureFormat ) {
  9495. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  9496. return false;
  9497. }
  9498. return true;
  9499. }
  9500. function textureTypeReadable( textureType ) {
  9501. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  9502. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  9503. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  9504. return false;
  9505. }
  9506. return true;
  9507. }
  9508. function getMaxPrecision( precision ) {
  9509. if ( precision === 'highp' ) {
  9510. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9511. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9512. return 'highp';
  9513. }
  9514. precision = 'mediump';
  9515. }
  9516. if ( precision === 'mediump' ) {
  9517. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9518. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9519. return 'mediump';
  9520. }
  9521. }
  9522. return 'lowp';
  9523. }
  9524. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9525. const maxPrecision = getMaxPrecision( precision );
  9526. if ( maxPrecision !== precision ) {
  9527. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9528. precision = maxPrecision;
  9529. }
  9530. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9531. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9532. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9533. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9534. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9535. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9536. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9537. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9538. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9539. const vertexTextures = maxVertexTextures > 0;
  9540. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  9541. return {
  9542. isWebGL2: true, // keeping this for backwards compatibility
  9543. getMaxAnisotropy: getMaxAnisotropy,
  9544. getMaxPrecision: getMaxPrecision,
  9545. textureFormatReadable: textureFormatReadable,
  9546. textureTypeReadable: textureTypeReadable,
  9547. precision: precision,
  9548. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9549. maxTextures: maxTextures,
  9550. maxVertexTextures: maxVertexTextures,
  9551. maxTextureSize: maxTextureSize,
  9552. maxCubemapSize: maxCubemapSize,
  9553. maxAttributes: maxAttributes,
  9554. maxVertexUniforms: maxVertexUniforms,
  9555. maxVaryings: maxVaryings,
  9556. maxFragmentUniforms: maxFragmentUniforms,
  9557. vertexTextures: vertexTextures,
  9558. maxSamples: maxSamples
  9559. };
  9560. }
  9561. function WebGLClipping( properties ) {
  9562. const scope = this;
  9563. let globalState = null,
  9564. numGlobalPlanes = 0,
  9565. localClippingEnabled = false,
  9566. renderingShadows = false;
  9567. const plane = new Plane(),
  9568. viewNormalMatrix = new Matrix3(),
  9569. uniform = { value: null, needsUpdate: false };
  9570. this.uniform = uniform;
  9571. this.numPlanes = 0;
  9572. this.numIntersection = 0;
  9573. this.init = function ( planes, enableLocalClipping ) {
  9574. const enabled =
  9575. planes.length !== 0 ||
  9576. enableLocalClipping ||
  9577. // enable state of previous frame - the clipping code has to
  9578. // run another frame in order to reset the state:
  9579. numGlobalPlanes !== 0 ||
  9580. localClippingEnabled;
  9581. localClippingEnabled = enableLocalClipping;
  9582. numGlobalPlanes = planes.length;
  9583. return enabled;
  9584. };
  9585. this.beginShadows = function () {
  9586. renderingShadows = true;
  9587. projectPlanes( null );
  9588. };
  9589. this.endShadows = function () {
  9590. renderingShadows = false;
  9591. };
  9592. this.setGlobalState = function ( planes, camera ) {
  9593. globalState = projectPlanes( planes, camera, 0 );
  9594. };
  9595. this.setState = function ( material, camera, useCache ) {
  9596. const planes = material.clippingPlanes,
  9597. clipIntersection = material.clipIntersection,
  9598. clipShadows = material.clipShadows;
  9599. const materialProperties = properties.get( material );
  9600. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9601. // there's no local clipping
  9602. if ( renderingShadows ) {
  9603. // there's no global clipping
  9604. projectPlanes( null );
  9605. } else {
  9606. resetGlobalState();
  9607. }
  9608. } else {
  9609. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9610. lGlobal = nGlobal * 4;
  9611. let dstArray = materialProperties.clippingState || null;
  9612. uniform.value = dstArray; // ensure unique state
  9613. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9614. for ( let i = 0; i !== lGlobal; ++ i ) {
  9615. dstArray[ i ] = globalState[ i ];
  9616. }
  9617. materialProperties.clippingState = dstArray;
  9618. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9619. this.numPlanes += nGlobal;
  9620. }
  9621. };
  9622. function resetGlobalState() {
  9623. if ( uniform.value !== globalState ) {
  9624. uniform.value = globalState;
  9625. uniform.needsUpdate = numGlobalPlanes > 0;
  9626. }
  9627. scope.numPlanes = numGlobalPlanes;
  9628. scope.numIntersection = 0;
  9629. }
  9630. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9631. const nPlanes = planes !== null ? planes.length : 0;
  9632. let dstArray = null;
  9633. if ( nPlanes !== 0 ) {
  9634. dstArray = uniform.value;
  9635. if ( skipTransform !== true || dstArray === null ) {
  9636. const flatSize = dstOffset + nPlanes * 4,
  9637. viewMatrix = camera.matrixWorldInverse;
  9638. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9639. if ( dstArray === null || dstArray.length < flatSize ) {
  9640. dstArray = new Float32Array( flatSize );
  9641. }
  9642. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9643. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9644. plane.normal.toArray( dstArray, i4 );
  9645. dstArray[ i4 + 3 ] = plane.constant;
  9646. }
  9647. }
  9648. uniform.value = dstArray;
  9649. uniform.needsUpdate = true;
  9650. }
  9651. scope.numPlanes = nPlanes;
  9652. scope.numIntersection = 0;
  9653. return dstArray;
  9654. }
  9655. }
  9656. function WebGLCubeMaps( renderer ) {
  9657. let cubemaps = new WeakMap();
  9658. function mapTextureMapping( texture, mapping ) {
  9659. if ( mapping === EquirectangularReflectionMapping ) {
  9660. texture.mapping = CubeReflectionMapping;
  9661. } else if ( mapping === EquirectangularRefractionMapping ) {
  9662. texture.mapping = CubeRefractionMapping;
  9663. }
  9664. return texture;
  9665. }
  9666. function get( texture ) {
  9667. if ( texture && texture.isTexture ) {
  9668. const mapping = texture.mapping;
  9669. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9670. if ( cubemaps.has( texture ) ) {
  9671. const cubemap = cubemaps.get( texture ).texture;
  9672. return mapTextureMapping( cubemap, texture.mapping );
  9673. } else {
  9674. const image = texture.image;
  9675. if ( image && image.height > 0 ) {
  9676. const renderTarget = new WebGLCubeRenderTarget( image.height );
  9677. renderTarget.fromEquirectangularTexture( renderer, texture );
  9678. cubemaps.set( texture, renderTarget );
  9679. texture.addEventListener( 'dispose', onTextureDispose );
  9680. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9681. } else {
  9682. // image not yet ready. try the conversion next frame
  9683. return null;
  9684. }
  9685. }
  9686. }
  9687. }
  9688. return texture;
  9689. }
  9690. function onTextureDispose( event ) {
  9691. const texture = event.target;
  9692. texture.removeEventListener( 'dispose', onTextureDispose );
  9693. const cubemap = cubemaps.get( texture );
  9694. if ( cubemap !== undefined ) {
  9695. cubemaps.delete( texture );
  9696. cubemap.dispose();
  9697. }
  9698. }
  9699. function dispose() {
  9700. cubemaps = new WeakMap();
  9701. }
  9702. return {
  9703. get: get,
  9704. dispose: dispose
  9705. };
  9706. }
  9707. class OrthographicCamera extends Camera {
  9708. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9709. super();
  9710. this.isOrthographicCamera = true;
  9711. this.type = 'OrthographicCamera';
  9712. this.zoom = 1;
  9713. this.view = null;
  9714. this.left = left;
  9715. this.right = right;
  9716. this.top = top;
  9717. this.bottom = bottom;
  9718. this.near = near;
  9719. this.far = far;
  9720. this.updateProjectionMatrix();
  9721. }
  9722. copy( source, recursive ) {
  9723. super.copy( source, recursive );
  9724. this.left = source.left;
  9725. this.right = source.right;
  9726. this.top = source.top;
  9727. this.bottom = source.bottom;
  9728. this.near = source.near;
  9729. this.far = source.far;
  9730. this.zoom = source.zoom;
  9731. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9732. return this;
  9733. }
  9734. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9735. if ( this.view === null ) {
  9736. this.view = {
  9737. enabled: true,
  9738. fullWidth: 1,
  9739. fullHeight: 1,
  9740. offsetX: 0,
  9741. offsetY: 0,
  9742. width: 1,
  9743. height: 1
  9744. };
  9745. }
  9746. this.view.enabled = true;
  9747. this.view.fullWidth = fullWidth;
  9748. this.view.fullHeight = fullHeight;
  9749. this.view.offsetX = x;
  9750. this.view.offsetY = y;
  9751. this.view.width = width;
  9752. this.view.height = height;
  9753. this.updateProjectionMatrix();
  9754. }
  9755. clearViewOffset() {
  9756. if ( this.view !== null ) {
  9757. this.view.enabled = false;
  9758. }
  9759. this.updateProjectionMatrix();
  9760. }
  9761. updateProjectionMatrix() {
  9762. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9763. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9764. const cx = ( this.right + this.left ) / 2;
  9765. const cy = ( this.top + this.bottom ) / 2;
  9766. let left = cx - dx;
  9767. let right = cx + dx;
  9768. let top = cy + dy;
  9769. let bottom = cy - dy;
  9770. if ( this.view !== null && this.view.enabled ) {
  9771. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9772. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9773. left += scaleW * this.view.offsetX;
  9774. right = left + scaleW * this.view.width;
  9775. top -= scaleH * this.view.offsetY;
  9776. bottom = top - scaleH * this.view.height;
  9777. }
  9778. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9779. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9780. }
  9781. toJSON( meta ) {
  9782. const data = super.toJSON( meta );
  9783. data.object.zoom = this.zoom;
  9784. data.object.left = this.left;
  9785. data.object.right = this.right;
  9786. data.object.top = this.top;
  9787. data.object.bottom = this.bottom;
  9788. data.object.near = this.near;
  9789. data.object.far = this.far;
  9790. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9791. return data;
  9792. }
  9793. }
  9794. const LOD_MIN = 4;
  9795. // The standard deviations (radians) associated with the extra mips. These are
  9796. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9797. // geometric shadowing function. These sigma values squared must match the
  9798. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9799. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9800. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9801. // samples and exit early, but not recompile the shader.
  9802. const MAX_SAMPLES = 20;
  9803. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9804. const _clearColor = /*@__PURE__*/ new Color();
  9805. let _oldTarget = null;
  9806. let _oldActiveCubeFace = 0;
  9807. let _oldActiveMipmapLevel = 0;
  9808. let _oldXrEnabled = false;
  9809. // Golden Ratio
  9810. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9811. const INV_PHI = 1 / PHI;
  9812. // Vertices of a dodecahedron (except the opposites, which represent the
  9813. // same axis), used as axis directions evenly spread on a sphere.
  9814. const _axisDirections = [
  9815. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  9816. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9817. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9818. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9819. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9820. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9821. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9822. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9823. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9824. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  9825. /**
  9826. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9827. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9828. * blur to be quickly accessed based on material roughness. It is packed into a
  9829. * special CubeUV format that allows us to perform custom interpolation so that
  9830. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9831. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9832. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9833. * higher roughness levels. In this way we maintain resolution to smoothly
  9834. * interpolate diffuse lighting while limiting sampling computation.
  9835. *
  9836. * Paper: Fast, Accurate Image-Based Lighting
  9837. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9838. */
  9839. class PMREMGenerator {
  9840. constructor( renderer ) {
  9841. this._renderer = renderer;
  9842. this._pingPongRenderTarget = null;
  9843. this._lodMax = 0;
  9844. this._cubeSize = 0;
  9845. this._lodPlanes = [];
  9846. this._sizeLods = [];
  9847. this._sigmas = [];
  9848. this._blurMaterial = null;
  9849. this._cubemapMaterial = null;
  9850. this._equirectMaterial = null;
  9851. this._compileMaterial( this._blurMaterial );
  9852. }
  9853. /**
  9854. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9855. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9856. * in radians to be applied to the scene before PMREM generation. Optional near
  9857. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9858. * is placed at the origin).
  9859. */
  9860. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9861. _oldTarget = this._renderer.getRenderTarget();
  9862. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9863. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9864. _oldXrEnabled = this._renderer.xr.enabled;
  9865. this._renderer.xr.enabled = false;
  9866. this._setSize( 256 );
  9867. const cubeUVRenderTarget = this._allocateTargets();
  9868. cubeUVRenderTarget.depthBuffer = true;
  9869. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9870. if ( sigma > 0 ) {
  9871. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9872. }
  9873. this._applyPMREM( cubeUVRenderTarget );
  9874. this._cleanup( cubeUVRenderTarget );
  9875. return cubeUVRenderTarget;
  9876. }
  9877. /**
  9878. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9879. * or HDR. The ideal input image size is 1k (1024 x 512),
  9880. * as this matches best with the 256 x 256 cubemap output.
  9881. * The smallest supported equirectangular image size is 64 x 32.
  9882. */
  9883. fromEquirectangular( equirectangular, renderTarget = null ) {
  9884. return this._fromTexture( equirectangular, renderTarget );
  9885. }
  9886. /**
  9887. * Generates a PMREM from an cubemap texture, which can be either LDR
  9888. * or HDR. The ideal input cube size is 256 x 256,
  9889. * as this matches best with the 256 x 256 cubemap output.
  9890. * The smallest supported cube size is 16 x 16.
  9891. */
  9892. fromCubemap( cubemap, renderTarget = null ) {
  9893. return this._fromTexture( cubemap, renderTarget );
  9894. }
  9895. /**
  9896. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9897. * your texture's network fetch for increased concurrency.
  9898. */
  9899. compileCubemapShader() {
  9900. if ( this._cubemapMaterial === null ) {
  9901. this._cubemapMaterial = _getCubemapMaterial();
  9902. this._compileMaterial( this._cubemapMaterial );
  9903. }
  9904. }
  9905. /**
  9906. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9907. * your texture's network fetch for increased concurrency.
  9908. */
  9909. compileEquirectangularShader() {
  9910. if ( this._equirectMaterial === null ) {
  9911. this._equirectMaterial = _getEquirectMaterial();
  9912. this._compileMaterial( this._equirectMaterial );
  9913. }
  9914. }
  9915. /**
  9916. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9917. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9918. * one of them will cause any others to also become unusable.
  9919. */
  9920. dispose() {
  9921. this._dispose();
  9922. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9923. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9924. }
  9925. // private interface
  9926. _setSize( cubeSize ) {
  9927. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9928. this._cubeSize = Math.pow( 2, this._lodMax );
  9929. }
  9930. _dispose() {
  9931. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9932. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9933. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9934. this._lodPlanes[ i ].dispose();
  9935. }
  9936. }
  9937. _cleanup( outputTarget ) {
  9938. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9939. this._renderer.xr.enabled = _oldXrEnabled;
  9940. outputTarget.scissorTest = false;
  9941. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9942. }
  9943. _fromTexture( texture, renderTarget ) {
  9944. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9945. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9946. } else { // Equirectangular
  9947. this._setSize( texture.image.width / 4 );
  9948. }
  9949. _oldTarget = this._renderer.getRenderTarget();
  9950. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9951. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9952. _oldXrEnabled = this._renderer.xr.enabled;
  9953. this._renderer.xr.enabled = false;
  9954. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9955. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9956. this._applyPMREM( cubeUVRenderTarget );
  9957. this._cleanup( cubeUVRenderTarget );
  9958. return cubeUVRenderTarget;
  9959. }
  9960. _allocateTargets() {
  9961. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9962. const height = 4 * this._cubeSize;
  9963. const params = {
  9964. magFilter: LinearFilter,
  9965. minFilter: LinearFilter,
  9966. generateMipmaps: false,
  9967. type: HalfFloatType,
  9968. format: RGBAFormat,
  9969. colorSpace: LinearSRGBColorSpace,
  9970. depthBuffer: false
  9971. };
  9972. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9973. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9974. if ( this._pingPongRenderTarget !== null ) {
  9975. this._dispose();
  9976. }
  9977. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9978. const { _lodMax } = this;
  9979. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9980. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9981. }
  9982. return cubeUVRenderTarget;
  9983. }
  9984. _compileMaterial( material ) {
  9985. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9986. this._renderer.compile( tmpMesh, _flatCamera );
  9987. }
  9988. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9989. const fov = 90;
  9990. const aspect = 1;
  9991. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9992. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9993. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9994. const renderer = this._renderer;
  9995. const originalAutoClear = renderer.autoClear;
  9996. const toneMapping = renderer.toneMapping;
  9997. renderer.getClearColor( _clearColor );
  9998. renderer.toneMapping = NoToneMapping;
  9999. renderer.autoClear = false;
  10000. const backgroundMaterial = new MeshBasicMaterial( {
  10001. name: 'PMREM.Background',
  10002. side: BackSide,
  10003. depthWrite: false,
  10004. depthTest: false,
  10005. } );
  10006. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  10007. let useSolidColor = false;
  10008. const background = scene.background;
  10009. if ( background ) {
  10010. if ( background.isColor ) {
  10011. backgroundMaterial.color.copy( background );
  10012. scene.background = null;
  10013. useSolidColor = true;
  10014. }
  10015. } else {
  10016. backgroundMaterial.color.copy( _clearColor );
  10017. useSolidColor = true;
  10018. }
  10019. for ( let i = 0; i < 6; i ++ ) {
  10020. const col = i % 3;
  10021. if ( col === 0 ) {
  10022. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10023. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  10024. } else if ( col === 1 ) {
  10025. cubeCamera.up.set( 0, 0, upSign[ i ] );
  10026. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  10027. } else {
  10028. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10029. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  10030. }
  10031. const size = this._cubeSize;
  10032. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  10033. renderer.setRenderTarget( cubeUVRenderTarget );
  10034. if ( useSolidColor ) {
  10035. renderer.render( backgroundBox, cubeCamera );
  10036. }
  10037. renderer.render( scene, cubeCamera );
  10038. }
  10039. backgroundBox.geometry.dispose();
  10040. backgroundBox.material.dispose();
  10041. renderer.toneMapping = toneMapping;
  10042. renderer.autoClear = originalAutoClear;
  10043. scene.background = background;
  10044. }
  10045. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  10046. const renderer = this._renderer;
  10047. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  10048. if ( isCubeTexture ) {
  10049. if ( this._cubemapMaterial === null ) {
  10050. this._cubemapMaterial = _getCubemapMaterial();
  10051. }
  10052. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  10053. } else {
  10054. if ( this._equirectMaterial === null ) {
  10055. this._equirectMaterial = _getEquirectMaterial();
  10056. }
  10057. }
  10058. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  10059. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  10060. const uniforms = material.uniforms;
  10061. uniforms[ 'envMap' ].value = texture;
  10062. const size = this._cubeSize;
  10063. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  10064. renderer.setRenderTarget( cubeUVRenderTarget );
  10065. renderer.render( mesh, _flatCamera );
  10066. }
  10067. _applyPMREM( cubeUVRenderTarget ) {
  10068. const renderer = this._renderer;
  10069. const autoClear = renderer.autoClear;
  10070. renderer.autoClear = false;
  10071. const n = this._lodPlanes.length;
  10072. for ( let i = 1; i < n; i ++ ) {
  10073. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  10074. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  10075. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10076. }
  10077. renderer.autoClear = autoClear;
  10078. }
  10079. /**
  10080. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10081. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10082. * the blur latitudinally (around the poles), and then longitudinally (towards
  10083. * the poles) to approximate the orthogonally-separable blur. It is least
  10084. * accurate at the poles, but still does a decent job.
  10085. */
  10086. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10087. const pingPongRenderTarget = this._pingPongRenderTarget;
  10088. this._halfBlur(
  10089. cubeUVRenderTarget,
  10090. pingPongRenderTarget,
  10091. lodIn,
  10092. lodOut,
  10093. sigma,
  10094. 'latitudinal',
  10095. poleAxis );
  10096. this._halfBlur(
  10097. pingPongRenderTarget,
  10098. cubeUVRenderTarget,
  10099. lodOut,
  10100. lodOut,
  10101. sigma,
  10102. 'longitudinal',
  10103. poleAxis );
  10104. }
  10105. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10106. const renderer = this._renderer;
  10107. const blurMaterial = this._blurMaterial;
  10108. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10109. console.error(
  10110. 'blur direction must be either latitudinal or longitudinal!' );
  10111. }
  10112. // Number of standard deviations at which to cut off the discrete approximation.
  10113. const STANDARD_DEVIATIONS = 3;
  10114. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10115. const blurUniforms = blurMaterial.uniforms;
  10116. const pixels = this._sizeLods[ lodIn ] - 1;
  10117. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10118. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10119. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10120. if ( samples > MAX_SAMPLES ) {
  10121. console.warn( `sigmaRadians, ${
  10122. sigmaRadians}, is too large and will clip, as it requested ${
  10123. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10124. }
  10125. const weights = [];
  10126. let sum = 0;
  10127. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10128. const x = i / sigmaPixels;
  10129. const weight = Math.exp( - x * x / 2 );
  10130. weights.push( weight );
  10131. if ( i === 0 ) {
  10132. sum += weight;
  10133. } else if ( i < samples ) {
  10134. sum += 2 * weight;
  10135. }
  10136. }
  10137. for ( let i = 0; i < weights.length; i ++ ) {
  10138. weights[ i ] = weights[ i ] / sum;
  10139. }
  10140. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10141. blurUniforms[ 'samples' ].value = samples;
  10142. blurUniforms[ 'weights' ].value = weights;
  10143. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10144. if ( poleAxis ) {
  10145. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10146. }
  10147. const { _lodMax } = this;
  10148. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10149. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10150. const outputSize = this._sizeLods[ lodOut ];
  10151. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10152. const y = 4 * ( this._cubeSize - outputSize );
  10153. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10154. renderer.setRenderTarget( targetOut );
  10155. renderer.render( blurMesh, _flatCamera );
  10156. }
  10157. }
  10158. function _createPlanes( lodMax ) {
  10159. const lodPlanes = [];
  10160. const sizeLods = [];
  10161. const sigmas = [];
  10162. let lod = lodMax;
  10163. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10164. for ( let i = 0; i < totalLods; i ++ ) {
  10165. const sizeLod = Math.pow( 2, lod );
  10166. sizeLods.push( sizeLod );
  10167. let sigma = 1.0 / sizeLod;
  10168. if ( i > lodMax - LOD_MIN ) {
  10169. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10170. } else if ( i === 0 ) {
  10171. sigma = 0;
  10172. }
  10173. sigmas.push( sigma );
  10174. const texelSize = 1.0 / ( sizeLod - 2 );
  10175. const min = - texelSize;
  10176. const max = 1 + texelSize;
  10177. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10178. const cubeFaces = 6;
  10179. const vertices = 6;
  10180. const positionSize = 3;
  10181. const uvSize = 2;
  10182. const faceIndexSize = 1;
  10183. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10184. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10185. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10186. for ( let face = 0; face < cubeFaces; face ++ ) {
  10187. const x = ( face % 3 ) * 2 / 3 - 1;
  10188. const y = face > 2 ? 0 : - 1;
  10189. const coordinates = [
  10190. x, y, 0,
  10191. x + 2 / 3, y, 0,
  10192. x + 2 / 3, y + 1, 0,
  10193. x, y, 0,
  10194. x + 2 / 3, y + 1, 0,
  10195. x, y + 1, 0
  10196. ];
  10197. position.set( coordinates, positionSize * vertices * face );
  10198. uv.set( uv1, uvSize * vertices * face );
  10199. const fill = [ face, face, face, face, face, face ];
  10200. faceIndex.set( fill, faceIndexSize * vertices * face );
  10201. }
  10202. const planes = new BufferGeometry();
  10203. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10204. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10205. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10206. lodPlanes.push( planes );
  10207. if ( lod > LOD_MIN ) {
  10208. lod --;
  10209. }
  10210. }
  10211. return { lodPlanes, sizeLods, sigmas };
  10212. }
  10213. function _createRenderTarget( width, height, params ) {
  10214. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10215. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10216. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10217. cubeUVRenderTarget.scissorTest = true;
  10218. return cubeUVRenderTarget;
  10219. }
  10220. function _setViewport( target, x, y, width, height ) {
  10221. target.viewport.set( x, y, width, height );
  10222. target.scissor.set( x, y, width, height );
  10223. }
  10224. function _getBlurShader( lodMax, width, height ) {
  10225. const weights = new Float32Array( MAX_SAMPLES );
  10226. const poleAxis = new Vector3( 0, 1, 0 );
  10227. const shaderMaterial = new ShaderMaterial( {
  10228. name: 'SphericalGaussianBlur',
  10229. defines: {
  10230. 'n': MAX_SAMPLES,
  10231. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10232. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10233. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10234. },
  10235. uniforms: {
  10236. 'envMap': { value: null },
  10237. 'samples': { value: 1 },
  10238. 'weights': { value: weights },
  10239. 'latitudinal': { value: false },
  10240. 'dTheta': { value: 0 },
  10241. 'mipInt': { value: 0 },
  10242. 'poleAxis': { value: poleAxis }
  10243. },
  10244. vertexShader: _getCommonVertexShader(),
  10245. fragmentShader: /* glsl */`
  10246. precision mediump float;
  10247. precision mediump int;
  10248. varying vec3 vOutputDirection;
  10249. uniform sampler2D envMap;
  10250. uniform int samples;
  10251. uniform float weights[ n ];
  10252. uniform bool latitudinal;
  10253. uniform float dTheta;
  10254. uniform float mipInt;
  10255. uniform vec3 poleAxis;
  10256. #define ENVMAP_TYPE_CUBE_UV
  10257. #include <cube_uv_reflection_fragment>
  10258. vec3 getSample( float theta, vec3 axis ) {
  10259. float cosTheta = cos( theta );
  10260. // Rodrigues' axis-angle rotation
  10261. vec3 sampleDirection = vOutputDirection * cosTheta
  10262. + cross( axis, vOutputDirection ) * sin( theta )
  10263. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10264. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10265. }
  10266. void main() {
  10267. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10268. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10269. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10270. }
  10271. axis = normalize( axis );
  10272. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10273. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10274. for ( int i = 1; i < n; i++ ) {
  10275. if ( i >= samples ) {
  10276. break;
  10277. }
  10278. float theta = dTheta * float( i );
  10279. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10280. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10281. }
  10282. }
  10283. `,
  10284. blending: NoBlending,
  10285. depthTest: false,
  10286. depthWrite: false
  10287. } );
  10288. return shaderMaterial;
  10289. }
  10290. function _getEquirectMaterial() {
  10291. return new ShaderMaterial( {
  10292. name: 'EquirectangularToCubeUV',
  10293. uniforms: {
  10294. 'envMap': { value: null }
  10295. },
  10296. vertexShader: _getCommonVertexShader(),
  10297. fragmentShader: /* glsl */`
  10298. precision mediump float;
  10299. precision mediump int;
  10300. varying vec3 vOutputDirection;
  10301. uniform sampler2D envMap;
  10302. #include <common>
  10303. void main() {
  10304. vec3 outputDirection = normalize( vOutputDirection );
  10305. vec2 uv = equirectUv( outputDirection );
  10306. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10307. }
  10308. `,
  10309. blending: NoBlending,
  10310. depthTest: false,
  10311. depthWrite: false
  10312. } );
  10313. }
  10314. function _getCubemapMaterial() {
  10315. return new ShaderMaterial( {
  10316. name: 'CubemapToCubeUV',
  10317. uniforms: {
  10318. 'envMap': { value: null },
  10319. 'flipEnvMap': { value: - 1 }
  10320. },
  10321. vertexShader: _getCommonVertexShader(),
  10322. fragmentShader: /* glsl */`
  10323. precision mediump float;
  10324. precision mediump int;
  10325. uniform float flipEnvMap;
  10326. varying vec3 vOutputDirection;
  10327. uniform samplerCube envMap;
  10328. void main() {
  10329. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10330. }
  10331. `,
  10332. blending: NoBlending,
  10333. depthTest: false,
  10334. depthWrite: false
  10335. } );
  10336. }
  10337. function _getCommonVertexShader() {
  10338. return /* glsl */`
  10339. precision mediump float;
  10340. precision mediump int;
  10341. attribute float faceIndex;
  10342. varying vec3 vOutputDirection;
  10343. // RH coordinate system; PMREM face-indexing convention
  10344. vec3 getDirection( vec2 uv, float face ) {
  10345. uv = 2.0 * uv - 1.0;
  10346. vec3 direction = vec3( uv, 1.0 );
  10347. if ( face == 0.0 ) {
  10348. direction = direction.zyx; // ( 1, v, u ) pos x
  10349. } else if ( face == 1.0 ) {
  10350. direction = direction.xzy;
  10351. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10352. } else if ( face == 2.0 ) {
  10353. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10354. } else if ( face == 3.0 ) {
  10355. direction = direction.zyx;
  10356. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10357. } else if ( face == 4.0 ) {
  10358. direction = direction.xzy;
  10359. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10360. } else if ( face == 5.0 ) {
  10361. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10362. }
  10363. return direction;
  10364. }
  10365. void main() {
  10366. vOutputDirection = getDirection( uv, faceIndex );
  10367. gl_Position = vec4( position, 1.0 );
  10368. }
  10369. `;
  10370. }
  10371. function WebGLCubeUVMaps( renderer ) {
  10372. let cubeUVmaps = new WeakMap();
  10373. let pmremGenerator = null;
  10374. function get( texture ) {
  10375. if ( texture && texture.isTexture ) {
  10376. const mapping = texture.mapping;
  10377. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10378. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10379. // equirect/cube map to cubeUV conversion
  10380. if ( isEquirectMap || isCubeMap ) {
  10381. let renderTarget = cubeUVmaps.get( texture );
  10382. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  10383. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  10384. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10385. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10386. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10387. cubeUVmaps.set( texture, renderTarget );
  10388. return renderTarget.texture;
  10389. } else {
  10390. if ( renderTarget !== undefined ) {
  10391. return renderTarget.texture;
  10392. } else {
  10393. const image = texture.image;
  10394. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10395. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10396. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10397. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10398. cubeUVmaps.set( texture, renderTarget );
  10399. texture.addEventListener( 'dispose', onTextureDispose );
  10400. return renderTarget.texture;
  10401. } else {
  10402. // image not yet ready. try the conversion next frame
  10403. return null;
  10404. }
  10405. }
  10406. }
  10407. }
  10408. }
  10409. return texture;
  10410. }
  10411. function isCubeTextureComplete( image ) {
  10412. let count = 0;
  10413. const length = 6;
  10414. for ( let i = 0; i < length; i ++ ) {
  10415. if ( image[ i ] !== undefined ) count ++;
  10416. }
  10417. return count === length;
  10418. }
  10419. function onTextureDispose( event ) {
  10420. const texture = event.target;
  10421. texture.removeEventListener( 'dispose', onTextureDispose );
  10422. const cubemapUV = cubeUVmaps.get( texture );
  10423. if ( cubemapUV !== undefined ) {
  10424. cubeUVmaps.delete( texture );
  10425. cubemapUV.dispose();
  10426. }
  10427. }
  10428. function dispose() {
  10429. cubeUVmaps = new WeakMap();
  10430. if ( pmremGenerator !== null ) {
  10431. pmremGenerator.dispose();
  10432. pmremGenerator = null;
  10433. }
  10434. }
  10435. return {
  10436. get: get,
  10437. dispose: dispose
  10438. };
  10439. }
  10440. function WebGLExtensions( gl ) {
  10441. const extensions = {};
  10442. function getExtension( name ) {
  10443. if ( extensions[ name ] !== undefined ) {
  10444. return extensions[ name ];
  10445. }
  10446. let extension;
  10447. switch ( name ) {
  10448. case 'WEBGL_depth_texture':
  10449. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10450. break;
  10451. case 'EXT_texture_filter_anisotropic':
  10452. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10453. break;
  10454. case 'WEBGL_compressed_texture_s3tc':
  10455. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10456. break;
  10457. case 'WEBGL_compressed_texture_pvrtc':
  10458. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10459. break;
  10460. default:
  10461. extension = gl.getExtension( name );
  10462. }
  10463. extensions[ name ] = extension;
  10464. return extension;
  10465. }
  10466. return {
  10467. has: function ( name ) {
  10468. return getExtension( name ) !== null;
  10469. },
  10470. init: function () {
  10471. getExtension( 'EXT_color_buffer_float' );
  10472. getExtension( 'WEBGL_clip_cull_distance' );
  10473. getExtension( 'OES_texture_float_linear' );
  10474. getExtension( 'EXT_color_buffer_half_float' );
  10475. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10476. getExtension( 'WEBGL_render_shared_exponent' );
  10477. },
  10478. get: function ( name ) {
  10479. const extension = getExtension( name );
  10480. if ( extension === null ) {
  10481. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10482. }
  10483. return extension;
  10484. }
  10485. };
  10486. }
  10487. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10488. const geometries = {};
  10489. const wireframeAttributes = new WeakMap();
  10490. function onGeometryDispose( event ) {
  10491. const geometry = event.target;
  10492. if ( geometry.index !== null ) {
  10493. attributes.remove( geometry.index );
  10494. }
  10495. for ( const name in geometry.attributes ) {
  10496. attributes.remove( geometry.attributes[ name ] );
  10497. }
  10498. for ( const name in geometry.morphAttributes ) {
  10499. const array = geometry.morphAttributes[ name ];
  10500. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10501. attributes.remove( array[ i ] );
  10502. }
  10503. }
  10504. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10505. delete geometries[ geometry.id ];
  10506. const attribute = wireframeAttributes.get( geometry );
  10507. if ( attribute ) {
  10508. attributes.remove( attribute );
  10509. wireframeAttributes.delete( geometry );
  10510. }
  10511. bindingStates.releaseStatesOfGeometry( geometry );
  10512. if ( geometry.isInstancedBufferGeometry === true ) {
  10513. delete geometry._maxInstanceCount;
  10514. }
  10515. //
  10516. info.memory.geometries --;
  10517. }
  10518. function get( object, geometry ) {
  10519. if ( geometries[ geometry.id ] === true ) return geometry;
  10520. geometry.addEventListener( 'dispose', onGeometryDispose );
  10521. geometries[ geometry.id ] = true;
  10522. info.memory.geometries ++;
  10523. return geometry;
  10524. }
  10525. function update( geometry ) {
  10526. const geometryAttributes = geometry.attributes;
  10527. // Updating index buffer in VAO now. See WebGLBindingStates.
  10528. for ( const name in geometryAttributes ) {
  10529. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10530. }
  10531. // morph targets
  10532. const morphAttributes = geometry.morphAttributes;
  10533. for ( const name in morphAttributes ) {
  10534. const array = morphAttributes[ name ];
  10535. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10536. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10537. }
  10538. }
  10539. }
  10540. function updateWireframeAttribute( geometry ) {
  10541. const indices = [];
  10542. const geometryIndex = geometry.index;
  10543. const geometryPosition = geometry.attributes.position;
  10544. let version = 0;
  10545. if ( geometryIndex !== null ) {
  10546. const array = geometryIndex.array;
  10547. version = geometryIndex.version;
  10548. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10549. const a = array[ i + 0 ];
  10550. const b = array[ i + 1 ];
  10551. const c = array[ i + 2 ];
  10552. indices.push( a, b, b, c, c, a );
  10553. }
  10554. } else if ( geometryPosition !== undefined ) {
  10555. const array = geometryPosition.array;
  10556. version = geometryPosition.version;
  10557. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10558. const a = i + 0;
  10559. const b = i + 1;
  10560. const c = i + 2;
  10561. indices.push( a, b, b, c, c, a );
  10562. }
  10563. } else {
  10564. return;
  10565. }
  10566. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10567. attribute.version = version;
  10568. // Updating index buffer in VAO now. See WebGLBindingStates
  10569. //
  10570. const previousAttribute = wireframeAttributes.get( geometry );
  10571. if ( previousAttribute ) attributes.remove( previousAttribute );
  10572. //
  10573. wireframeAttributes.set( geometry, attribute );
  10574. }
  10575. function getWireframeAttribute( geometry ) {
  10576. const currentAttribute = wireframeAttributes.get( geometry );
  10577. if ( currentAttribute ) {
  10578. const geometryIndex = geometry.index;
  10579. if ( geometryIndex !== null ) {
  10580. // if the attribute is obsolete, create a new one
  10581. if ( currentAttribute.version < geometryIndex.version ) {
  10582. updateWireframeAttribute( geometry );
  10583. }
  10584. }
  10585. } else {
  10586. updateWireframeAttribute( geometry );
  10587. }
  10588. return wireframeAttributes.get( geometry );
  10589. }
  10590. return {
  10591. get: get,
  10592. update: update,
  10593. getWireframeAttribute: getWireframeAttribute
  10594. };
  10595. }
  10596. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  10597. let mode;
  10598. function setMode( value ) {
  10599. mode = value;
  10600. }
  10601. let type, bytesPerElement;
  10602. function setIndex( value ) {
  10603. type = value.type;
  10604. bytesPerElement = value.bytesPerElement;
  10605. }
  10606. function render( start, count ) {
  10607. gl.drawElements( mode, count, type, start * bytesPerElement );
  10608. info.update( count, mode, 1 );
  10609. }
  10610. function renderInstances( start, count, primcount ) {
  10611. if ( primcount === 0 ) return;
  10612. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  10613. info.update( count, mode, primcount );
  10614. }
  10615. function renderMultiDraw( starts, counts, drawCount ) {
  10616. if ( drawCount === 0 ) return;
  10617. const extension = extensions.get( 'WEBGL_multi_draw' );
  10618. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10619. let elementCount = 0;
  10620. for ( let i = 0; i < drawCount; i ++ ) {
  10621. elementCount += counts[ i ];
  10622. }
  10623. info.update( elementCount, mode, 1 );
  10624. }
  10625. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  10626. if ( drawCount === 0 ) return;
  10627. const extension = extensions.get( 'WEBGL_multi_draw' );
  10628. if ( extension === null ) {
  10629. for ( let i = 0; i < starts.length; i ++ ) {
  10630. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  10631. }
  10632. } else {
  10633. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  10634. let elementCount = 0;
  10635. for ( let i = 0; i < drawCount; i ++ ) {
  10636. elementCount += counts[ i ];
  10637. }
  10638. for ( let i = 0; i < primcount.length; i ++ ) {
  10639. info.update( elementCount, mode, primcount[ i ] );
  10640. }
  10641. }
  10642. }
  10643. //
  10644. this.setMode = setMode;
  10645. this.setIndex = setIndex;
  10646. this.render = render;
  10647. this.renderInstances = renderInstances;
  10648. this.renderMultiDraw = renderMultiDraw;
  10649. this.renderMultiDrawInstances = renderMultiDrawInstances;
  10650. }
  10651. function WebGLInfo( gl ) {
  10652. const memory = {
  10653. geometries: 0,
  10654. textures: 0
  10655. };
  10656. const render = {
  10657. frame: 0,
  10658. calls: 0,
  10659. triangles: 0,
  10660. points: 0,
  10661. lines: 0
  10662. };
  10663. function update( count, mode, instanceCount ) {
  10664. render.calls ++;
  10665. switch ( mode ) {
  10666. case gl.TRIANGLES:
  10667. render.triangles += instanceCount * ( count / 3 );
  10668. break;
  10669. case gl.LINES:
  10670. render.lines += instanceCount * ( count / 2 );
  10671. break;
  10672. case gl.LINE_STRIP:
  10673. render.lines += instanceCount * ( count - 1 );
  10674. break;
  10675. case gl.LINE_LOOP:
  10676. render.lines += instanceCount * count;
  10677. break;
  10678. case gl.POINTS:
  10679. render.points += instanceCount * count;
  10680. break;
  10681. default:
  10682. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10683. break;
  10684. }
  10685. }
  10686. function reset() {
  10687. render.calls = 0;
  10688. render.triangles = 0;
  10689. render.points = 0;
  10690. render.lines = 0;
  10691. }
  10692. return {
  10693. memory: memory,
  10694. render: render,
  10695. programs: null,
  10696. autoReset: true,
  10697. reset: reset,
  10698. update: update
  10699. };
  10700. }
  10701. function WebGLMorphtargets( gl, capabilities, textures ) {
  10702. const morphTextures = new WeakMap();
  10703. const morph = new Vector4();
  10704. function update( object, geometry, program ) {
  10705. const objectInfluences = object.morphTargetInfluences;
  10706. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  10707. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10708. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10709. let entry = morphTextures.get( geometry );
  10710. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10711. if ( entry !== undefined ) entry.texture.dispose();
  10712. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10713. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10714. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10715. const morphTargets = geometry.morphAttributes.position || [];
  10716. const morphNormals = geometry.morphAttributes.normal || [];
  10717. const morphColors = geometry.morphAttributes.color || [];
  10718. let vertexDataCount = 0;
  10719. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10720. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10721. if ( hasMorphColors === true ) vertexDataCount = 3;
  10722. let width = geometry.attributes.position.count * vertexDataCount;
  10723. let height = 1;
  10724. if ( width > capabilities.maxTextureSize ) {
  10725. height = Math.ceil( width / capabilities.maxTextureSize );
  10726. width = capabilities.maxTextureSize;
  10727. }
  10728. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10729. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10730. texture.type = FloatType;
  10731. texture.needsUpdate = true;
  10732. // fill buffer
  10733. const vertexDataStride = vertexDataCount * 4;
  10734. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10735. const morphTarget = morphTargets[ i ];
  10736. const morphNormal = morphNormals[ i ];
  10737. const morphColor = morphColors[ i ];
  10738. const offset = width * height * 4 * i;
  10739. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10740. const stride = j * vertexDataStride;
  10741. if ( hasMorphPosition === true ) {
  10742. morph.fromBufferAttribute( morphTarget, j );
  10743. buffer[ offset + stride + 0 ] = morph.x;
  10744. buffer[ offset + stride + 1 ] = morph.y;
  10745. buffer[ offset + stride + 2 ] = morph.z;
  10746. buffer[ offset + stride + 3 ] = 0;
  10747. }
  10748. if ( hasMorphNormals === true ) {
  10749. morph.fromBufferAttribute( morphNormal, j );
  10750. buffer[ offset + stride + 4 ] = morph.x;
  10751. buffer[ offset + stride + 5 ] = morph.y;
  10752. buffer[ offset + stride + 6 ] = morph.z;
  10753. buffer[ offset + stride + 7 ] = 0;
  10754. }
  10755. if ( hasMorphColors === true ) {
  10756. morph.fromBufferAttribute( morphColor, j );
  10757. buffer[ offset + stride + 8 ] = morph.x;
  10758. buffer[ offset + stride + 9 ] = morph.y;
  10759. buffer[ offset + stride + 10 ] = morph.z;
  10760. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10761. }
  10762. }
  10763. }
  10764. entry = {
  10765. count: morphTargetsCount,
  10766. texture: texture,
  10767. size: new Vector2( width, height )
  10768. };
  10769. morphTextures.set( geometry, entry );
  10770. function disposeTexture() {
  10771. texture.dispose();
  10772. morphTextures.delete( geometry );
  10773. geometry.removeEventListener( 'dispose', disposeTexture );
  10774. }
  10775. geometry.addEventListener( 'dispose', disposeTexture );
  10776. }
  10777. //
  10778. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  10779. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  10780. } else {
  10781. let morphInfluencesSum = 0;
  10782. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10783. morphInfluencesSum += objectInfluences[ i ];
  10784. }
  10785. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10786. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10787. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10788. }
  10789. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10790. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10791. }
  10792. return {
  10793. update: update
  10794. };
  10795. }
  10796. function WebGLObjects( gl, geometries, attributes, info ) {
  10797. let updateMap = new WeakMap();
  10798. function update( object ) {
  10799. const frame = info.render.frame;
  10800. const geometry = object.geometry;
  10801. const buffergeometry = geometries.get( object, geometry );
  10802. // Update once per frame
  10803. if ( updateMap.get( buffergeometry ) !== frame ) {
  10804. geometries.update( buffergeometry );
  10805. updateMap.set( buffergeometry, frame );
  10806. }
  10807. if ( object.isInstancedMesh ) {
  10808. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10809. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10810. }
  10811. if ( updateMap.get( object ) !== frame ) {
  10812. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10813. if ( object.instanceColor !== null ) {
  10814. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10815. }
  10816. updateMap.set( object, frame );
  10817. }
  10818. }
  10819. if ( object.isSkinnedMesh ) {
  10820. const skeleton = object.skeleton;
  10821. if ( updateMap.get( skeleton ) !== frame ) {
  10822. skeleton.update();
  10823. updateMap.set( skeleton, frame );
  10824. }
  10825. }
  10826. return buffergeometry;
  10827. }
  10828. function dispose() {
  10829. updateMap = new WeakMap();
  10830. }
  10831. function onInstancedMeshDispose( event ) {
  10832. const instancedMesh = event.target;
  10833. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10834. attributes.remove( instancedMesh.instanceMatrix );
  10835. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10836. }
  10837. return {
  10838. update: update,
  10839. dispose: dispose
  10840. };
  10841. }
  10842. class DepthTexture extends Texture {
  10843. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10844. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10845. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10846. }
  10847. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10848. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10849. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10850. this.isDepthTexture = true;
  10851. this.image = { width: width, height: height };
  10852. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10853. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10854. this.flipY = false;
  10855. this.generateMipmaps = false;
  10856. this.compareFunction = null;
  10857. }
  10858. copy( source ) {
  10859. super.copy( source );
  10860. this.compareFunction = source.compareFunction;
  10861. return this;
  10862. }
  10863. toJSON( meta ) {
  10864. const data = super.toJSON( meta );
  10865. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10866. return data;
  10867. }
  10868. }
  10869. /**
  10870. * Uniforms of a program.
  10871. * Those form a tree structure with a special top-level container for the root,
  10872. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10873. *
  10874. *
  10875. * Properties of inner nodes including the top-level container:
  10876. *
  10877. * .seq - array of nested uniforms
  10878. * .map - nested uniforms by name
  10879. *
  10880. *
  10881. * Methods of all nodes except the top-level container:
  10882. *
  10883. * .setValue( gl, value, [textures] )
  10884. *
  10885. * uploads a uniform value(s)
  10886. * the 'textures' parameter is needed for sampler uniforms
  10887. *
  10888. *
  10889. * Static methods of the top-level container (textures factorizations):
  10890. *
  10891. * .upload( gl, seq, values, textures )
  10892. *
  10893. * sets uniforms in 'seq' to 'values[id].value'
  10894. *
  10895. * .seqWithValue( seq, values ) : filteredSeq
  10896. *
  10897. * filters 'seq' entries with corresponding entry in values
  10898. *
  10899. *
  10900. * Methods of the top-level container (textures factorizations):
  10901. *
  10902. * .setValue( gl, name, value, textures )
  10903. *
  10904. * sets uniform with name 'name' to 'value'
  10905. *
  10906. * .setOptional( gl, obj, prop )
  10907. *
  10908. * like .set for an optional property of the object
  10909. *
  10910. */
  10911. const emptyTexture = /*@__PURE__*/ new Texture();
  10912. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10913. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10914. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10915. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10916. // --- Utilities ---
  10917. // Array Caches (provide typed arrays for temporary by size)
  10918. const arrayCacheF32 = [];
  10919. const arrayCacheI32 = [];
  10920. // Float32Array caches used for uploading Matrix uniforms
  10921. const mat4array = new Float32Array( 16 );
  10922. const mat3array = new Float32Array( 9 );
  10923. const mat2array = new Float32Array( 4 );
  10924. // Flattening for arrays of vectors and matrices
  10925. function flatten( array, nBlocks, blockSize ) {
  10926. const firstElem = array[ 0 ];
  10927. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10928. // unoptimized: ! isNaN( firstElem )
  10929. // see http://jacksondunstan.com/articles/983
  10930. const n = nBlocks * blockSize;
  10931. let r = arrayCacheF32[ n ];
  10932. if ( r === undefined ) {
  10933. r = new Float32Array( n );
  10934. arrayCacheF32[ n ] = r;
  10935. }
  10936. if ( nBlocks !== 0 ) {
  10937. firstElem.toArray( r, 0 );
  10938. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10939. offset += blockSize;
  10940. array[ i ].toArray( r, offset );
  10941. }
  10942. }
  10943. return r;
  10944. }
  10945. function arraysEqual( a, b ) {
  10946. if ( a.length !== b.length ) return false;
  10947. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10948. if ( a[ i ] !== b[ i ] ) return false;
  10949. }
  10950. return true;
  10951. }
  10952. function copyArray( a, b ) {
  10953. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10954. a[ i ] = b[ i ];
  10955. }
  10956. }
  10957. // Texture unit allocation
  10958. function allocTexUnits( textures, n ) {
  10959. let r = arrayCacheI32[ n ];
  10960. if ( r === undefined ) {
  10961. r = new Int32Array( n );
  10962. arrayCacheI32[ n ] = r;
  10963. }
  10964. for ( let i = 0; i !== n; ++ i ) {
  10965. r[ i ] = textures.allocateTextureUnit();
  10966. }
  10967. return r;
  10968. }
  10969. // --- Setters ---
  10970. // Note: Defining these methods externally, because they come in a bunch
  10971. // and this way their names minify.
  10972. // Single scalar
  10973. function setValueV1f( gl, v ) {
  10974. const cache = this.cache;
  10975. if ( cache[ 0 ] === v ) return;
  10976. gl.uniform1f( this.addr, v );
  10977. cache[ 0 ] = v;
  10978. }
  10979. // Single float vector (from flat array or THREE.VectorN)
  10980. function setValueV2f( gl, v ) {
  10981. const cache = this.cache;
  10982. if ( v.x !== undefined ) {
  10983. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10984. gl.uniform2f( this.addr, v.x, v.y );
  10985. cache[ 0 ] = v.x;
  10986. cache[ 1 ] = v.y;
  10987. }
  10988. } else {
  10989. if ( arraysEqual( cache, v ) ) return;
  10990. gl.uniform2fv( this.addr, v );
  10991. copyArray( cache, v );
  10992. }
  10993. }
  10994. function setValueV3f( gl, v ) {
  10995. const cache = this.cache;
  10996. if ( v.x !== undefined ) {
  10997. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10998. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10999. cache[ 0 ] = v.x;
  11000. cache[ 1 ] = v.y;
  11001. cache[ 2 ] = v.z;
  11002. }
  11003. } else if ( v.r !== undefined ) {
  11004. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  11005. gl.uniform3f( this.addr, v.r, v.g, v.b );
  11006. cache[ 0 ] = v.r;
  11007. cache[ 1 ] = v.g;
  11008. cache[ 2 ] = v.b;
  11009. }
  11010. } else {
  11011. if ( arraysEqual( cache, v ) ) return;
  11012. gl.uniform3fv( this.addr, v );
  11013. copyArray( cache, v );
  11014. }
  11015. }
  11016. function setValueV4f( gl, v ) {
  11017. const cache = this.cache;
  11018. if ( v.x !== undefined ) {
  11019. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11020. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11021. cache[ 0 ] = v.x;
  11022. cache[ 1 ] = v.y;
  11023. cache[ 2 ] = v.z;
  11024. cache[ 3 ] = v.w;
  11025. }
  11026. } else {
  11027. if ( arraysEqual( cache, v ) ) return;
  11028. gl.uniform4fv( this.addr, v );
  11029. copyArray( cache, v );
  11030. }
  11031. }
  11032. // Single matrix (from flat array or THREE.MatrixN)
  11033. function setValueM2( gl, v ) {
  11034. const cache = this.cache;
  11035. const elements = v.elements;
  11036. if ( elements === undefined ) {
  11037. if ( arraysEqual( cache, v ) ) return;
  11038. gl.uniformMatrix2fv( this.addr, false, v );
  11039. copyArray( cache, v );
  11040. } else {
  11041. if ( arraysEqual( cache, elements ) ) return;
  11042. mat2array.set( elements );
  11043. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11044. copyArray( cache, elements );
  11045. }
  11046. }
  11047. function setValueM3( gl, v ) {
  11048. const cache = this.cache;
  11049. const elements = v.elements;
  11050. if ( elements === undefined ) {
  11051. if ( arraysEqual( cache, v ) ) return;
  11052. gl.uniformMatrix3fv( this.addr, false, v );
  11053. copyArray( cache, v );
  11054. } else {
  11055. if ( arraysEqual( cache, elements ) ) return;
  11056. mat3array.set( elements );
  11057. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11058. copyArray( cache, elements );
  11059. }
  11060. }
  11061. function setValueM4( gl, v ) {
  11062. const cache = this.cache;
  11063. const elements = v.elements;
  11064. if ( elements === undefined ) {
  11065. if ( arraysEqual( cache, v ) ) return;
  11066. gl.uniformMatrix4fv( this.addr, false, v );
  11067. copyArray( cache, v );
  11068. } else {
  11069. if ( arraysEqual( cache, elements ) ) return;
  11070. mat4array.set( elements );
  11071. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11072. copyArray( cache, elements );
  11073. }
  11074. }
  11075. // Single integer / boolean
  11076. function setValueV1i( gl, v ) {
  11077. const cache = this.cache;
  11078. if ( cache[ 0 ] === v ) return;
  11079. gl.uniform1i( this.addr, v );
  11080. cache[ 0 ] = v;
  11081. }
  11082. // Single integer / boolean vector (from flat array or THREE.VectorN)
  11083. function setValueV2i( gl, v ) {
  11084. const cache = this.cache;
  11085. if ( v.x !== undefined ) {
  11086. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11087. gl.uniform2i( this.addr, v.x, v.y );
  11088. cache[ 0 ] = v.x;
  11089. cache[ 1 ] = v.y;
  11090. }
  11091. } else {
  11092. if ( arraysEqual( cache, v ) ) return;
  11093. gl.uniform2iv( this.addr, v );
  11094. copyArray( cache, v );
  11095. }
  11096. }
  11097. function setValueV3i( gl, v ) {
  11098. const cache = this.cache;
  11099. if ( v.x !== undefined ) {
  11100. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11101. gl.uniform3i( this.addr, v.x, v.y, v.z );
  11102. cache[ 0 ] = v.x;
  11103. cache[ 1 ] = v.y;
  11104. cache[ 2 ] = v.z;
  11105. }
  11106. } else {
  11107. if ( arraysEqual( cache, v ) ) return;
  11108. gl.uniform3iv( this.addr, v );
  11109. copyArray( cache, v );
  11110. }
  11111. }
  11112. function setValueV4i( gl, v ) {
  11113. const cache = this.cache;
  11114. if ( v.x !== undefined ) {
  11115. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11116. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11117. cache[ 0 ] = v.x;
  11118. cache[ 1 ] = v.y;
  11119. cache[ 2 ] = v.z;
  11120. cache[ 3 ] = v.w;
  11121. }
  11122. } else {
  11123. if ( arraysEqual( cache, v ) ) return;
  11124. gl.uniform4iv( this.addr, v );
  11125. copyArray( cache, v );
  11126. }
  11127. }
  11128. // Single unsigned integer
  11129. function setValueV1ui( gl, v ) {
  11130. const cache = this.cache;
  11131. if ( cache[ 0 ] === v ) return;
  11132. gl.uniform1ui( this.addr, v );
  11133. cache[ 0 ] = v;
  11134. }
  11135. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11136. function setValueV2ui( gl, v ) {
  11137. const cache = this.cache;
  11138. if ( v.x !== undefined ) {
  11139. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11140. gl.uniform2ui( this.addr, v.x, v.y );
  11141. cache[ 0 ] = v.x;
  11142. cache[ 1 ] = v.y;
  11143. }
  11144. } else {
  11145. if ( arraysEqual( cache, v ) ) return;
  11146. gl.uniform2uiv( this.addr, v );
  11147. copyArray( cache, v );
  11148. }
  11149. }
  11150. function setValueV3ui( gl, v ) {
  11151. const cache = this.cache;
  11152. if ( v.x !== undefined ) {
  11153. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11154. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11155. cache[ 0 ] = v.x;
  11156. cache[ 1 ] = v.y;
  11157. cache[ 2 ] = v.z;
  11158. }
  11159. } else {
  11160. if ( arraysEqual( cache, v ) ) return;
  11161. gl.uniform3uiv( this.addr, v );
  11162. copyArray( cache, v );
  11163. }
  11164. }
  11165. function setValueV4ui( gl, v ) {
  11166. const cache = this.cache;
  11167. if ( v.x !== undefined ) {
  11168. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11169. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11170. cache[ 0 ] = v.x;
  11171. cache[ 1 ] = v.y;
  11172. cache[ 2 ] = v.z;
  11173. cache[ 3 ] = v.w;
  11174. }
  11175. } else {
  11176. if ( arraysEqual( cache, v ) ) return;
  11177. gl.uniform4uiv( this.addr, v );
  11178. copyArray( cache, v );
  11179. }
  11180. }
  11181. // Single texture (2D / Cube)
  11182. function setValueT1( gl, v, textures ) {
  11183. const cache = this.cache;
  11184. const unit = textures.allocateTextureUnit();
  11185. if ( cache[ 0 ] !== unit ) {
  11186. gl.uniform1i( this.addr, unit );
  11187. cache[ 0 ] = unit;
  11188. }
  11189. let emptyTexture2D;
  11190. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  11191. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  11192. emptyTexture2D = emptyShadowTexture;
  11193. } else {
  11194. emptyTexture2D = emptyTexture;
  11195. }
  11196. textures.setTexture2D( v || emptyTexture2D, unit );
  11197. }
  11198. function setValueT3D1( gl, v, textures ) {
  11199. const cache = this.cache;
  11200. const unit = textures.allocateTextureUnit();
  11201. if ( cache[ 0 ] !== unit ) {
  11202. gl.uniform1i( this.addr, unit );
  11203. cache[ 0 ] = unit;
  11204. }
  11205. textures.setTexture3D( v || empty3dTexture, unit );
  11206. }
  11207. function setValueT6( gl, v, textures ) {
  11208. const cache = this.cache;
  11209. const unit = textures.allocateTextureUnit();
  11210. if ( cache[ 0 ] !== unit ) {
  11211. gl.uniform1i( this.addr, unit );
  11212. cache[ 0 ] = unit;
  11213. }
  11214. textures.setTextureCube( v || emptyCubeTexture, unit );
  11215. }
  11216. function setValueT2DArray1( gl, v, textures ) {
  11217. const cache = this.cache;
  11218. const unit = textures.allocateTextureUnit();
  11219. if ( cache[ 0 ] !== unit ) {
  11220. gl.uniform1i( this.addr, unit );
  11221. cache[ 0 ] = unit;
  11222. }
  11223. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11224. }
  11225. // Helper to pick the right setter for the singular case
  11226. function getSingularSetter( type ) {
  11227. switch ( type ) {
  11228. case 0x1406: return setValueV1f; // FLOAT
  11229. case 0x8b50: return setValueV2f; // _VEC2
  11230. case 0x8b51: return setValueV3f; // _VEC3
  11231. case 0x8b52: return setValueV4f; // _VEC4
  11232. case 0x8b5a: return setValueM2; // _MAT2
  11233. case 0x8b5b: return setValueM3; // _MAT3
  11234. case 0x8b5c: return setValueM4; // _MAT4
  11235. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11236. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11237. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11238. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11239. case 0x1405: return setValueV1ui; // UINT
  11240. case 0x8dc6: return setValueV2ui; // _VEC2
  11241. case 0x8dc7: return setValueV3ui; // _VEC3
  11242. case 0x8dc8: return setValueV4ui; // _VEC4
  11243. case 0x8b5e: // SAMPLER_2D
  11244. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11245. case 0x8dca: // INT_SAMPLER_2D
  11246. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11247. case 0x8b62: // SAMPLER_2D_SHADOW
  11248. return setValueT1;
  11249. case 0x8b5f: // SAMPLER_3D
  11250. case 0x8dcb: // INT_SAMPLER_3D
  11251. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11252. return setValueT3D1;
  11253. case 0x8b60: // SAMPLER_CUBE
  11254. case 0x8dcc: // INT_SAMPLER_CUBE
  11255. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11256. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11257. return setValueT6;
  11258. case 0x8dc1: // SAMPLER_2D_ARRAY
  11259. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11260. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11261. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11262. return setValueT2DArray1;
  11263. }
  11264. }
  11265. // Array of scalars
  11266. function setValueV1fArray( gl, v ) {
  11267. gl.uniform1fv( this.addr, v );
  11268. }
  11269. // Array of vectors (from flat array or array of THREE.VectorN)
  11270. function setValueV2fArray( gl, v ) {
  11271. const data = flatten( v, this.size, 2 );
  11272. gl.uniform2fv( this.addr, data );
  11273. }
  11274. function setValueV3fArray( gl, v ) {
  11275. const data = flatten( v, this.size, 3 );
  11276. gl.uniform3fv( this.addr, data );
  11277. }
  11278. function setValueV4fArray( gl, v ) {
  11279. const data = flatten( v, this.size, 4 );
  11280. gl.uniform4fv( this.addr, data );
  11281. }
  11282. // Array of matrices (from flat array or array of THREE.MatrixN)
  11283. function setValueM2Array( gl, v ) {
  11284. const data = flatten( v, this.size, 4 );
  11285. gl.uniformMatrix2fv( this.addr, false, data );
  11286. }
  11287. function setValueM3Array( gl, v ) {
  11288. const data = flatten( v, this.size, 9 );
  11289. gl.uniformMatrix3fv( this.addr, false, data );
  11290. }
  11291. function setValueM4Array( gl, v ) {
  11292. const data = flatten( v, this.size, 16 );
  11293. gl.uniformMatrix4fv( this.addr, false, data );
  11294. }
  11295. // Array of integer / boolean
  11296. function setValueV1iArray( gl, v ) {
  11297. gl.uniform1iv( this.addr, v );
  11298. }
  11299. // Array of integer / boolean vectors (from flat array)
  11300. function setValueV2iArray( gl, v ) {
  11301. gl.uniform2iv( this.addr, v );
  11302. }
  11303. function setValueV3iArray( gl, v ) {
  11304. gl.uniform3iv( this.addr, v );
  11305. }
  11306. function setValueV4iArray( gl, v ) {
  11307. gl.uniform4iv( this.addr, v );
  11308. }
  11309. // Array of unsigned integer
  11310. function setValueV1uiArray( gl, v ) {
  11311. gl.uniform1uiv( this.addr, v );
  11312. }
  11313. // Array of unsigned integer vectors (from flat array)
  11314. function setValueV2uiArray( gl, v ) {
  11315. gl.uniform2uiv( this.addr, v );
  11316. }
  11317. function setValueV3uiArray( gl, v ) {
  11318. gl.uniform3uiv( this.addr, v );
  11319. }
  11320. function setValueV4uiArray( gl, v ) {
  11321. gl.uniform4uiv( this.addr, v );
  11322. }
  11323. // Array of textures (2D / 3D / Cube / 2DArray)
  11324. function setValueT1Array( gl, v, textures ) {
  11325. const cache = this.cache;
  11326. const n = v.length;
  11327. const units = allocTexUnits( textures, n );
  11328. if ( ! arraysEqual( cache, units ) ) {
  11329. gl.uniform1iv( this.addr, units );
  11330. copyArray( cache, units );
  11331. }
  11332. for ( let i = 0; i !== n; ++ i ) {
  11333. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11334. }
  11335. }
  11336. function setValueT3DArray( gl, v, textures ) {
  11337. const cache = this.cache;
  11338. const n = v.length;
  11339. const units = allocTexUnits( textures, n );
  11340. if ( ! arraysEqual( cache, units ) ) {
  11341. gl.uniform1iv( this.addr, units );
  11342. copyArray( cache, units );
  11343. }
  11344. for ( let i = 0; i !== n; ++ i ) {
  11345. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11346. }
  11347. }
  11348. function setValueT6Array( gl, v, textures ) {
  11349. const cache = this.cache;
  11350. const n = v.length;
  11351. const units = allocTexUnits( textures, n );
  11352. if ( ! arraysEqual( cache, units ) ) {
  11353. gl.uniform1iv( this.addr, units );
  11354. copyArray( cache, units );
  11355. }
  11356. for ( let i = 0; i !== n; ++ i ) {
  11357. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11358. }
  11359. }
  11360. function setValueT2DArrayArray( gl, v, textures ) {
  11361. const cache = this.cache;
  11362. const n = v.length;
  11363. const units = allocTexUnits( textures, n );
  11364. if ( ! arraysEqual( cache, units ) ) {
  11365. gl.uniform1iv( this.addr, units );
  11366. copyArray( cache, units );
  11367. }
  11368. for ( let i = 0; i !== n; ++ i ) {
  11369. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11370. }
  11371. }
  11372. // Helper to pick the right setter for a pure (bottom-level) array
  11373. function getPureArraySetter( type ) {
  11374. switch ( type ) {
  11375. case 0x1406: return setValueV1fArray; // FLOAT
  11376. case 0x8b50: return setValueV2fArray; // _VEC2
  11377. case 0x8b51: return setValueV3fArray; // _VEC3
  11378. case 0x8b52: return setValueV4fArray; // _VEC4
  11379. case 0x8b5a: return setValueM2Array; // _MAT2
  11380. case 0x8b5b: return setValueM3Array; // _MAT3
  11381. case 0x8b5c: return setValueM4Array; // _MAT4
  11382. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11383. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11384. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11385. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11386. case 0x1405: return setValueV1uiArray; // UINT
  11387. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11388. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11389. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11390. case 0x8b5e: // SAMPLER_2D
  11391. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11392. case 0x8dca: // INT_SAMPLER_2D
  11393. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11394. case 0x8b62: // SAMPLER_2D_SHADOW
  11395. return setValueT1Array;
  11396. case 0x8b5f: // SAMPLER_3D
  11397. case 0x8dcb: // INT_SAMPLER_3D
  11398. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11399. return setValueT3DArray;
  11400. case 0x8b60: // SAMPLER_CUBE
  11401. case 0x8dcc: // INT_SAMPLER_CUBE
  11402. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11403. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11404. return setValueT6Array;
  11405. case 0x8dc1: // SAMPLER_2D_ARRAY
  11406. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11407. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11408. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11409. return setValueT2DArrayArray;
  11410. }
  11411. }
  11412. // --- Uniform Classes ---
  11413. class SingleUniform {
  11414. constructor( id, activeInfo, addr ) {
  11415. this.id = id;
  11416. this.addr = addr;
  11417. this.cache = [];
  11418. this.type = activeInfo.type;
  11419. this.setValue = getSingularSetter( activeInfo.type );
  11420. // this.path = activeInfo.name; // DEBUG
  11421. }
  11422. }
  11423. class PureArrayUniform {
  11424. constructor( id, activeInfo, addr ) {
  11425. this.id = id;
  11426. this.addr = addr;
  11427. this.cache = [];
  11428. this.type = activeInfo.type;
  11429. this.size = activeInfo.size;
  11430. this.setValue = getPureArraySetter( activeInfo.type );
  11431. // this.path = activeInfo.name; // DEBUG
  11432. }
  11433. }
  11434. class StructuredUniform {
  11435. constructor( id ) {
  11436. this.id = id;
  11437. this.seq = [];
  11438. this.map = {};
  11439. }
  11440. setValue( gl, value, textures ) {
  11441. const seq = this.seq;
  11442. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11443. const u = seq[ i ];
  11444. u.setValue( gl, value[ u.id ], textures );
  11445. }
  11446. }
  11447. }
  11448. // --- Top-level ---
  11449. // Parser - builds up the property tree from the path strings
  11450. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11451. // extracts
  11452. // - the identifier (member name or array index)
  11453. // - followed by an optional right bracket (found when array index)
  11454. // - followed by an optional left bracket or dot (type of subscript)
  11455. //
  11456. // Note: These portions can be read in a non-overlapping fashion and
  11457. // allow straightforward parsing of the hierarchy that WebGL encodes
  11458. // in the uniform names.
  11459. function addUniform( container, uniformObject ) {
  11460. container.seq.push( uniformObject );
  11461. container.map[ uniformObject.id ] = uniformObject;
  11462. }
  11463. function parseUniform( activeInfo, addr, container ) {
  11464. const path = activeInfo.name,
  11465. pathLength = path.length;
  11466. // reset RegExp object, because of the early exit of a previous run
  11467. RePathPart.lastIndex = 0;
  11468. while ( true ) {
  11469. const match = RePathPart.exec( path ),
  11470. matchEnd = RePathPart.lastIndex;
  11471. let id = match[ 1 ];
  11472. const idIsIndex = match[ 2 ] === ']',
  11473. subscript = match[ 3 ];
  11474. if ( idIsIndex ) id = id | 0; // convert to integer
  11475. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11476. // bare name or "pure" bottom-level array "[0]" suffix
  11477. addUniform( container, subscript === undefined ?
  11478. new SingleUniform( id, activeInfo, addr ) :
  11479. new PureArrayUniform( id, activeInfo, addr ) );
  11480. break;
  11481. } else {
  11482. // step into inner node / create it in case it doesn't exist
  11483. const map = container.map;
  11484. let next = map[ id ];
  11485. if ( next === undefined ) {
  11486. next = new StructuredUniform( id );
  11487. addUniform( container, next );
  11488. }
  11489. container = next;
  11490. }
  11491. }
  11492. }
  11493. // Root Container
  11494. class WebGLUniforms {
  11495. constructor( gl, program ) {
  11496. this.seq = [];
  11497. this.map = {};
  11498. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11499. for ( let i = 0; i < n; ++ i ) {
  11500. const info = gl.getActiveUniform( program, i ),
  11501. addr = gl.getUniformLocation( program, info.name );
  11502. parseUniform( info, addr, this );
  11503. }
  11504. }
  11505. setValue( gl, name, value, textures ) {
  11506. const u = this.map[ name ];
  11507. if ( u !== undefined ) u.setValue( gl, value, textures );
  11508. }
  11509. setOptional( gl, object, name ) {
  11510. const v = object[ name ];
  11511. if ( v !== undefined ) this.setValue( gl, name, v );
  11512. }
  11513. static upload( gl, seq, values, textures ) {
  11514. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11515. const u = seq[ i ],
  11516. v = values[ u.id ];
  11517. if ( v.needsUpdate !== false ) {
  11518. // note: always updating when .needsUpdate is undefined
  11519. u.setValue( gl, v.value, textures );
  11520. }
  11521. }
  11522. }
  11523. static seqWithValue( seq, values ) {
  11524. const r = [];
  11525. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11526. const u = seq[ i ];
  11527. if ( u.id in values ) r.push( u );
  11528. }
  11529. return r;
  11530. }
  11531. }
  11532. function WebGLShader( gl, type, string ) {
  11533. const shader = gl.createShader( type );
  11534. gl.shaderSource( shader, string );
  11535. gl.compileShader( shader );
  11536. return shader;
  11537. }
  11538. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11539. const COMPLETION_STATUS_KHR = 0x91B1;
  11540. let programIdCount = 0;
  11541. function handleSource( string, errorLine ) {
  11542. const lines = string.split( '\n' );
  11543. const lines2 = [];
  11544. const from = Math.max( errorLine - 6, 0 );
  11545. const to = Math.min( errorLine + 6, lines.length );
  11546. for ( let i = from; i < to; i ++ ) {
  11547. const line = i + 1;
  11548. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11549. }
  11550. return lines2.join( '\n' );
  11551. }
  11552. function getEncodingComponents( colorSpace ) {
  11553. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11554. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11555. let gamutMapping;
  11556. if ( workingPrimaries === encodingPrimaries ) {
  11557. gamutMapping = '';
  11558. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11559. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11560. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11561. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11562. }
  11563. switch ( colorSpace ) {
  11564. case LinearSRGBColorSpace:
  11565. case LinearDisplayP3ColorSpace:
  11566. return [ gamutMapping, 'LinearTransferOETF' ];
  11567. case SRGBColorSpace:
  11568. case DisplayP3ColorSpace:
  11569. return [ gamutMapping, 'sRGBTransferOETF' ];
  11570. default:
  11571. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11572. return [ gamutMapping, 'LinearTransferOETF' ];
  11573. }
  11574. }
  11575. function getShaderErrors( gl, shader, type ) {
  11576. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11577. const errors = gl.getShaderInfoLog( shader ).trim();
  11578. if ( status && errors === '' ) return '';
  11579. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11580. if ( errorMatches ) {
  11581. // --enable-privileged-webgl-extension
  11582. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11583. const errorLine = parseInt( errorMatches[ 1 ] );
  11584. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11585. } else {
  11586. return errors;
  11587. }
  11588. }
  11589. function getTexelEncodingFunction( functionName, colorSpace ) {
  11590. const components = getEncodingComponents( colorSpace );
  11591. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11592. }
  11593. function getToneMappingFunction( functionName, toneMapping ) {
  11594. let toneMappingName;
  11595. switch ( toneMapping ) {
  11596. case LinearToneMapping:
  11597. toneMappingName = 'Linear';
  11598. break;
  11599. case ReinhardToneMapping:
  11600. toneMappingName = 'Reinhard';
  11601. break;
  11602. case CineonToneMapping:
  11603. toneMappingName = 'OptimizedCineon';
  11604. break;
  11605. case ACESFilmicToneMapping:
  11606. toneMappingName = 'ACESFilmic';
  11607. break;
  11608. case AgXToneMapping:
  11609. toneMappingName = 'AgX';
  11610. break;
  11611. case NeutralToneMapping:
  11612. toneMappingName = 'Neutral';
  11613. break;
  11614. case CustomToneMapping:
  11615. toneMappingName = 'Custom';
  11616. break;
  11617. default:
  11618. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11619. toneMappingName = 'Linear';
  11620. }
  11621. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11622. }
  11623. const _v0$1 = /*@__PURE__*/ new Vector3();
  11624. function getLuminanceFunction() {
  11625. ColorManagement.getLuminanceCoefficients( _v0$1 );
  11626. const r = _v0$1.x.toFixed( 4 );
  11627. const g = _v0$1.y.toFixed( 4 );
  11628. const b = _v0$1.z.toFixed( 4 );
  11629. return [
  11630. 'float luminance( const in vec3 rgb ) {',
  11631. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  11632. ' return dot( weights, rgb );',
  11633. '}'
  11634. ].join( '\n' );
  11635. }
  11636. function generateVertexExtensions( parameters ) {
  11637. const chunks = [
  11638. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  11639. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  11640. ];
  11641. return chunks.filter( filterEmptyLine ).join( '\n' );
  11642. }
  11643. function generateDefines( defines ) {
  11644. const chunks = [];
  11645. for ( const name in defines ) {
  11646. const value = defines[ name ];
  11647. if ( value === false ) continue;
  11648. chunks.push( '#define ' + name + ' ' + value );
  11649. }
  11650. return chunks.join( '\n' );
  11651. }
  11652. function fetchAttributeLocations( gl, program ) {
  11653. const attributes = {};
  11654. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11655. for ( let i = 0; i < n; i ++ ) {
  11656. const info = gl.getActiveAttrib( program, i );
  11657. const name = info.name;
  11658. let locationSize = 1;
  11659. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11660. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11661. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11662. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11663. attributes[ name ] = {
  11664. type: info.type,
  11665. location: gl.getAttribLocation( program, name ),
  11666. locationSize: locationSize
  11667. };
  11668. }
  11669. return attributes;
  11670. }
  11671. function filterEmptyLine( string ) {
  11672. return string !== '';
  11673. }
  11674. function replaceLightNums( string, parameters ) {
  11675. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11676. return string
  11677. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11678. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11679. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11680. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11681. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11682. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11683. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11684. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11685. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11686. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11687. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11688. }
  11689. function replaceClippingPlaneNums( string, parameters ) {
  11690. return string
  11691. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11692. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11693. }
  11694. // Resolve Includes
  11695. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11696. function resolveIncludes( string ) {
  11697. return string.replace( includePattern, includeReplacer );
  11698. }
  11699. const shaderChunkMap = new Map();
  11700. function includeReplacer( match, include ) {
  11701. let string = ShaderChunk[ include ];
  11702. if ( string === undefined ) {
  11703. const newInclude = shaderChunkMap.get( include );
  11704. if ( newInclude !== undefined ) {
  11705. string = ShaderChunk[ newInclude ];
  11706. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11707. } else {
  11708. throw new Error( 'Can not resolve #include <' + include + '>' );
  11709. }
  11710. }
  11711. return resolveIncludes( string );
  11712. }
  11713. // Unroll Loops
  11714. 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;
  11715. function unrollLoops( string ) {
  11716. return string.replace( unrollLoopPattern, loopReplacer );
  11717. }
  11718. function loopReplacer( match, start, end, snippet ) {
  11719. let string = '';
  11720. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11721. string += snippet
  11722. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11723. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11724. }
  11725. return string;
  11726. }
  11727. //
  11728. function generatePrecision( parameters ) {
  11729. let precisionstring = `precision ${parameters.precision} float;
  11730. precision ${parameters.precision} int;
  11731. precision ${parameters.precision} sampler2D;
  11732. precision ${parameters.precision} samplerCube;
  11733. precision ${parameters.precision} sampler3D;
  11734. precision ${parameters.precision} sampler2DArray;
  11735. precision ${parameters.precision} sampler2DShadow;
  11736. precision ${parameters.precision} samplerCubeShadow;
  11737. precision ${parameters.precision} sampler2DArrayShadow;
  11738. precision ${parameters.precision} isampler2D;
  11739. precision ${parameters.precision} isampler3D;
  11740. precision ${parameters.precision} isamplerCube;
  11741. precision ${parameters.precision} isampler2DArray;
  11742. precision ${parameters.precision} usampler2D;
  11743. precision ${parameters.precision} usampler3D;
  11744. precision ${parameters.precision} usamplerCube;
  11745. precision ${parameters.precision} usampler2DArray;
  11746. `;
  11747. if ( parameters.precision === 'highp' ) {
  11748. precisionstring += '\n#define HIGH_PRECISION';
  11749. } else if ( parameters.precision === 'mediump' ) {
  11750. precisionstring += '\n#define MEDIUM_PRECISION';
  11751. } else if ( parameters.precision === 'lowp' ) {
  11752. precisionstring += '\n#define LOW_PRECISION';
  11753. }
  11754. return precisionstring;
  11755. }
  11756. function generateShadowMapTypeDefine( parameters ) {
  11757. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11758. if ( parameters.shadowMapType === PCFShadowMap ) {
  11759. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11760. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11761. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11762. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11763. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11764. }
  11765. return shadowMapTypeDefine;
  11766. }
  11767. function generateEnvMapTypeDefine( parameters ) {
  11768. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11769. if ( parameters.envMap ) {
  11770. switch ( parameters.envMapMode ) {
  11771. case CubeReflectionMapping:
  11772. case CubeRefractionMapping:
  11773. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11774. break;
  11775. case CubeUVReflectionMapping:
  11776. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11777. break;
  11778. }
  11779. }
  11780. return envMapTypeDefine;
  11781. }
  11782. function generateEnvMapModeDefine( parameters ) {
  11783. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11784. if ( parameters.envMap ) {
  11785. switch ( parameters.envMapMode ) {
  11786. case CubeRefractionMapping:
  11787. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11788. break;
  11789. }
  11790. }
  11791. return envMapModeDefine;
  11792. }
  11793. function generateEnvMapBlendingDefine( parameters ) {
  11794. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11795. if ( parameters.envMap ) {
  11796. switch ( parameters.combine ) {
  11797. case MultiplyOperation:
  11798. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11799. break;
  11800. case MixOperation:
  11801. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11802. break;
  11803. case AddOperation:
  11804. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11805. break;
  11806. }
  11807. }
  11808. return envMapBlendingDefine;
  11809. }
  11810. function generateCubeUVSize( parameters ) {
  11811. const imageHeight = parameters.envMapCubeUVHeight;
  11812. if ( imageHeight === null ) return null;
  11813. const maxMip = Math.log2( imageHeight ) - 2;
  11814. const texelHeight = 1.0 / imageHeight;
  11815. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11816. return { texelWidth, texelHeight, maxMip };
  11817. }
  11818. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11819. // TODO Send this event to Three.js DevTools
  11820. // console.log( 'WebGLProgram', cacheKey );
  11821. const gl = renderer.getContext();
  11822. const defines = parameters.defines;
  11823. let vertexShader = parameters.vertexShader;
  11824. let fragmentShader = parameters.fragmentShader;
  11825. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11826. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11827. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11828. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11829. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11830. const customVertexExtensions = generateVertexExtensions( parameters );
  11831. const customDefines = generateDefines( defines );
  11832. const program = gl.createProgram();
  11833. let prefixVertex, prefixFragment;
  11834. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11835. if ( parameters.isRawShaderMaterial ) {
  11836. prefixVertex = [
  11837. '#define SHADER_TYPE ' + parameters.shaderType,
  11838. '#define SHADER_NAME ' + parameters.shaderName,
  11839. customDefines
  11840. ].filter( filterEmptyLine ).join( '\n' );
  11841. if ( prefixVertex.length > 0 ) {
  11842. prefixVertex += '\n';
  11843. }
  11844. prefixFragment = [
  11845. '#define SHADER_TYPE ' + parameters.shaderType,
  11846. '#define SHADER_NAME ' + parameters.shaderName,
  11847. customDefines
  11848. ].filter( filterEmptyLine ).join( '\n' );
  11849. if ( prefixFragment.length > 0 ) {
  11850. prefixFragment += '\n';
  11851. }
  11852. } else {
  11853. prefixVertex = [
  11854. generatePrecision( parameters ),
  11855. '#define SHADER_TYPE ' + parameters.shaderType,
  11856. '#define SHADER_NAME ' + parameters.shaderName,
  11857. customDefines,
  11858. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11859. parameters.batching ? '#define USE_BATCHING' : '',
  11860. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  11861. parameters.instancing ? '#define USE_INSTANCING' : '',
  11862. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11863. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  11864. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11865. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11866. parameters.map ? '#define USE_MAP' : '',
  11867. parameters.envMap ? '#define USE_ENVMAP' : '',
  11868. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11869. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11870. parameters.aoMap ? '#define USE_AOMAP' : '',
  11871. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11872. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11873. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11874. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11875. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11876. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11877. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11878. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11879. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11880. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11881. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11882. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11883. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11884. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11885. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11886. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11887. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11888. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11889. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11890. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11891. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11892. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11893. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11894. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11895. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11896. //
  11897. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11898. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11899. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11900. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11901. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11902. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11903. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11904. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11905. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11906. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11907. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11908. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11909. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11910. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11911. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11912. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11913. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11914. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11915. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11916. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11917. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11918. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11919. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11920. //
  11921. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11922. parameters.vertexColors ? '#define USE_COLOR' : '',
  11923. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11924. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11925. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11926. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11927. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11928. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11929. parameters.skinning ? '#define USE_SKINNING' : '',
  11930. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11931. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11932. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  11933. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11934. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11935. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11936. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11937. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11938. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11939. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11940. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11941. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11942. 'uniform mat4 modelMatrix;',
  11943. 'uniform mat4 modelViewMatrix;',
  11944. 'uniform mat4 projectionMatrix;',
  11945. 'uniform mat4 viewMatrix;',
  11946. 'uniform mat3 normalMatrix;',
  11947. 'uniform vec3 cameraPosition;',
  11948. 'uniform bool isOrthographic;',
  11949. '#ifdef USE_INSTANCING',
  11950. ' attribute mat4 instanceMatrix;',
  11951. '#endif',
  11952. '#ifdef USE_INSTANCING_COLOR',
  11953. ' attribute vec3 instanceColor;',
  11954. '#endif',
  11955. '#ifdef USE_INSTANCING_MORPH',
  11956. ' uniform sampler2D morphTexture;',
  11957. '#endif',
  11958. 'attribute vec3 position;',
  11959. 'attribute vec3 normal;',
  11960. 'attribute vec2 uv;',
  11961. '#ifdef USE_UV1',
  11962. ' attribute vec2 uv1;',
  11963. '#endif',
  11964. '#ifdef USE_UV2',
  11965. ' attribute vec2 uv2;',
  11966. '#endif',
  11967. '#ifdef USE_UV3',
  11968. ' attribute vec2 uv3;',
  11969. '#endif',
  11970. '#ifdef USE_TANGENT',
  11971. ' attribute vec4 tangent;',
  11972. '#endif',
  11973. '#if defined( USE_COLOR_ALPHA )',
  11974. ' attribute vec4 color;',
  11975. '#elif defined( USE_COLOR )',
  11976. ' attribute vec3 color;',
  11977. '#endif',
  11978. '#ifdef USE_SKINNING',
  11979. ' attribute vec4 skinIndex;',
  11980. ' attribute vec4 skinWeight;',
  11981. '#endif',
  11982. '\n'
  11983. ].filter( filterEmptyLine ).join( '\n' );
  11984. prefixFragment = [
  11985. generatePrecision( parameters ),
  11986. '#define SHADER_TYPE ' + parameters.shaderType,
  11987. '#define SHADER_NAME ' + parameters.shaderName,
  11988. customDefines,
  11989. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11990. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11991. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  11992. parameters.map ? '#define USE_MAP' : '',
  11993. parameters.matcap ? '#define USE_MATCAP' : '',
  11994. parameters.envMap ? '#define USE_ENVMAP' : '',
  11995. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11996. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11997. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11998. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11999. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  12000. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  12001. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12002. parameters.aoMap ? '#define USE_AOMAP' : '',
  12003. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12004. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12005. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  12006. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  12007. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12008. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  12009. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  12010. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  12011. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12012. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12013. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12014. parameters.dispersion ? '#define USE_DISPERSION' : '',
  12015. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  12016. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  12017. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  12018. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12019. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  12020. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  12021. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12022. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12023. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12024. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  12025. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  12026. parameters.sheen ? '#define USE_SHEEN' : '',
  12027. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  12028. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  12029. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12030. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12031. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12032. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  12033. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  12034. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12035. parameters.vertexUv1s ? '#define USE_UV1' : '',
  12036. parameters.vertexUv2s ? '#define USE_UV2' : '',
  12037. parameters.vertexUv3s ? '#define USE_UV3' : '',
  12038. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  12039. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12040. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12041. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12042. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12043. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12044. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12045. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12046. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  12047. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  12048. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12049. 'uniform mat4 viewMatrix;',
  12050. 'uniform vec3 cameraPosition;',
  12051. 'uniform bool isOrthographic;',
  12052. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12053. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12054. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12055. parameters.dithering ? '#define DITHERING' : '',
  12056. parameters.opaque ? '#define OPAQUE' : '',
  12057. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12058. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  12059. getLuminanceFunction(),
  12060. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12061. '\n'
  12062. ].filter( filterEmptyLine ).join( '\n' );
  12063. }
  12064. vertexShader = resolveIncludes( vertexShader );
  12065. vertexShader = replaceLightNums( vertexShader, parameters );
  12066. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12067. fragmentShader = resolveIncludes( fragmentShader );
  12068. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12069. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12070. vertexShader = unrollLoops( vertexShader );
  12071. fragmentShader = unrollLoops( fragmentShader );
  12072. if ( parameters.isRawShaderMaterial !== true ) {
  12073. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12074. versionString = '#version 300 es\n';
  12075. prefixVertex = [
  12076. customVertexExtensions,
  12077. '#define attribute in',
  12078. '#define varying out',
  12079. '#define texture2D texture'
  12080. ].join( '\n' ) + '\n' + prefixVertex;
  12081. prefixFragment = [
  12082. '#define varying in',
  12083. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  12084. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12085. '#define gl_FragDepthEXT gl_FragDepth',
  12086. '#define texture2D texture',
  12087. '#define textureCube texture',
  12088. '#define texture2DProj textureProj',
  12089. '#define texture2DLodEXT textureLod',
  12090. '#define texture2DProjLodEXT textureProjLod',
  12091. '#define textureCubeLodEXT textureLod',
  12092. '#define texture2DGradEXT textureGrad',
  12093. '#define texture2DProjGradEXT textureProjGrad',
  12094. '#define textureCubeGradEXT textureGrad'
  12095. ].join( '\n' ) + '\n' + prefixFragment;
  12096. }
  12097. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12098. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12099. // console.log( '*VERTEX*', vertexGlsl );
  12100. // console.log( '*FRAGMENT*', fragmentGlsl );
  12101. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12102. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12103. gl.attachShader( program, glVertexShader );
  12104. gl.attachShader( program, glFragmentShader );
  12105. // Force a particular attribute to index 0.
  12106. if ( parameters.index0AttributeName !== undefined ) {
  12107. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12108. } else if ( parameters.morphTargets === true ) {
  12109. // programs with morphTargets displace position out of attribute 0
  12110. gl.bindAttribLocation( program, 0, 'position' );
  12111. }
  12112. gl.linkProgram( program );
  12113. function onFirstUse( self ) {
  12114. // check for link errors
  12115. if ( renderer.debug.checkShaderErrors ) {
  12116. const programLog = gl.getProgramInfoLog( program ).trim();
  12117. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12118. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12119. let runnable = true;
  12120. let haveDiagnostics = true;
  12121. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12122. runnable = false;
  12123. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12124. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12125. } else {
  12126. // default error reporting
  12127. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12128. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12129. console.error(
  12130. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12131. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12132. 'Material Name: ' + self.name + '\n' +
  12133. 'Material Type: ' + self.type + '\n\n' +
  12134. 'Program Info Log: ' + programLog + '\n' +
  12135. vertexErrors + '\n' +
  12136. fragmentErrors
  12137. );
  12138. }
  12139. } else if ( programLog !== '' ) {
  12140. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12141. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12142. haveDiagnostics = false;
  12143. }
  12144. if ( haveDiagnostics ) {
  12145. self.diagnostics = {
  12146. runnable: runnable,
  12147. programLog: programLog,
  12148. vertexShader: {
  12149. log: vertexLog,
  12150. prefix: prefixVertex
  12151. },
  12152. fragmentShader: {
  12153. log: fragmentLog,
  12154. prefix: prefixFragment
  12155. }
  12156. };
  12157. }
  12158. }
  12159. // Clean up
  12160. // Crashes in iOS9 and iOS10. #18402
  12161. // gl.detachShader( program, glVertexShader );
  12162. // gl.detachShader( program, glFragmentShader );
  12163. gl.deleteShader( glVertexShader );
  12164. gl.deleteShader( glFragmentShader );
  12165. cachedUniforms = new WebGLUniforms( gl, program );
  12166. cachedAttributes = fetchAttributeLocations( gl, program );
  12167. }
  12168. // set up caching for uniform locations
  12169. let cachedUniforms;
  12170. this.getUniforms = function () {
  12171. if ( cachedUniforms === undefined ) {
  12172. // Populates cachedUniforms and cachedAttributes
  12173. onFirstUse( this );
  12174. }
  12175. return cachedUniforms;
  12176. };
  12177. // set up caching for attribute locations
  12178. let cachedAttributes;
  12179. this.getAttributes = function () {
  12180. if ( cachedAttributes === undefined ) {
  12181. // Populates cachedAttributes and cachedUniforms
  12182. onFirstUse( this );
  12183. }
  12184. return cachedAttributes;
  12185. };
  12186. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12187. // flag the program as ready immediately. It may cause a stall when it's first used.
  12188. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12189. this.isReady = function () {
  12190. if ( programReady === false ) {
  12191. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12192. }
  12193. return programReady;
  12194. };
  12195. // free resource
  12196. this.destroy = function () {
  12197. bindingStates.releaseStatesOfProgram( this );
  12198. gl.deleteProgram( program );
  12199. this.program = undefined;
  12200. };
  12201. //
  12202. this.type = parameters.shaderType;
  12203. this.name = parameters.shaderName;
  12204. this.id = programIdCount ++;
  12205. this.cacheKey = cacheKey;
  12206. this.usedTimes = 1;
  12207. this.program = program;
  12208. this.vertexShader = glVertexShader;
  12209. this.fragmentShader = glFragmentShader;
  12210. return this;
  12211. }
  12212. let _id$1 = 0;
  12213. class WebGLShaderCache {
  12214. constructor() {
  12215. this.shaderCache = new Map();
  12216. this.materialCache = new Map();
  12217. }
  12218. update( material ) {
  12219. const vertexShader = material.vertexShader;
  12220. const fragmentShader = material.fragmentShader;
  12221. const vertexShaderStage = this._getShaderStage( vertexShader );
  12222. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12223. const materialShaders = this._getShaderCacheForMaterial( material );
  12224. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12225. materialShaders.add( vertexShaderStage );
  12226. vertexShaderStage.usedTimes ++;
  12227. }
  12228. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12229. materialShaders.add( fragmentShaderStage );
  12230. fragmentShaderStage.usedTimes ++;
  12231. }
  12232. return this;
  12233. }
  12234. remove( material ) {
  12235. const materialShaders = this.materialCache.get( material );
  12236. for ( const shaderStage of materialShaders ) {
  12237. shaderStage.usedTimes --;
  12238. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12239. }
  12240. this.materialCache.delete( material );
  12241. return this;
  12242. }
  12243. getVertexShaderID( material ) {
  12244. return this._getShaderStage( material.vertexShader ).id;
  12245. }
  12246. getFragmentShaderID( material ) {
  12247. return this._getShaderStage( material.fragmentShader ).id;
  12248. }
  12249. dispose() {
  12250. this.shaderCache.clear();
  12251. this.materialCache.clear();
  12252. }
  12253. _getShaderCacheForMaterial( material ) {
  12254. const cache = this.materialCache;
  12255. let set = cache.get( material );
  12256. if ( set === undefined ) {
  12257. set = new Set();
  12258. cache.set( material, set );
  12259. }
  12260. return set;
  12261. }
  12262. _getShaderStage( code ) {
  12263. const cache = this.shaderCache;
  12264. let stage = cache.get( code );
  12265. if ( stage === undefined ) {
  12266. stage = new WebGLShaderStage( code );
  12267. cache.set( code, stage );
  12268. }
  12269. return stage;
  12270. }
  12271. }
  12272. class WebGLShaderStage {
  12273. constructor( code ) {
  12274. this.id = _id$1 ++;
  12275. this.code = code;
  12276. this.usedTimes = 0;
  12277. }
  12278. }
  12279. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12280. const _programLayers = new Layers();
  12281. const _customShaders = new WebGLShaderCache();
  12282. const _activeChannels = new Set();
  12283. const programs = [];
  12284. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12285. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12286. let precision = capabilities.precision;
  12287. const shaderIDs = {
  12288. MeshDepthMaterial: 'depth',
  12289. MeshDistanceMaterial: 'distanceRGBA',
  12290. MeshNormalMaterial: 'normal',
  12291. MeshBasicMaterial: 'basic',
  12292. MeshLambertMaterial: 'lambert',
  12293. MeshPhongMaterial: 'phong',
  12294. MeshToonMaterial: 'toon',
  12295. MeshStandardMaterial: 'physical',
  12296. MeshPhysicalMaterial: 'physical',
  12297. MeshMatcapMaterial: 'matcap',
  12298. LineBasicMaterial: 'basic',
  12299. LineDashedMaterial: 'dashed',
  12300. PointsMaterial: 'points',
  12301. ShadowMaterial: 'shadow',
  12302. SpriteMaterial: 'sprite'
  12303. };
  12304. function getChannel( value ) {
  12305. _activeChannels.add( value );
  12306. if ( value === 0 ) return 'uv';
  12307. return `uv${ value }`;
  12308. }
  12309. function getParameters( material, lights, shadows, scene, object ) {
  12310. const fog = scene.fog;
  12311. const geometry = object.geometry;
  12312. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12313. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12314. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12315. const shaderID = shaderIDs[ material.type ];
  12316. // heuristics to create shader parameters according to lights in the scene
  12317. // (not to blow over maxLights budget)
  12318. if ( material.precision !== null ) {
  12319. precision = capabilities.getMaxPrecision( material.precision );
  12320. if ( precision !== material.precision ) {
  12321. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12322. }
  12323. }
  12324. //
  12325. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12326. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12327. let morphTextureStride = 0;
  12328. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12329. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12330. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12331. //
  12332. let vertexShader, fragmentShader;
  12333. let customVertexShaderID, customFragmentShaderID;
  12334. if ( shaderID ) {
  12335. const shader = ShaderLib[ shaderID ];
  12336. vertexShader = shader.vertexShader;
  12337. fragmentShader = shader.fragmentShader;
  12338. } else {
  12339. vertexShader = material.vertexShader;
  12340. fragmentShader = material.fragmentShader;
  12341. _customShaders.update( material );
  12342. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12343. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12344. }
  12345. const currentRenderTarget = renderer.getRenderTarget();
  12346. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12347. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12348. const HAS_MAP = !! material.map;
  12349. const HAS_MATCAP = !! material.matcap;
  12350. const HAS_ENVMAP = !! envMap;
  12351. const HAS_AOMAP = !! material.aoMap;
  12352. const HAS_LIGHTMAP = !! material.lightMap;
  12353. const HAS_BUMPMAP = !! material.bumpMap;
  12354. const HAS_NORMALMAP = !! material.normalMap;
  12355. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12356. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12357. const HAS_METALNESSMAP = !! material.metalnessMap;
  12358. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12359. const HAS_ANISOTROPY = material.anisotropy > 0;
  12360. const HAS_CLEARCOAT = material.clearcoat > 0;
  12361. const HAS_DISPERSION = material.dispersion > 0;
  12362. const HAS_IRIDESCENCE = material.iridescence > 0;
  12363. const HAS_SHEEN = material.sheen > 0;
  12364. const HAS_TRANSMISSION = material.transmission > 0;
  12365. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12366. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12367. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12368. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12369. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12370. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12371. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12372. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12373. const HAS_SPECULARMAP = !! material.specularMap;
  12374. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12375. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12376. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12377. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12378. const HAS_GRADIENTMAP = !! material.gradientMap;
  12379. const HAS_ALPHAMAP = !! material.alphaMap;
  12380. const HAS_ALPHATEST = material.alphaTest > 0;
  12381. const HAS_ALPHAHASH = !! material.alphaHash;
  12382. const HAS_EXTENSIONS = !! material.extensions;
  12383. let toneMapping = NoToneMapping;
  12384. if ( material.toneMapped ) {
  12385. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12386. toneMapping = renderer.toneMapping;
  12387. }
  12388. }
  12389. const parameters = {
  12390. shaderID: shaderID,
  12391. shaderType: material.type,
  12392. shaderName: material.name,
  12393. vertexShader: vertexShader,
  12394. fragmentShader: fragmentShader,
  12395. defines: material.defines,
  12396. customVertexShaderID: customVertexShaderID,
  12397. customFragmentShaderID: customFragmentShaderID,
  12398. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12399. glslVersion: material.glslVersion,
  12400. precision: precision,
  12401. batching: IS_BATCHEDMESH,
  12402. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  12403. instancing: IS_INSTANCEDMESH,
  12404. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12405. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  12406. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12407. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12408. alphaToCoverage: !! material.alphaToCoverage,
  12409. map: HAS_MAP,
  12410. matcap: HAS_MATCAP,
  12411. envMap: HAS_ENVMAP,
  12412. envMapMode: HAS_ENVMAP && envMap.mapping,
  12413. envMapCubeUVHeight: envMapCubeUVHeight,
  12414. aoMap: HAS_AOMAP,
  12415. lightMap: HAS_LIGHTMAP,
  12416. bumpMap: HAS_BUMPMAP,
  12417. normalMap: HAS_NORMALMAP,
  12418. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12419. emissiveMap: HAS_EMISSIVEMAP,
  12420. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12421. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12422. metalnessMap: HAS_METALNESSMAP,
  12423. roughnessMap: HAS_ROUGHNESSMAP,
  12424. anisotropy: HAS_ANISOTROPY,
  12425. anisotropyMap: HAS_ANISOTROPYMAP,
  12426. clearcoat: HAS_CLEARCOAT,
  12427. clearcoatMap: HAS_CLEARCOATMAP,
  12428. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12429. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12430. dispersion: HAS_DISPERSION,
  12431. iridescence: HAS_IRIDESCENCE,
  12432. iridescenceMap: HAS_IRIDESCENCEMAP,
  12433. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12434. sheen: HAS_SHEEN,
  12435. sheenColorMap: HAS_SHEEN_COLORMAP,
  12436. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12437. specularMap: HAS_SPECULARMAP,
  12438. specularColorMap: HAS_SPECULAR_COLORMAP,
  12439. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12440. transmission: HAS_TRANSMISSION,
  12441. transmissionMap: HAS_TRANSMISSIONMAP,
  12442. thicknessMap: HAS_THICKNESSMAP,
  12443. gradientMap: HAS_GRADIENTMAP,
  12444. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  12445. alphaMap: HAS_ALPHAMAP,
  12446. alphaTest: HAS_ALPHATEST,
  12447. alphaHash: HAS_ALPHAHASH,
  12448. combine: material.combine,
  12449. //
  12450. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12451. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12452. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12453. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12454. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12455. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12456. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12457. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12458. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12459. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12460. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12461. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12462. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12463. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12464. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12465. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12466. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12467. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12468. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12469. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12470. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12471. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12472. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12473. //
  12474. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12475. vertexColors: material.vertexColors,
  12476. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12477. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12478. fog: !! fog,
  12479. useFog: material.fog === true,
  12480. fogExp2: ( !! fog && fog.isFogExp2 ),
  12481. flatShading: material.flatShading === true,
  12482. sizeAttenuation: material.sizeAttenuation === true,
  12483. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12484. skinning: object.isSkinnedMesh === true,
  12485. morphTargets: geometry.morphAttributes.position !== undefined,
  12486. morphNormals: geometry.morphAttributes.normal !== undefined,
  12487. morphColors: geometry.morphAttributes.color !== undefined,
  12488. morphTargetsCount: morphTargetsCount,
  12489. morphTextureStride: morphTextureStride,
  12490. numDirLights: lights.directional.length,
  12491. numPointLights: lights.point.length,
  12492. numSpotLights: lights.spot.length,
  12493. numSpotLightMaps: lights.spotLightMap.length,
  12494. numRectAreaLights: lights.rectArea.length,
  12495. numHemiLights: lights.hemi.length,
  12496. numDirLightShadows: lights.directionalShadowMap.length,
  12497. numPointLightShadows: lights.pointShadowMap.length,
  12498. numSpotLightShadows: lights.spotShadowMap.length,
  12499. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12500. numLightProbes: lights.numLightProbes,
  12501. numClippingPlanes: clipping.numPlanes,
  12502. numClipIntersection: clipping.numIntersection,
  12503. dithering: material.dithering,
  12504. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12505. shadowMapType: renderer.shadowMap.type,
  12506. toneMapping: toneMapping,
  12507. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12508. premultipliedAlpha: material.premultipliedAlpha,
  12509. doubleSided: material.side === DoubleSide,
  12510. flipSided: material.side === BackSide,
  12511. useDepthPacking: material.depthPacking >= 0,
  12512. depthPacking: material.depthPacking || 0,
  12513. index0AttributeName: material.index0AttributeName,
  12514. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  12515. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  12516. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12517. customProgramCacheKey: material.customProgramCacheKey()
  12518. };
  12519. // the usage of getChannel() determines the active texture channels for this shader
  12520. parameters.vertexUv1s = _activeChannels.has( 1 );
  12521. parameters.vertexUv2s = _activeChannels.has( 2 );
  12522. parameters.vertexUv3s = _activeChannels.has( 3 );
  12523. _activeChannels.clear();
  12524. return parameters;
  12525. }
  12526. function getProgramCacheKey( parameters ) {
  12527. const array = [];
  12528. if ( parameters.shaderID ) {
  12529. array.push( parameters.shaderID );
  12530. } else {
  12531. array.push( parameters.customVertexShaderID );
  12532. array.push( parameters.customFragmentShaderID );
  12533. }
  12534. if ( parameters.defines !== undefined ) {
  12535. for ( const name in parameters.defines ) {
  12536. array.push( name );
  12537. array.push( parameters.defines[ name ] );
  12538. }
  12539. }
  12540. if ( parameters.isRawShaderMaterial === false ) {
  12541. getProgramCacheKeyParameters( array, parameters );
  12542. getProgramCacheKeyBooleans( array, parameters );
  12543. array.push( renderer.outputColorSpace );
  12544. }
  12545. array.push( parameters.customProgramCacheKey );
  12546. return array.join();
  12547. }
  12548. function getProgramCacheKeyParameters( array, parameters ) {
  12549. array.push( parameters.precision );
  12550. array.push( parameters.outputColorSpace );
  12551. array.push( parameters.envMapMode );
  12552. array.push( parameters.envMapCubeUVHeight );
  12553. array.push( parameters.mapUv );
  12554. array.push( parameters.alphaMapUv );
  12555. array.push( parameters.lightMapUv );
  12556. array.push( parameters.aoMapUv );
  12557. array.push( parameters.bumpMapUv );
  12558. array.push( parameters.normalMapUv );
  12559. array.push( parameters.displacementMapUv );
  12560. array.push( parameters.emissiveMapUv );
  12561. array.push( parameters.metalnessMapUv );
  12562. array.push( parameters.roughnessMapUv );
  12563. array.push( parameters.anisotropyMapUv );
  12564. array.push( parameters.clearcoatMapUv );
  12565. array.push( parameters.clearcoatNormalMapUv );
  12566. array.push( parameters.clearcoatRoughnessMapUv );
  12567. array.push( parameters.iridescenceMapUv );
  12568. array.push( parameters.iridescenceThicknessMapUv );
  12569. array.push( parameters.sheenColorMapUv );
  12570. array.push( parameters.sheenRoughnessMapUv );
  12571. array.push( parameters.specularMapUv );
  12572. array.push( parameters.specularColorMapUv );
  12573. array.push( parameters.specularIntensityMapUv );
  12574. array.push( parameters.transmissionMapUv );
  12575. array.push( parameters.thicknessMapUv );
  12576. array.push( parameters.combine );
  12577. array.push( parameters.fogExp2 );
  12578. array.push( parameters.sizeAttenuation );
  12579. array.push( parameters.morphTargetsCount );
  12580. array.push( parameters.morphAttributeCount );
  12581. array.push( parameters.numDirLights );
  12582. array.push( parameters.numPointLights );
  12583. array.push( parameters.numSpotLights );
  12584. array.push( parameters.numSpotLightMaps );
  12585. array.push( parameters.numHemiLights );
  12586. array.push( parameters.numRectAreaLights );
  12587. array.push( parameters.numDirLightShadows );
  12588. array.push( parameters.numPointLightShadows );
  12589. array.push( parameters.numSpotLightShadows );
  12590. array.push( parameters.numSpotLightShadowsWithMaps );
  12591. array.push( parameters.numLightProbes );
  12592. array.push( parameters.shadowMapType );
  12593. array.push( parameters.toneMapping );
  12594. array.push( parameters.numClippingPlanes );
  12595. array.push( parameters.numClipIntersection );
  12596. array.push( parameters.depthPacking );
  12597. }
  12598. function getProgramCacheKeyBooleans( array, parameters ) {
  12599. _programLayers.disableAll();
  12600. if ( parameters.supportsVertexTextures )
  12601. _programLayers.enable( 0 );
  12602. if ( parameters.instancing )
  12603. _programLayers.enable( 1 );
  12604. if ( parameters.instancingColor )
  12605. _programLayers.enable( 2 );
  12606. if ( parameters.instancingMorph )
  12607. _programLayers.enable( 3 );
  12608. if ( parameters.matcap )
  12609. _programLayers.enable( 4 );
  12610. if ( parameters.envMap )
  12611. _programLayers.enable( 5 );
  12612. if ( parameters.normalMapObjectSpace )
  12613. _programLayers.enable( 6 );
  12614. if ( parameters.normalMapTangentSpace )
  12615. _programLayers.enable( 7 );
  12616. if ( parameters.clearcoat )
  12617. _programLayers.enable( 8 );
  12618. if ( parameters.iridescence )
  12619. _programLayers.enable( 9 );
  12620. if ( parameters.alphaTest )
  12621. _programLayers.enable( 10 );
  12622. if ( parameters.vertexColors )
  12623. _programLayers.enable( 11 );
  12624. if ( parameters.vertexAlphas )
  12625. _programLayers.enable( 12 );
  12626. if ( parameters.vertexUv1s )
  12627. _programLayers.enable( 13 );
  12628. if ( parameters.vertexUv2s )
  12629. _programLayers.enable( 14 );
  12630. if ( parameters.vertexUv3s )
  12631. _programLayers.enable( 15 );
  12632. if ( parameters.vertexTangents )
  12633. _programLayers.enable( 16 );
  12634. if ( parameters.anisotropy )
  12635. _programLayers.enable( 17 );
  12636. if ( parameters.alphaHash )
  12637. _programLayers.enable( 18 );
  12638. if ( parameters.batching )
  12639. _programLayers.enable( 19 );
  12640. if ( parameters.dispersion )
  12641. _programLayers.enable( 20 );
  12642. if ( parameters.batchingColor )
  12643. _programLayers.enable( 21 );
  12644. array.push( _programLayers.mask );
  12645. _programLayers.disableAll();
  12646. if ( parameters.fog )
  12647. _programLayers.enable( 0 );
  12648. if ( parameters.useFog )
  12649. _programLayers.enable( 1 );
  12650. if ( parameters.flatShading )
  12651. _programLayers.enable( 2 );
  12652. if ( parameters.logarithmicDepthBuffer )
  12653. _programLayers.enable( 3 );
  12654. if ( parameters.skinning )
  12655. _programLayers.enable( 4 );
  12656. if ( parameters.morphTargets )
  12657. _programLayers.enable( 5 );
  12658. if ( parameters.morphNormals )
  12659. _programLayers.enable( 6 );
  12660. if ( parameters.morphColors )
  12661. _programLayers.enable( 7 );
  12662. if ( parameters.premultipliedAlpha )
  12663. _programLayers.enable( 8 );
  12664. if ( parameters.shadowMapEnabled )
  12665. _programLayers.enable( 9 );
  12666. if ( parameters.doubleSided )
  12667. _programLayers.enable( 10 );
  12668. if ( parameters.flipSided )
  12669. _programLayers.enable( 11 );
  12670. if ( parameters.useDepthPacking )
  12671. _programLayers.enable( 12 );
  12672. if ( parameters.dithering )
  12673. _programLayers.enable( 13 );
  12674. if ( parameters.transmission )
  12675. _programLayers.enable( 14 );
  12676. if ( parameters.sheen )
  12677. _programLayers.enable( 15 );
  12678. if ( parameters.opaque )
  12679. _programLayers.enable( 16 );
  12680. if ( parameters.pointsUvs )
  12681. _programLayers.enable( 17 );
  12682. if ( parameters.decodeVideoTexture )
  12683. _programLayers.enable( 18 );
  12684. if ( parameters.alphaToCoverage )
  12685. _programLayers.enable( 19 );
  12686. array.push( _programLayers.mask );
  12687. }
  12688. function getUniforms( material ) {
  12689. const shaderID = shaderIDs[ material.type ];
  12690. let uniforms;
  12691. if ( shaderID ) {
  12692. const shader = ShaderLib[ shaderID ];
  12693. uniforms = UniformsUtils.clone( shader.uniforms );
  12694. } else {
  12695. uniforms = material.uniforms;
  12696. }
  12697. return uniforms;
  12698. }
  12699. function acquireProgram( parameters, cacheKey ) {
  12700. let program;
  12701. // Check if code has been already compiled
  12702. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12703. const preexistingProgram = programs[ p ];
  12704. if ( preexistingProgram.cacheKey === cacheKey ) {
  12705. program = preexistingProgram;
  12706. ++ program.usedTimes;
  12707. break;
  12708. }
  12709. }
  12710. if ( program === undefined ) {
  12711. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12712. programs.push( program );
  12713. }
  12714. return program;
  12715. }
  12716. function releaseProgram( program ) {
  12717. if ( -- program.usedTimes === 0 ) {
  12718. // Remove from unordered set
  12719. const i = programs.indexOf( program );
  12720. programs[ i ] = programs[ programs.length - 1 ];
  12721. programs.pop();
  12722. // Free WebGL resources
  12723. program.destroy();
  12724. }
  12725. }
  12726. function releaseShaderCache( material ) {
  12727. _customShaders.remove( material );
  12728. }
  12729. function dispose() {
  12730. _customShaders.dispose();
  12731. }
  12732. return {
  12733. getParameters: getParameters,
  12734. getProgramCacheKey: getProgramCacheKey,
  12735. getUniforms: getUniforms,
  12736. acquireProgram: acquireProgram,
  12737. releaseProgram: releaseProgram,
  12738. releaseShaderCache: releaseShaderCache,
  12739. // Exposed for resource monitoring & error feedback via renderer.info:
  12740. programs: programs,
  12741. dispose: dispose
  12742. };
  12743. }
  12744. function WebGLProperties() {
  12745. let properties = new WeakMap();
  12746. function get( object ) {
  12747. let map = properties.get( object );
  12748. if ( map === undefined ) {
  12749. map = {};
  12750. properties.set( object, map );
  12751. }
  12752. return map;
  12753. }
  12754. function remove( object ) {
  12755. properties.delete( object );
  12756. }
  12757. function update( object, key, value ) {
  12758. properties.get( object )[ key ] = value;
  12759. }
  12760. function dispose() {
  12761. properties = new WeakMap();
  12762. }
  12763. return {
  12764. get: get,
  12765. remove: remove,
  12766. update: update,
  12767. dispose: dispose
  12768. };
  12769. }
  12770. function painterSortStable( a, b ) {
  12771. if ( a.groupOrder !== b.groupOrder ) {
  12772. return a.groupOrder - b.groupOrder;
  12773. } else if ( a.renderOrder !== b.renderOrder ) {
  12774. return a.renderOrder - b.renderOrder;
  12775. } else if ( a.material.id !== b.material.id ) {
  12776. return a.material.id - b.material.id;
  12777. } else if ( a.z !== b.z ) {
  12778. return a.z - b.z;
  12779. } else {
  12780. return a.id - b.id;
  12781. }
  12782. }
  12783. function reversePainterSortStable( a, b ) {
  12784. if ( a.groupOrder !== b.groupOrder ) {
  12785. return a.groupOrder - b.groupOrder;
  12786. } else if ( a.renderOrder !== b.renderOrder ) {
  12787. return a.renderOrder - b.renderOrder;
  12788. } else if ( a.z !== b.z ) {
  12789. return b.z - a.z;
  12790. } else {
  12791. return a.id - b.id;
  12792. }
  12793. }
  12794. function WebGLRenderList() {
  12795. const renderItems = [];
  12796. let renderItemsIndex = 0;
  12797. const opaque = [];
  12798. const transmissive = [];
  12799. const transparent = [];
  12800. function init() {
  12801. renderItemsIndex = 0;
  12802. opaque.length = 0;
  12803. transmissive.length = 0;
  12804. transparent.length = 0;
  12805. }
  12806. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12807. let renderItem = renderItems[ renderItemsIndex ];
  12808. if ( renderItem === undefined ) {
  12809. renderItem = {
  12810. id: object.id,
  12811. object: object,
  12812. geometry: geometry,
  12813. material: material,
  12814. groupOrder: groupOrder,
  12815. renderOrder: object.renderOrder,
  12816. z: z,
  12817. group: group
  12818. };
  12819. renderItems[ renderItemsIndex ] = renderItem;
  12820. } else {
  12821. renderItem.id = object.id;
  12822. renderItem.object = object;
  12823. renderItem.geometry = geometry;
  12824. renderItem.material = material;
  12825. renderItem.groupOrder = groupOrder;
  12826. renderItem.renderOrder = object.renderOrder;
  12827. renderItem.z = z;
  12828. renderItem.group = group;
  12829. }
  12830. renderItemsIndex ++;
  12831. return renderItem;
  12832. }
  12833. function push( object, geometry, material, groupOrder, z, group ) {
  12834. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12835. if ( material.transmission > 0.0 ) {
  12836. transmissive.push( renderItem );
  12837. } else if ( material.transparent === true ) {
  12838. transparent.push( renderItem );
  12839. } else {
  12840. opaque.push( renderItem );
  12841. }
  12842. }
  12843. function unshift( object, geometry, material, groupOrder, z, group ) {
  12844. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12845. if ( material.transmission > 0.0 ) {
  12846. transmissive.unshift( renderItem );
  12847. } else if ( material.transparent === true ) {
  12848. transparent.unshift( renderItem );
  12849. } else {
  12850. opaque.unshift( renderItem );
  12851. }
  12852. }
  12853. function sort( customOpaqueSort, customTransparentSort ) {
  12854. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12855. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12856. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12857. }
  12858. function finish() {
  12859. // Clear references from inactive renderItems in the list
  12860. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12861. const renderItem = renderItems[ i ];
  12862. if ( renderItem.id === null ) break;
  12863. renderItem.id = null;
  12864. renderItem.object = null;
  12865. renderItem.geometry = null;
  12866. renderItem.material = null;
  12867. renderItem.group = null;
  12868. }
  12869. }
  12870. return {
  12871. opaque: opaque,
  12872. transmissive: transmissive,
  12873. transparent: transparent,
  12874. init: init,
  12875. push: push,
  12876. unshift: unshift,
  12877. finish: finish,
  12878. sort: sort
  12879. };
  12880. }
  12881. function WebGLRenderLists() {
  12882. let lists = new WeakMap();
  12883. function get( scene, renderCallDepth ) {
  12884. const listArray = lists.get( scene );
  12885. let list;
  12886. if ( listArray === undefined ) {
  12887. list = new WebGLRenderList();
  12888. lists.set( scene, [ list ] );
  12889. } else {
  12890. if ( renderCallDepth >= listArray.length ) {
  12891. list = new WebGLRenderList();
  12892. listArray.push( list );
  12893. } else {
  12894. list = listArray[ renderCallDepth ];
  12895. }
  12896. }
  12897. return list;
  12898. }
  12899. function dispose() {
  12900. lists = new WeakMap();
  12901. }
  12902. return {
  12903. get: get,
  12904. dispose: dispose
  12905. };
  12906. }
  12907. function UniformsCache() {
  12908. const lights = {};
  12909. return {
  12910. get: function ( light ) {
  12911. if ( lights[ light.id ] !== undefined ) {
  12912. return lights[ light.id ];
  12913. }
  12914. let uniforms;
  12915. switch ( light.type ) {
  12916. case 'DirectionalLight':
  12917. uniforms = {
  12918. direction: new Vector3(),
  12919. color: new Color()
  12920. };
  12921. break;
  12922. case 'SpotLight':
  12923. uniforms = {
  12924. position: new Vector3(),
  12925. direction: new Vector3(),
  12926. color: new Color(),
  12927. distance: 0,
  12928. coneCos: 0,
  12929. penumbraCos: 0,
  12930. decay: 0
  12931. };
  12932. break;
  12933. case 'PointLight':
  12934. uniforms = {
  12935. position: new Vector3(),
  12936. color: new Color(),
  12937. distance: 0,
  12938. decay: 0
  12939. };
  12940. break;
  12941. case 'HemisphereLight':
  12942. uniforms = {
  12943. direction: new Vector3(),
  12944. skyColor: new Color(),
  12945. groundColor: new Color()
  12946. };
  12947. break;
  12948. case 'RectAreaLight':
  12949. uniforms = {
  12950. color: new Color(),
  12951. position: new Vector3(),
  12952. halfWidth: new Vector3(),
  12953. halfHeight: new Vector3()
  12954. };
  12955. break;
  12956. }
  12957. lights[ light.id ] = uniforms;
  12958. return uniforms;
  12959. }
  12960. };
  12961. }
  12962. function ShadowUniformsCache() {
  12963. const lights = {};
  12964. return {
  12965. get: function ( light ) {
  12966. if ( lights[ light.id ] !== undefined ) {
  12967. return lights[ light.id ];
  12968. }
  12969. let uniforms;
  12970. switch ( light.type ) {
  12971. case 'DirectionalLight':
  12972. uniforms = {
  12973. shadowIntensity: 1,
  12974. shadowBias: 0,
  12975. shadowNormalBias: 0,
  12976. shadowRadius: 1,
  12977. shadowMapSize: new Vector2()
  12978. };
  12979. break;
  12980. case 'SpotLight':
  12981. uniforms = {
  12982. shadowIntensity: 1,
  12983. shadowBias: 0,
  12984. shadowNormalBias: 0,
  12985. shadowRadius: 1,
  12986. shadowMapSize: new Vector2()
  12987. };
  12988. break;
  12989. case 'PointLight':
  12990. uniforms = {
  12991. shadowIntensity: 1,
  12992. shadowBias: 0,
  12993. shadowNormalBias: 0,
  12994. shadowRadius: 1,
  12995. shadowMapSize: new Vector2(),
  12996. shadowCameraNear: 1,
  12997. shadowCameraFar: 1000
  12998. };
  12999. break;
  13000. // TODO (abelnation): set RectAreaLight shadow uniforms
  13001. }
  13002. lights[ light.id ] = uniforms;
  13003. return uniforms;
  13004. }
  13005. };
  13006. }
  13007. let nextVersion = 0;
  13008. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  13009. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  13010. }
  13011. function WebGLLights( extensions ) {
  13012. const cache = new UniformsCache();
  13013. const shadowCache = ShadowUniformsCache();
  13014. const state = {
  13015. version: 0,
  13016. hash: {
  13017. directionalLength: - 1,
  13018. pointLength: - 1,
  13019. spotLength: - 1,
  13020. rectAreaLength: - 1,
  13021. hemiLength: - 1,
  13022. numDirectionalShadows: - 1,
  13023. numPointShadows: - 1,
  13024. numSpotShadows: - 1,
  13025. numSpotMaps: - 1,
  13026. numLightProbes: - 1
  13027. },
  13028. ambient: [ 0, 0, 0 ],
  13029. probe: [],
  13030. directional: [],
  13031. directionalShadow: [],
  13032. directionalShadowMap: [],
  13033. directionalShadowMatrix: [],
  13034. spot: [],
  13035. spotLightMap: [],
  13036. spotShadow: [],
  13037. spotShadowMap: [],
  13038. spotLightMatrix: [],
  13039. rectArea: [],
  13040. rectAreaLTC1: null,
  13041. rectAreaLTC2: null,
  13042. point: [],
  13043. pointShadow: [],
  13044. pointShadowMap: [],
  13045. pointShadowMatrix: [],
  13046. hemi: [],
  13047. numSpotLightShadowsWithMaps: 0,
  13048. numLightProbes: 0
  13049. };
  13050. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  13051. const vector3 = new Vector3();
  13052. const matrix4 = new Matrix4();
  13053. const matrix42 = new Matrix4();
  13054. function setup( lights ) {
  13055. let r = 0, g = 0, b = 0;
  13056. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  13057. let directionalLength = 0;
  13058. let pointLength = 0;
  13059. let spotLength = 0;
  13060. let rectAreaLength = 0;
  13061. let hemiLength = 0;
  13062. let numDirectionalShadows = 0;
  13063. let numPointShadows = 0;
  13064. let numSpotShadows = 0;
  13065. let numSpotMaps = 0;
  13066. let numSpotShadowsWithMaps = 0;
  13067. let numLightProbes = 0;
  13068. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  13069. lights.sort( shadowCastingAndTexturingLightsFirst );
  13070. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13071. const light = lights[ i ];
  13072. const color = light.color;
  13073. const intensity = light.intensity;
  13074. const distance = light.distance;
  13075. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13076. if ( light.isAmbientLight ) {
  13077. r += color.r * intensity;
  13078. g += color.g * intensity;
  13079. b += color.b * intensity;
  13080. } else if ( light.isLightProbe ) {
  13081. for ( let j = 0; j < 9; j ++ ) {
  13082. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  13083. }
  13084. numLightProbes ++;
  13085. } else if ( light.isDirectionalLight ) {
  13086. const uniforms = cache.get( light );
  13087. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13088. if ( light.castShadow ) {
  13089. const shadow = light.shadow;
  13090. const shadowUniforms = shadowCache.get( light );
  13091. shadowUniforms.shadowIntensity = shadow.intensity;
  13092. shadowUniforms.shadowBias = shadow.bias;
  13093. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13094. shadowUniforms.shadowRadius = shadow.radius;
  13095. shadowUniforms.shadowMapSize = shadow.mapSize;
  13096. state.directionalShadow[ directionalLength ] = shadowUniforms;
  13097. state.directionalShadowMap[ directionalLength ] = shadowMap;
  13098. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13099. numDirectionalShadows ++;
  13100. }
  13101. state.directional[ directionalLength ] = uniforms;
  13102. directionalLength ++;
  13103. } else if ( light.isSpotLight ) {
  13104. const uniforms = cache.get( light );
  13105. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13106. uniforms.color.copy( color ).multiplyScalar( intensity );
  13107. uniforms.distance = distance;
  13108. uniforms.coneCos = Math.cos( light.angle );
  13109. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13110. uniforms.decay = light.decay;
  13111. state.spot[ spotLength ] = uniforms;
  13112. const shadow = light.shadow;
  13113. if ( light.map ) {
  13114. state.spotLightMap[ numSpotMaps ] = light.map;
  13115. numSpotMaps ++;
  13116. // make sure the lightMatrix is up to date
  13117. // TODO : do it if required only
  13118. shadow.updateMatrices( light );
  13119. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13120. }
  13121. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13122. if ( light.castShadow ) {
  13123. const shadowUniforms = shadowCache.get( light );
  13124. shadowUniforms.shadowIntensity = shadow.intensity;
  13125. shadowUniforms.shadowBias = shadow.bias;
  13126. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13127. shadowUniforms.shadowRadius = shadow.radius;
  13128. shadowUniforms.shadowMapSize = shadow.mapSize;
  13129. state.spotShadow[ spotLength ] = shadowUniforms;
  13130. state.spotShadowMap[ spotLength ] = shadowMap;
  13131. numSpotShadows ++;
  13132. }
  13133. spotLength ++;
  13134. } else if ( light.isRectAreaLight ) {
  13135. const uniforms = cache.get( light );
  13136. uniforms.color.copy( color ).multiplyScalar( intensity );
  13137. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13138. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13139. state.rectArea[ rectAreaLength ] = uniforms;
  13140. rectAreaLength ++;
  13141. } else if ( light.isPointLight ) {
  13142. const uniforms = cache.get( light );
  13143. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13144. uniforms.distance = light.distance;
  13145. uniforms.decay = light.decay;
  13146. if ( light.castShadow ) {
  13147. const shadow = light.shadow;
  13148. const shadowUniforms = shadowCache.get( light );
  13149. shadowUniforms.shadowIntensity = shadow.intensity;
  13150. shadowUniforms.shadowBias = shadow.bias;
  13151. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13152. shadowUniforms.shadowRadius = shadow.radius;
  13153. shadowUniforms.shadowMapSize = shadow.mapSize;
  13154. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13155. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13156. state.pointShadow[ pointLength ] = shadowUniforms;
  13157. state.pointShadowMap[ pointLength ] = shadowMap;
  13158. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13159. numPointShadows ++;
  13160. }
  13161. state.point[ pointLength ] = uniforms;
  13162. pointLength ++;
  13163. } else if ( light.isHemisphereLight ) {
  13164. const uniforms = cache.get( light );
  13165. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13166. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13167. state.hemi[ hemiLength ] = uniforms;
  13168. hemiLength ++;
  13169. }
  13170. }
  13171. if ( rectAreaLength > 0 ) {
  13172. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13173. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13174. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13175. } else {
  13176. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13177. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13178. }
  13179. }
  13180. state.ambient[ 0 ] = r;
  13181. state.ambient[ 1 ] = g;
  13182. state.ambient[ 2 ] = b;
  13183. const hash = state.hash;
  13184. if ( hash.directionalLength !== directionalLength ||
  13185. hash.pointLength !== pointLength ||
  13186. hash.spotLength !== spotLength ||
  13187. hash.rectAreaLength !== rectAreaLength ||
  13188. hash.hemiLength !== hemiLength ||
  13189. hash.numDirectionalShadows !== numDirectionalShadows ||
  13190. hash.numPointShadows !== numPointShadows ||
  13191. hash.numSpotShadows !== numSpotShadows ||
  13192. hash.numSpotMaps !== numSpotMaps ||
  13193. hash.numLightProbes !== numLightProbes ) {
  13194. state.directional.length = directionalLength;
  13195. state.spot.length = spotLength;
  13196. state.rectArea.length = rectAreaLength;
  13197. state.point.length = pointLength;
  13198. state.hemi.length = hemiLength;
  13199. state.directionalShadow.length = numDirectionalShadows;
  13200. state.directionalShadowMap.length = numDirectionalShadows;
  13201. state.pointShadow.length = numPointShadows;
  13202. state.pointShadowMap.length = numPointShadows;
  13203. state.spotShadow.length = numSpotShadows;
  13204. state.spotShadowMap.length = numSpotShadows;
  13205. state.directionalShadowMatrix.length = numDirectionalShadows;
  13206. state.pointShadowMatrix.length = numPointShadows;
  13207. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13208. state.spotLightMap.length = numSpotMaps;
  13209. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13210. state.numLightProbes = numLightProbes;
  13211. hash.directionalLength = directionalLength;
  13212. hash.pointLength = pointLength;
  13213. hash.spotLength = spotLength;
  13214. hash.rectAreaLength = rectAreaLength;
  13215. hash.hemiLength = hemiLength;
  13216. hash.numDirectionalShadows = numDirectionalShadows;
  13217. hash.numPointShadows = numPointShadows;
  13218. hash.numSpotShadows = numSpotShadows;
  13219. hash.numSpotMaps = numSpotMaps;
  13220. hash.numLightProbes = numLightProbes;
  13221. state.version = nextVersion ++;
  13222. }
  13223. }
  13224. function setupView( lights, camera ) {
  13225. let directionalLength = 0;
  13226. let pointLength = 0;
  13227. let spotLength = 0;
  13228. let rectAreaLength = 0;
  13229. let hemiLength = 0;
  13230. const viewMatrix = camera.matrixWorldInverse;
  13231. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13232. const light = lights[ i ];
  13233. if ( light.isDirectionalLight ) {
  13234. const uniforms = state.directional[ directionalLength ];
  13235. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13236. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13237. uniforms.direction.sub( vector3 );
  13238. uniforms.direction.transformDirection( viewMatrix );
  13239. directionalLength ++;
  13240. } else if ( light.isSpotLight ) {
  13241. const uniforms = state.spot[ spotLength ];
  13242. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13243. uniforms.position.applyMatrix4( viewMatrix );
  13244. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13245. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13246. uniforms.direction.sub( vector3 );
  13247. uniforms.direction.transformDirection( viewMatrix );
  13248. spotLength ++;
  13249. } else if ( light.isRectAreaLight ) {
  13250. const uniforms = state.rectArea[ rectAreaLength ];
  13251. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13252. uniforms.position.applyMatrix4( viewMatrix );
  13253. // extract local rotation of light to derive width/height half vectors
  13254. matrix42.identity();
  13255. matrix4.copy( light.matrixWorld );
  13256. matrix4.premultiply( viewMatrix );
  13257. matrix42.extractRotation( matrix4 );
  13258. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13259. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13260. uniforms.halfWidth.applyMatrix4( matrix42 );
  13261. uniforms.halfHeight.applyMatrix4( matrix42 );
  13262. rectAreaLength ++;
  13263. } else if ( light.isPointLight ) {
  13264. const uniforms = state.point[ pointLength ];
  13265. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13266. uniforms.position.applyMatrix4( viewMatrix );
  13267. pointLength ++;
  13268. } else if ( light.isHemisphereLight ) {
  13269. const uniforms = state.hemi[ hemiLength ];
  13270. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13271. uniforms.direction.transformDirection( viewMatrix );
  13272. hemiLength ++;
  13273. }
  13274. }
  13275. }
  13276. return {
  13277. setup: setup,
  13278. setupView: setupView,
  13279. state: state
  13280. };
  13281. }
  13282. function WebGLRenderState( extensions ) {
  13283. const lights = new WebGLLights( extensions );
  13284. const lightsArray = [];
  13285. const shadowsArray = [];
  13286. function init( camera ) {
  13287. state.camera = camera;
  13288. lightsArray.length = 0;
  13289. shadowsArray.length = 0;
  13290. }
  13291. function pushLight( light ) {
  13292. lightsArray.push( light );
  13293. }
  13294. function pushShadow( shadowLight ) {
  13295. shadowsArray.push( shadowLight );
  13296. }
  13297. function setupLights() {
  13298. lights.setup( lightsArray );
  13299. }
  13300. function setupLightsView( camera ) {
  13301. lights.setupView( lightsArray, camera );
  13302. }
  13303. const state = {
  13304. lightsArray: lightsArray,
  13305. shadowsArray: shadowsArray,
  13306. camera: null,
  13307. lights: lights,
  13308. transmissionRenderTarget: {}
  13309. };
  13310. return {
  13311. init: init,
  13312. state: state,
  13313. setupLights: setupLights,
  13314. setupLightsView: setupLightsView,
  13315. pushLight: pushLight,
  13316. pushShadow: pushShadow
  13317. };
  13318. }
  13319. function WebGLRenderStates( extensions ) {
  13320. let renderStates = new WeakMap();
  13321. function get( scene, renderCallDepth = 0 ) {
  13322. const renderStateArray = renderStates.get( scene );
  13323. let renderState;
  13324. if ( renderStateArray === undefined ) {
  13325. renderState = new WebGLRenderState( extensions );
  13326. renderStates.set( scene, [ renderState ] );
  13327. } else {
  13328. if ( renderCallDepth >= renderStateArray.length ) {
  13329. renderState = new WebGLRenderState( extensions );
  13330. renderStateArray.push( renderState );
  13331. } else {
  13332. renderState = renderStateArray[ renderCallDepth ];
  13333. }
  13334. }
  13335. return renderState;
  13336. }
  13337. function dispose() {
  13338. renderStates = new WeakMap();
  13339. }
  13340. return {
  13341. get: get,
  13342. dispose: dispose
  13343. };
  13344. }
  13345. class MeshDepthMaterial extends Material {
  13346. constructor( parameters ) {
  13347. super();
  13348. this.isMeshDepthMaterial = true;
  13349. this.type = 'MeshDepthMaterial';
  13350. this.depthPacking = BasicDepthPacking;
  13351. this.map = null;
  13352. this.alphaMap = null;
  13353. this.displacementMap = null;
  13354. this.displacementScale = 1;
  13355. this.displacementBias = 0;
  13356. this.wireframe = false;
  13357. this.wireframeLinewidth = 1;
  13358. this.setValues( parameters );
  13359. }
  13360. copy( source ) {
  13361. super.copy( source );
  13362. this.depthPacking = source.depthPacking;
  13363. this.map = source.map;
  13364. this.alphaMap = source.alphaMap;
  13365. this.displacementMap = source.displacementMap;
  13366. this.displacementScale = source.displacementScale;
  13367. this.displacementBias = source.displacementBias;
  13368. this.wireframe = source.wireframe;
  13369. this.wireframeLinewidth = source.wireframeLinewidth;
  13370. return this;
  13371. }
  13372. }
  13373. class MeshDistanceMaterial extends Material {
  13374. constructor( parameters ) {
  13375. super();
  13376. this.isMeshDistanceMaterial = true;
  13377. this.type = 'MeshDistanceMaterial';
  13378. this.map = null;
  13379. this.alphaMap = null;
  13380. this.displacementMap = null;
  13381. this.displacementScale = 1;
  13382. this.displacementBias = 0;
  13383. this.setValues( parameters );
  13384. }
  13385. copy( source ) {
  13386. super.copy( source );
  13387. this.map = source.map;
  13388. this.alphaMap = source.alphaMap;
  13389. this.displacementMap = source.displacementMap;
  13390. this.displacementScale = source.displacementScale;
  13391. this.displacementBias = source.displacementBias;
  13392. return this;
  13393. }
  13394. }
  13395. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13396. 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}";
  13397. function WebGLShadowMap( renderer, objects, capabilities ) {
  13398. let _frustum = new Frustum();
  13399. const _shadowMapSize = new Vector2(),
  13400. _viewportSize = new Vector2(),
  13401. _viewport = new Vector4(),
  13402. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13403. _distanceMaterial = new MeshDistanceMaterial(),
  13404. _materialCache = {},
  13405. _maxTextureSize = capabilities.maxTextureSize;
  13406. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13407. const shadowMaterialVertical = new ShaderMaterial( {
  13408. defines: {
  13409. VSM_SAMPLES: 8
  13410. },
  13411. uniforms: {
  13412. shadow_pass: { value: null },
  13413. resolution: { value: new Vector2() },
  13414. radius: { value: 4.0 }
  13415. },
  13416. vertexShader: vertex,
  13417. fragmentShader: fragment
  13418. } );
  13419. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13420. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13421. const fullScreenTri = new BufferGeometry();
  13422. fullScreenTri.setAttribute(
  13423. 'position',
  13424. new BufferAttribute(
  13425. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13426. 3
  13427. )
  13428. );
  13429. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13430. const scope = this;
  13431. this.enabled = false;
  13432. this.autoUpdate = true;
  13433. this.needsUpdate = false;
  13434. this.type = PCFShadowMap;
  13435. let _previousType = this.type;
  13436. this.render = function ( lights, scene, camera ) {
  13437. if ( scope.enabled === false ) return;
  13438. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13439. if ( lights.length === 0 ) return;
  13440. const currentRenderTarget = renderer.getRenderTarget();
  13441. const activeCubeFace = renderer.getActiveCubeFace();
  13442. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  13443. const _state = renderer.state;
  13444. // Set GL state for depth map.
  13445. _state.setBlending( NoBlending );
  13446. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13447. _state.buffers.depth.setTest( true );
  13448. _state.setScissorTest( false );
  13449. // check for shadow map type changes
  13450. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13451. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13452. // render depth map
  13453. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13454. const light = lights[ i ];
  13455. const shadow = light.shadow;
  13456. if ( shadow === undefined ) {
  13457. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13458. continue;
  13459. }
  13460. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13461. _shadowMapSize.copy( shadow.mapSize );
  13462. const shadowFrameExtents = shadow.getFrameExtents();
  13463. _shadowMapSize.multiply( shadowFrameExtents );
  13464. _viewportSize.copy( shadow.mapSize );
  13465. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13466. if ( _shadowMapSize.x > _maxTextureSize ) {
  13467. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13468. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13469. shadow.mapSize.x = _viewportSize.x;
  13470. }
  13471. if ( _shadowMapSize.y > _maxTextureSize ) {
  13472. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13473. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13474. shadow.mapSize.y = _viewportSize.y;
  13475. }
  13476. }
  13477. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13478. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13479. if ( shadow.map !== null ) {
  13480. shadow.map.dispose();
  13481. }
  13482. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13483. shadow.map.texture.name = light.name + '.shadowMap';
  13484. shadow.camera.updateProjectionMatrix();
  13485. }
  13486. renderer.setRenderTarget( shadow.map );
  13487. renderer.clear();
  13488. const viewportCount = shadow.getViewportCount();
  13489. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13490. const viewport = shadow.getViewport( vp );
  13491. _viewport.set(
  13492. _viewportSize.x * viewport.x,
  13493. _viewportSize.y * viewport.y,
  13494. _viewportSize.x * viewport.z,
  13495. _viewportSize.y * viewport.w
  13496. );
  13497. _state.viewport( _viewport );
  13498. shadow.updateMatrices( light, vp );
  13499. _frustum = shadow.getFrustum();
  13500. renderObject( scene, camera, shadow.camera, light, this.type );
  13501. }
  13502. // do blur pass for VSM
  13503. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13504. VSMPass( shadow, camera );
  13505. }
  13506. shadow.needsUpdate = false;
  13507. }
  13508. _previousType = this.type;
  13509. scope.needsUpdate = false;
  13510. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13511. };
  13512. function VSMPass( shadow, camera ) {
  13513. const geometry = objects.update( fullScreenMesh );
  13514. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13515. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13516. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13517. shadowMaterialVertical.needsUpdate = true;
  13518. shadowMaterialHorizontal.needsUpdate = true;
  13519. }
  13520. if ( shadow.mapPass === null ) {
  13521. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13522. }
  13523. // vertical pass
  13524. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13525. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13526. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13527. renderer.setRenderTarget( shadow.mapPass );
  13528. renderer.clear();
  13529. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13530. // horizontal pass
  13531. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13532. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13533. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13534. renderer.setRenderTarget( shadow.map );
  13535. renderer.clear();
  13536. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13537. }
  13538. function getDepthMaterial( object, material, light, type ) {
  13539. let result = null;
  13540. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13541. if ( customMaterial !== undefined ) {
  13542. result = customMaterial;
  13543. } else {
  13544. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13545. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13546. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13547. ( material.alphaMap && material.alphaTest > 0 ) ||
  13548. ( material.map && material.alphaTest > 0 ) ) {
  13549. // in this case we need a unique material instance reflecting the
  13550. // appropriate state
  13551. const keyA = result.uuid, keyB = material.uuid;
  13552. let materialsForVariant = _materialCache[ keyA ];
  13553. if ( materialsForVariant === undefined ) {
  13554. materialsForVariant = {};
  13555. _materialCache[ keyA ] = materialsForVariant;
  13556. }
  13557. let cachedMaterial = materialsForVariant[ keyB ];
  13558. if ( cachedMaterial === undefined ) {
  13559. cachedMaterial = result.clone();
  13560. materialsForVariant[ keyB ] = cachedMaterial;
  13561. material.addEventListener( 'dispose', onMaterialDispose );
  13562. }
  13563. result = cachedMaterial;
  13564. }
  13565. }
  13566. result.visible = material.visible;
  13567. result.wireframe = material.wireframe;
  13568. if ( type === VSMShadowMap ) {
  13569. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13570. } else {
  13571. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13572. }
  13573. result.alphaMap = material.alphaMap;
  13574. result.alphaTest = material.alphaTest;
  13575. result.map = material.map;
  13576. result.clipShadows = material.clipShadows;
  13577. result.clippingPlanes = material.clippingPlanes;
  13578. result.clipIntersection = material.clipIntersection;
  13579. result.displacementMap = material.displacementMap;
  13580. result.displacementScale = material.displacementScale;
  13581. result.displacementBias = material.displacementBias;
  13582. result.wireframeLinewidth = material.wireframeLinewidth;
  13583. result.linewidth = material.linewidth;
  13584. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13585. const materialProperties = renderer.properties.get( result );
  13586. materialProperties.light = light;
  13587. }
  13588. return result;
  13589. }
  13590. function renderObject( object, camera, shadowCamera, light, type ) {
  13591. if ( object.visible === false ) return;
  13592. const visible = object.layers.test( camera.layers );
  13593. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13594. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13595. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13596. const geometry = objects.update( object );
  13597. const material = object.material;
  13598. if ( Array.isArray( material ) ) {
  13599. const groups = geometry.groups;
  13600. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13601. const group = groups[ k ];
  13602. const groupMaterial = material[ group.materialIndex ];
  13603. if ( groupMaterial && groupMaterial.visible ) {
  13604. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13605. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13606. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13607. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13608. }
  13609. }
  13610. } else if ( material.visible ) {
  13611. const depthMaterial = getDepthMaterial( object, material, light, type );
  13612. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13613. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13614. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13615. }
  13616. }
  13617. }
  13618. const children = object.children;
  13619. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13620. renderObject( children[ i ], camera, shadowCamera, light, type );
  13621. }
  13622. }
  13623. function onMaterialDispose( event ) {
  13624. const material = event.target;
  13625. material.removeEventListener( 'dispose', onMaterialDispose );
  13626. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13627. for ( const id in _materialCache ) {
  13628. const cache = _materialCache[ id ];
  13629. const uuid = event.target.uuid;
  13630. if ( uuid in cache ) {
  13631. const shadowMaterial = cache[ uuid ];
  13632. shadowMaterial.dispose();
  13633. delete cache[ uuid ];
  13634. }
  13635. }
  13636. }
  13637. }
  13638. function WebGLState( gl ) {
  13639. function ColorBuffer() {
  13640. let locked = false;
  13641. const color = new Vector4();
  13642. let currentColorMask = null;
  13643. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13644. return {
  13645. setMask: function ( colorMask ) {
  13646. if ( currentColorMask !== colorMask && ! locked ) {
  13647. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13648. currentColorMask = colorMask;
  13649. }
  13650. },
  13651. setLocked: function ( lock ) {
  13652. locked = lock;
  13653. },
  13654. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13655. if ( premultipliedAlpha === true ) {
  13656. r *= a; g *= a; b *= a;
  13657. }
  13658. color.set( r, g, b, a );
  13659. if ( currentColorClear.equals( color ) === false ) {
  13660. gl.clearColor( r, g, b, a );
  13661. currentColorClear.copy( color );
  13662. }
  13663. },
  13664. reset: function () {
  13665. locked = false;
  13666. currentColorMask = null;
  13667. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13668. }
  13669. };
  13670. }
  13671. function DepthBuffer() {
  13672. let locked = false;
  13673. let currentDepthMask = null;
  13674. let currentDepthFunc = null;
  13675. let currentDepthClear = null;
  13676. return {
  13677. setTest: function ( depthTest ) {
  13678. if ( depthTest ) {
  13679. enable( gl.DEPTH_TEST );
  13680. } else {
  13681. disable( gl.DEPTH_TEST );
  13682. }
  13683. },
  13684. setMask: function ( depthMask ) {
  13685. if ( currentDepthMask !== depthMask && ! locked ) {
  13686. gl.depthMask( depthMask );
  13687. currentDepthMask = depthMask;
  13688. }
  13689. },
  13690. setFunc: function ( depthFunc ) {
  13691. if ( currentDepthFunc !== depthFunc ) {
  13692. switch ( depthFunc ) {
  13693. case NeverDepth:
  13694. gl.depthFunc( gl.NEVER );
  13695. break;
  13696. case AlwaysDepth:
  13697. gl.depthFunc( gl.ALWAYS );
  13698. break;
  13699. case LessDepth:
  13700. gl.depthFunc( gl.LESS );
  13701. break;
  13702. case LessEqualDepth:
  13703. gl.depthFunc( gl.LEQUAL );
  13704. break;
  13705. case EqualDepth:
  13706. gl.depthFunc( gl.EQUAL );
  13707. break;
  13708. case GreaterEqualDepth:
  13709. gl.depthFunc( gl.GEQUAL );
  13710. break;
  13711. case GreaterDepth:
  13712. gl.depthFunc( gl.GREATER );
  13713. break;
  13714. case NotEqualDepth:
  13715. gl.depthFunc( gl.NOTEQUAL );
  13716. break;
  13717. default:
  13718. gl.depthFunc( gl.LEQUAL );
  13719. }
  13720. currentDepthFunc = depthFunc;
  13721. }
  13722. },
  13723. setLocked: function ( lock ) {
  13724. locked = lock;
  13725. },
  13726. setClear: function ( depth ) {
  13727. if ( currentDepthClear !== depth ) {
  13728. gl.clearDepth( depth );
  13729. currentDepthClear = depth;
  13730. }
  13731. },
  13732. reset: function () {
  13733. locked = false;
  13734. currentDepthMask = null;
  13735. currentDepthFunc = null;
  13736. currentDepthClear = null;
  13737. }
  13738. };
  13739. }
  13740. function StencilBuffer() {
  13741. let locked = false;
  13742. let currentStencilMask = null;
  13743. let currentStencilFunc = null;
  13744. let currentStencilRef = null;
  13745. let currentStencilFuncMask = null;
  13746. let currentStencilFail = null;
  13747. let currentStencilZFail = null;
  13748. let currentStencilZPass = null;
  13749. let currentStencilClear = null;
  13750. return {
  13751. setTest: function ( stencilTest ) {
  13752. if ( ! locked ) {
  13753. if ( stencilTest ) {
  13754. enable( gl.STENCIL_TEST );
  13755. } else {
  13756. disable( gl.STENCIL_TEST );
  13757. }
  13758. }
  13759. },
  13760. setMask: function ( stencilMask ) {
  13761. if ( currentStencilMask !== stencilMask && ! locked ) {
  13762. gl.stencilMask( stencilMask );
  13763. currentStencilMask = stencilMask;
  13764. }
  13765. },
  13766. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13767. if ( currentStencilFunc !== stencilFunc ||
  13768. currentStencilRef !== stencilRef ||
  13769. currentStencilFuncMask !== stencilMask ) {
  13770. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13771. currentStencilFunc = stencilFunc;
  13772. currentStencilRef = stencilRef;
  13773. currentStencilFuncMask = stencilMask;
  13774. }
  13775. },
  13776. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13777. if ( currentStencilFail !== stencilFail ||
  13778. currentStencilZFail !== stencilZFail ||
  13779. currentStencilZPass !== stencilZPass ) {
  13780. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13781. currentStencilFail = stencilFail;
  13782. currentStencilZFail = stencilZFail;
  13783. currentStencilZPass = stencilZPass;
  13784. }
  13785. },
  13786. setLocked: function ( lock ) {
  13787. locked = lock;
  13788. },
  13789. setClear: function ( stencil ) {
  13790. if ( currentStencilClear !== stencil ) {
  13791. gl.clearStencil( stencil );
  13792. currentStencilClear = stencil;
  13793. }
  13794. },
  13795. reset: function () {
  13796. locked = false;
  13797. currentStencilMask = null;
  13798. currentStencilFunc = null;
  13799. currentStencilRef = null;
  13800. currentStencilFuncMask = null;
  13801. currentStencilFail = null;
  13802. currentStencilZFail = null;
  13803. currentStencilZPass = null;
  13804. currentStencilClear = null;
  13805. }
  13806. };
  13807. }
  13808. //
  13809. const colorBuffer = new ColorBuffer();
  13810. const depthBuffer = new DepthBuffer();
  13811. const stencilBuffer = new StencilBuffer();
  13812. const uboBindings = new WeakMap();
  13813. const uboProgramMap = new WeakMap();
  13814. let enabledCapabilities = {};
  13815. let currentBoundFramebuffers = {};
  13816. let currentDrawbuffers = new WeakMap();
  13817. let defaultDrawbuffers = [];
  13818. let currentProgram = null;
  13819. let currentBlendingEnabled = false;
  13820. let currentBlending = null;
  13821. let currentBlendEquation = null;
  13822. let currentBlendSrc = null;
  13823. let currentBlendDst = null;
  13824. let currentBlendEquationAlpha = null;
  13825. let currentBlendSrcAlpha = null;
  13826. let currentBlendDstAlpha = null;
  13827. let currentBlendColor = new Color( 0, 0, 0 );
  13828. let currentBlendAlpha = 0;
  13829. let currentPremultipledAlpha = false;
  13830. let currentFlipSided = null;
  13831. let currentCullFace = null;
  13832. let currentLineWidth = null;
  13833. let currentPolygonOffsetFactor = null;
  13834. let currentPolygonOffsetUnits = null;
  13835. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13836. let lineWidthAvailable = false;
  13837. let version = 0;
  13838. const glVersion = gl.getParameter( gl.VERSION );
  13839. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13840. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13841. lineWidthAvailable = ( version >= 1.0 );
  13842. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13843. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13844. lineWidthAvailable = ( version >= 2.0 );
  13845. }
  13846. let currentTextureSlot = null;
  13847. let currentBoundTextures = {};
  13848. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13849. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13850. const currentScissor = new Vector4().fromArray( scissorParam );
  13851. const currentViewport = new Vector4().fromArray( viewportParam );
  13852. function createTexture( type, target, count, dimensions ) {
  13853. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13854. const texture = gl.createTexture();
  13855. gl.bindTexture( type, texture );
  13856. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13857. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13858. for ( let i = 0; i < count; i ++ ) {
  13859. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  13860. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13861. } else {
  13862. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13863. }
  13864. }
  13865. return texture;
  13866. }
  13867. const emptyTextures = {};
  13868. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13869. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13870. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13871. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13872. // init
  13873. colorBuffer.setClear( 0, 0, 0, 1 );
  13874. depthBuffer.setClear( 1 );
  13875. stencilBuffer.setClear( 0 );
  13876. enable( gl.DEPTH_TEST );
  13877. depthBuffer.setFunc( LessEqualDepth );
  13878. setFlipSided( false );
  13879. setCullFace( CullFaceBack );
  13880. enable( gl.CULL_FACE );
  13881. setBlending( NoBlending );
  13882. //
  13883. function enable( id ) {
  13884. if ( enabledCapabilities[ id ] !== true ) {
  13885. gl.enable( id );
  13886. enabledCapabilities[ id ] = true;
  13887. }
  13888. }
  13889. function disable( id ) {
  13890. if ( enabledCapabilities[ id ] !== false ) {
  13891. gl.disable( id );
  13892. enabledCapabilities[ id ] = false;
  13893. }
  13894. }
  13895. function bindFramebuffer( target, framebuffer ) {
  13896. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13897. gl.bindFramebuffer( target, framebuffer );
  13898. currentBoundFramebuffers[ target ] = framebuffer;
  13899. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13900. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13901. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13902. }
  13903. if ( target === gl.FRAMEBUFFER ) {
  13904. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13905. }
  13906. return true;
  13907. }
  13908. return false;
  13909. }
  13910. function drawBuffers( renderTarget, framebuffer ) {
  13911. let drawBuffers = defaultDrawbuffers;
  13912. let needsUpdate = false;
  13913. if ( renderTarget ) {
  13914. drawBuffers = currentDrawbuffers.get( framebuffer );
  13915. if ( drawBuffers === undefined ) {
  13916. drawBuffers = [];
  13917. currentDrawbuffers.set( framebuffer, drawBuffers );
  13918. }
  13919. const textures = renderTarget.textures;
  13920. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13921. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13922. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13923. }
  13924. drawBuffers.length = textures.length;
  13925. needsUpdate = true;
  13926. }
  13927. } else {
  13928. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13929. drawBuffers[ 0 ] = gl.BACK;
  13930. needsUpdate = true;
  13931. }
  13932. }
  13933. if ( needsUpdate ) {
  13934. gl.drawBuffers( drawBuffers );
  13935. }
  13936. }
  13937. function useProgram( program ) {
  13938. if ( currentProgram !== program ) {
  13939. gl.useProgram( program );
  13940. currentProgram = program;
  13941. return true;
  13942. }
  13943. return false;
  13944. }
  13945. const equationToGL = {
  13946. [ AddEquation ]: gl.FUNC_ADD,
  13947. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13948. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13949. };
  13950. equationToGL[ MinEquation ] = gl.MIN;
  13951. equationToGL[ MaxEquation ] = gl.MAX;
  13952. const factorToGL = {
  13953. [ ZeroFactor ]: gl.ZERO,
  13954. [ OneFactor ]: gl.ONE,
  13955. [ SrcColorFactor ]: gl.SRC_COLOR,
  13956. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13957. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13958. [ DstColorFactor ]: gl.DST_COLOR,
  13959. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13960. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13961. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13962. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13963. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  13964. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  13965. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  13966. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  13967. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  13968. };
  13969. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  13970. if ( blending === NoBlending ) {
  13971. if ( currentBlendingEnabled === true ) {
  13972. disable( gl.BLEND );
  13973. currentBlendingEnabled = false;
  13974. }
  13975. return;
  13976. }
  13977. if ( currentBlendingEnabled === false ) {
  13978. enable( gl.BLEND );
  13979. currentBlendingEnabled = true;
  13980. }
  13981. if ( blending !== CustomBlending ) {
  13982. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13983. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13984. gl.blendEquation( gl.FUNC_ADD );
  13985. currentBlendEquation = AddEquation;
  13986. currentBlendEquationAlpha = AddEquation;
  13987. }
  13988. if ( premultipliedAlpha ) {
  13989. switch ( blending ) {
  13990. case NormalBlending:
  13991. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13992. break;
  13993. case AdditiveBlending:
  13994. gl.blendFunc( gl.ONE, gl.ONE );
  13995. break;
  13996. case SubtractiveBlending:
  13997. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13998. break;
  13999. case MultiplyBlending:
  14000. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  14001. break;
  14002. default:
  14003. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14004. break;
  14005. }
  14006. } else {
  14007. switch ( blending ) {
  14008. case NormalBlending:
  14009. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14010. break;
  14011. case AdditiveBlending:
  14012. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14013. break;
  14014. case SubtractiveBlending:
  14015. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14016. break;
  14017. case MultiplyBlending:
  14018. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14019. break;
  14020. default:
  14021. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14022. break;
  14023. }
  14024. }
  14025. currentBlendSrc = null;
  14026. currentBlendDst = null;
  14027. currentBlendSrcAlpha = null;
  14028. currentBlendDstAlpha = null;
  14029. currentBlendColor.set( 0, 0, 0 );
  14030. currentBlendAlpha = 0;
  14031. currentBlending = blending;
  14032. currentPremultipledAlpha = premultipliedAlpha;
  14033. }
  14034. return;
  14035. }
  14036. // custom blending
  14037. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14038. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14039. blendDstAlpha = blendDstAlpha || blendDst;
  14040. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14041. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  14042. currentBlendEquation = blendEquation;
  14043. currentBlendEquationAlpha = blendEquationAlpha;
  14044. }
  14045. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14046. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  14047. currentBlendSrc = blendSrc;
  14048. currentBlendDst = blendDst;
  14049. currentBlendSrcAlpha = blendSrcAlpha;
  14050. currentBlendDstAlpha = blendDstAlpha;
  14051. }
  14052. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  14053. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  14054. currentBlendColor.copy( blendColor );
  14055. currentBlendAlpha = blendAlpha;
  14056. }
  14057. currentBlending = blending;
  14058. currentPremultipledAlpha = false;
  14059. }
  14060. function setMaterial( material, frontFaceCW ) {
  14061. material.side === DoubleSide
  14062. ? disable( gl.CULL_FACE )
  14063. : enable( gl.CULL_FACE );
  14064. let flipSided = ( material.side === BackSide );
  14065. if ( frontFaceCW ) flipSided = ! flipSided;
  14066. setFlipSided( flipSided );
  14067. ( material.blending === NormalBlending && material.transparent === false )
  14068. ? setBlending( NoBlending )
  14069. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  14070. depthBuffer.setFunc( material.depthFunc );
  14071. depthBuffer.setTest( material.depthTest );
  14072. depthBuffer.setMask( material.depthWrite );
  14073. colorBuffer.setMask( material.colorWrite );
  14074. const stencilWrite = material.stencilWrite;
  14075. stencilBuffer.setTest( stencilWrite );
  14076. if ( stencilWrite ) {
  14077. stencilBuffer.setMask( material.stencilWriteMask );
  14078. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  14079. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  14080. }
  14081. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14082. material.alphaToCoverage === true
  14083. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  14084. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14085. }
  14086. //
  14087. function setFlipSided( flipSided ) {
  14088. if ( currentFlipSided !== flipSided ) {
  14089. if ( flipSided ) {
  14090. gl.frontFace( gl.CW );
  14091. } else {
  14092. gl.frontFace( gl.CCW );
  14093. }
  14094. currentFlipSided = flipSided;
  14095. }
  14096. }
  14097. function setCullFace( cullFace ) {
  14098. if ( cullFace !== CullFaceNone ) {
  14099. enable( gl.CULL_FACE );
  14100. if ( cullFace !== currentCullFace ) {
  14101. if ( cullFace === CullFaceBack ) {
  14102. gl.cullFace( gl.BACK );
  14103. } else if ( cullFace === CullFaceFront ) {
  14104. gl.cullFace( gl.FRONT );
  14105. } else {
  14106. gl.cullFace( gl.FRONT_AND_BACK );
  14107. }
  14108. }
  14109. } else {
  14110. disable( gl.CULL_FACE );
  14111. }
  14112. currentCullFace = cullFace;
  14113. }
  14114. function setLineWidth( width ) {
  14115. if ( width !== currentLineWidth ) {
  14116. if ( lineWidthAvailable ) gl.lineWidth( width );
  14117. currentLineWidth = width;
  14118. }
  14119. }
  14120. function setPolygonOffset( polygonOffset, factor, units ) {
  14121. if ( polygonOffset ) {
  14122. enable( gl.POLYGON_OFFSET_FILL );
  14123. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14124. gl.polygonOffset( factor, units );
  14125. currentPolygonOffsetFactor = factor;
  14126. currentPolygonOffsetUnits = units;
  14127. }
  14128. } else {
  14129. disable( gl.POLYGON_OFFSET_FILL );
  14130. }
  14131. }
  14132. function setScissorTest( scissorTest ) {
  14133. if ( scissorTest ) {
  14134. enable( gl.SCISSOR_TEST );
  14135. } else {
  14136. disable( gl.SCISSOR_TEST );
  14137. }
  14138. }
  14139. // texture
  14140. function activeTexture( webglSlot ) {
  14141. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14142. if ( currentTextureSlot !== webglSlot ) {
  14143. gl.activeTexture( webglSlot );
  14144. currentTextureSlot = webglSlot;
  14145. }
  14146. }
  14147. function bindTexture( webglType, webglTexture, webglSlot ) {
  14148. if ( webglSlot === undefined ) {
  14149. if ( currentTextureSlot === null ) {
  14150. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14151. } else {
  14152. webglSlot = currentTextureSlot;
  14153. }
  14154. }
  14155. let boundTexture = currentBoundTextures[ webglSlot ];
  14156. if ( boundTexture === undefined ) {
  14157. boundTexture = { type: undefined, texture: undefined };
  14158. currentBoundTextures[ webglSlot ] = boundTexture;
  14159. }
  14160. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14161. if ( currentTextureSlot !== webglSlot ) {
  14162. gl.activeTexture( webglSlot );
  14163. currentTextureSlot = webglSlot;
  14164. }
  14165. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14166. boundTexture.type = webglType;
  14167. boundTexture.texture = webglTexture;
  14168. }
  14169. }
  14170. function unbindTexture() {
  14171. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14172. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14173. gl.bindTexture( boundTexture.type, null );
  14174. boundTexture.type = undefined;
  14175. boundTexture.texture = undefined;
  14176. }
  14177. }
  14178. function compressedTexImage2D() {
  14179. try {
  14180. gl.compressedTexImage2D.apply( gl, arguments );
  14181. } catch ( error ) {
  14182. console.error( 'THREE.WebGLState:', error );
  14183. }
  14184. }
  14185. function compressedTexImage3D() {
  14186. try {
  14187. gl.compressedTexImage3D.apply( gl, arguments );
  14188. } catch ( error ) {
  14189. console.error( 'THREE.WebGLState:', error );
  14190. }
  14191. }
  14192. function texSubImage2D() {
  14193. try {
  14194. gl.texSubImage2D.apply( gl, arguments );
  14195. } catch ( error ) {
  14196. console.error( 'THREE.WebGLState:', error );
  14197. }
  14198. }
  14199. function texSubImage3D() {
  14200. try {
  14201. gl.texSubImage3D.apply( gl, arguments );
  14202. } catch ( error ) {
  14203. console.error( 'THREE.WebGLState:', error );
  14204. }
  14205. }
  14206. function compressedTexSubImage2D() {
  14207. try {
  14208. gl.compressedTexSubImage2D.apply( gl, arguments );
  14209. } catch ( error ) {
  14210. console.error( 'THREE.WebGLState:', error );
  14211. }
  14212. }
  14213. function compressedTexSubImage3D() {
  14214. try {
  14215. gl.compressedTexSubImage3D.apply( gl, arguments );
  14216. } catch ( error ) {
  14217. console.error( 'THREE.WebGLState:', error );
  14218. }
  14219. }
  14220. function texStorage2D() {
  14221. try {
  14222. gl.texStorage2D.apply( gl, arguments );
  14223. } catch ( error ) {
  14224. console.error( 'THREE.WebGLState:', error );
  14225. }
  14226. }
  14227. function texStorage3D() {
  14228. try {
  14229. gl.texStorage3D.apply( gl, arguments );
  14230. } catch ( error ) {
  14231. console.error( 'THREE.WebGLState:', error );
  14232. }
  14233. }
  14234. function texImage2D() {
  14235. try {
  14236. gl.texImage2D.apply( gl, arguments );
  14237. } catch ( error ) {
  14238. console.error( 'THREE.WebGLState:', error );
  14239. }
  14240. }
  14241. function texImage3D() {
  14242. try {
  14243. gl.texImage3D.apply( gl, arguments );
  14244. } catch ( error ) {
  14245. console.error( 'THREE.WebGLState:', error );
  14246. }
  14247. }
  14248. //
  14249. function scissor( scissor ) {
  14250. if ( currentScissor.equals( scissor ) === false ) {
  14251. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14252. currentScissor.copy( scissor );
  14253. }
  14254. }
  14255. function viewport( viewport ) {
  14256. if ( currentViewport.equals( viewport ) === false ) {
  14257. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14258. currentViewport.copy( viewport );
  14259. }
  14260. }
  14261. function updateUBOMapping( uniformsGroup, program ) {
  14262. let mapping = uboProgramMap.get( program );
  14263. if ( mapping === undefined ) {
  14264. mapping = new WeakMap();
  14265. uboProgramMap.set( program, mapping );
  14266. }
  14267. let blockIndex = mapping.get( uniformsGroup );
  14268. if ( blockIndex === undefined ) {
  14269. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14270. mapping.set( uniformsGroup, blockIndex );
  14271. }
  14272. }
  14273. function uniformBlockBinding( uniformsGroup, program ) {
  14274. const mapping = uboProgramMap.get( program );
  14275. const blockIndex = mapping.get( uniformsGroup );
  14276. if ( uboBindings.get( program ) !== blockIndex ) {
  14277. // bind shader specific block index to global block point
  14278. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14279. uboBindings.set( program, blockIndex );
  14280. }
  14281. }
  14282. //
  14283. function reset() {
  14284. // reset state
  14285. gl.disable( gl.BLEND );
  14286. gl.disable( gl.CULL_FACE );
  14287. gl.disable( gl.DEPTH_TEST );
  14288. gl.disable( gl.POLYGON_OFFSET_FILL );
  14289. gl.disable( gl.SCISSOR_TEST );
  14290. gl.disable( gl.STENCIL_TEST );
  14291. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14292. gl.blendEquation( gl.FUNC_ADD );
  14293. gl.blendFunc( gl.ONE, gl.ZERO );
  14294. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14295. gl.blendColor( 0, 0, 0, 0 );
  14296. gl.colorMask( true, true, true, true );
  14297. gl.clearColor( 0, 0, 0, 0 );
  14298. gl.depthMask( true );
  14299. gl.depthFunc( gl.LESS );
  14300. gl.clearDepth( 1 );
  14301. gl.stencilMask( 0xffffffff );
  14302. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14303. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14304. gl.clearStencil( 0 );
  14305. gl.cullFace( gl.BACK );
  14306. gl.frontFace( gl.CCW );
  14307. gl.polygonOffset( 0, 0 );
  14308. gl.activeTexture( gl.TEXTURE0 );
  14309. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14310. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14311. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14312. gl.useProgram( null );
  14313. gl.lineWidth( 1 );
  14314. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14315. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14316. // reset internals
  14317. enabledCapabilities = {};
  14318. currentTextureSlot = null;
  14319. currentBoundTextures = {};
  14320. currentBoundFramebuffers = {};
  14321. currentDrawbuffers = new WeakMap();
  14322. defaultDrawbuffers = [];
  14323. currentProgram = null;
  14324. currentBlendingEnabled = false;
  14325. currentBlending = null;
  14326. currentBlendEquation = null;
  14327. currentBlendSrc = null;
  14328. currentBlendDst = null;
  14329. currentBlendEquationAlpha = null;
  14330. currentBlendSrcAlpha = null;
  14331. currentBlendDstAlpha = null;
  14332. currentBlendColor = new Color( 0, 0, 0 );
  14333. currentBlendAlpha = 0;
  14334. currentPremultipledAlpha = false;
  14335. currentFlipSided = null;
  14336. currentCullFace = null;
  14337. currentLineWidth = null;
  14338. currentPolygonOffsetFactor = null;
  14339. currentPolygonOffsetUnits = null;
  14340. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14341. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14342. colorBuffer.reset();
  14343. depthBuffer.reset();
  14344. stencilBuffer.reset();
  14345. }
  14346. return {
  14347. buffers: {
  14348. color: colorBuffer,
  14349. depth: depthBuffer,
  14350. stencil: stencilBuffer
  14351. },
  14352. enable: enable,
  14353. disable: disable,
  14354. bindFramebuffer: bindFramebuffer,
  14355. drawBuffers: drawBuffers,
  14356. useProgram: useProgram,
  14357. setBlending: setBlending,
  14358. setMaterial: setMaterial,
  14359. setFlipSided: setFlipSided,
  14360. setCullFace: setCullFace,
  14361. setLineWidth: setLineWidth,
  14362. setPolygonOffset: setPolygonOffset,
  14363. setScissorTest: setScissorTest,
  14364. activeTexture: activeTexture,
  14365. bindTexture: bindTexture,
  14366. unbindTexture: unbindTexture,
  14367. compressedTexImage2D: compressedTexImage2D,
  14368. compressedTexImage3D: compressedTexImage3D,
  14369. texImage2D: texImage2D,
  14370. texImage3D: texImage3D,
  14371. updateUBOMapping: updateUBOMapping,
  14372. uniformBlockBinding: uniformBlockBinding,
  14373. texStorage2D: texStorage2D,
  14374. texStorage3D: texStorage3D,
  14375. texSubImage2D: texSubImage2D,
  14376. texSubImage3D: texSubImage3D,
  14377. compressedTexSubImage2D: compressedTexSubImage2D,
  14378. compressedTexSubImage3D: compressedTexSubImage3D,
  14379. scissor: scissor,
  14380. viewport: viewport,
  14381. reset: reset
  14382. };
  14383. }
  14384. function contain( texture, aspect ) {
  14385. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  14386. if ( imageAspect > aspect ) {
  14387. texture.repeat.x = 1;
  14388. texture.repeat.y = imageAspect / aspect;
  14389. texture.offset.x = 0;
  14390. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  14391. } else {
  14392. texture.repeat.x = aspect / imageAspect;
  14393. texture.repeat.y = 1;
  14394. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  14395. texture.offset.y = 0;
  14396. }
  14397. return texture;
  14398. }
  14399. function cover( texture, aspect ) {
  14400. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  14401. if ( imageAspect > aspect ) {
  14402. texture.repeat.x = aspect / imageAspect;
  14403. texture.repeat.y = 1;
  14404. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  14405. texture.offset.y = 0;
  14406. } else {
  14407. texture.repeat.x = 1;
  14408. texture.repeat.y = imageAspect / aspect;
  14409. texture.offset.x = 0;
  14410. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  14411. }
  14412. return texture;
  14413. }
  14414. function fill( texture ) {
  14415. texture.repeat.x = 1;
  14416. texture.repeat.y = 1;
  14417. texture.offset.x = 0;
  14418. texture.offset.y = 0;
  14419. return texture;
  14420. }
  14421. /**
  14422. * Given the width, height, format, and type of a texture. Determines how many
  14423. * bytes must be used to represent the texture.
  14424. */
  14425. function getByteLength( width, height, format, type ) {
  14426. const typeByteLength = getTextureTypeByteLength( type );
  14427. switch ( format ) {
  14428. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  14429. case AlphaFormat:
  14430. return width * height;
  14431. case LuminanceFormat:
  14432. return width * height;
  14433. case LuminanceAlphaFormat:
  14434. return width * height * 2;
  14435. case RedFormat:
  14436. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  14437. case RedIntegerFormat:
  14438. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  14439. case RGFormat:
  14440. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14441. case RGIntegerFormat:
  14442. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14443. case RGBFormat:
  14444. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14445. case RGBAFormat:
  14446. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14447. case RGBAIntegerFormat:
  14448. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14449. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  14450. case RGB_S3TC_DXT1_Format:
  14451. case RGBA_S3TC_DXT1_Format:
  14452. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  14453. case RGBA_S3TC_DXT3_Format:
  14454. case RGBA_S3TC_DXT5_Format:
  14455. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14456. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  14457. case RGB_PVRTC_2BPPV1_Format:
  14458. case RGBA_PVRTC_2BPPV1_Format:
  14459. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  14460. case RGB_PVRTC_4BPPV1_Format:
  14461. case RGBA_PVRTC_4BPPV1_Format:
  14462. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  14463. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  14464. case RGB_ETC1_Format:
  14465. case RGB_ETC2_Format:
  14466. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  14467. case RGBA_ETC2_EAC_Format:
  14468. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14469. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  14470. case RGBA_ASTC_4x4_Format:
  14471. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14472. case RGBA_ASTC_5x4_Format:
  14473. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14474. case RGBA_ASTC_5x5_Format:
  14475. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14476. case RGBA_ASTC_6x5_Format:
  14477. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14478. case RGBA_ASTC_6x6_Format:
  14479. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  14480. case RGBA_ASTC_8x5_Format:
  14481. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14482. case RGBA_ASTC_8x6_Format:
  14483. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  14484. case RGBA_ASTC_8x8_Format:
  14485. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  14486. case RGBA_ASTC_10x5_Format:
  14487. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14488. case RGBA_ASTC_10x6_Format:
  14489. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  14490. case RGBA_ASTC_10x8_Format:
  14491. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  14492. case RGBA_ASTC_10x10_Format:
  14493. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  14494. case RGBA_ASTC_12x10_Format:
  14495. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  14496. case RGBA_ASTC_12x12_Format:
  14497. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  14498. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  14499. case RGBA_BPTC_Format:
  14500. case RGB_BPTC_SIGNED_Format:
  14501. case RGB_BPTC_UNSIGNED_Format:
  14502. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  14503. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  14504. case RED_RGTC1_Format:
  14505. case SIGNED_RED_RGTC1_Format:
  14506. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  14507. case RED_GREEN_RGTC2_Format:
  14508. case SIGNED_RED_GREEN_RGTC2_Format:
  14509. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  14510. }
  14511. throw new Error(
  14512. `Unable to determine texture byte length for ${format} format.`,
  14513. );
  14514. }
  14515. function getTextureTypeByteLength( type ) {
  14516. switch ( type ) {
  14517. case UnsignedByteType:
  14518. case ByteType:
  14519. return { byteLength: 1, components: 1 };
  14520. case UnsignedShortType:
  14521. case ShortType:
  14522. case HalfFloatType:
  14523. return { byteLength: 2, components: 1 };
  14524. case UnsignedShort4444Type:
  14525. case UnsignedShort5551Type:
  14526. return { byteLength: 2, components: 4 };
  14527. case UnsignedIntType:
  14528. case IntType:
  14529. case FloatType:
  14530. return { byteLength: 4, components: 1 };
  14531. case UnsignedInt5999Type:
  14532. return { byteLength: 4, components: 3 };
  14533. }
  14534. throw new Error( `Unknown texture type ${type}.` );
  14535. }
  14536. const TextureUtils = {
  14537. contain,
  14538. cover,
  14539. fill,
  14540. getByteLength
  14541. };
  14542. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14543. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14544. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14545. const _imageDimensions = new Vector2();
  14546. const _videoTextures = new WeakMap();
  14547. let _canvas;
  14548. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14549. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14550. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14551. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14552. let useOffscreenCanvas = false;
  14553. try {
  14554. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14555. // eslint-disable-next-line compat/compat
  14556. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14557. } catch ( err ) {
  14558. // Ignore any errors
  14559. }
  14560. function createCanvas( width, height ) {
  14561. // Use OffscreenCanvas when available. Specially needed in web workers
  14562. return useOffscreenCanvas ?
  14563. // eslint-disable-next-line compat/compat
  14564. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14565. }
  14566. function resizeImage( image, needsNewCanvas, maxSize ) {
  14567. let scale = 1;
  14568. const dimensions = getDimensions( image );
  14569. // handle case if texture exceeds max size
  14570. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  14571. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  14572. }
  14573. // only perform resize if necessary
  14574. if ( scale < 1 ) {
  14575. // only perform resize for certain image types
  14576. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14577. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14578. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  14579. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  14580. const width = Math.floor( scale * dimensions.width );
  14581. const height = Math.floor( scale * dimensions.height );
  14582. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14583. // cube textures can't reuse the same canvas
  14584. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14585. canvas.width = width;
  14586. canvas.height = height;
  14587. const context = canvas.getContext( '2d' );
  14588. context.drawImage( image, 0, 0, width, height );
  14589. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  14590. return canvas;
  14591. } else {
  14592. if ( 'data' in image ) {
  14593. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  14594. }
  14595. return image;
  14596. }
  14597. }
  14598. return image;
  14599. }
  14600. function textureNeedsGenerateMipmaps( texture ) {
  14601. return texture.generateMipmaps && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14602. }
  14603. function generateMipmap( target ) {
  14604. _gl.generateMipmap( target );
  14605. }
  14606. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14607. if ( internalFormatName !== null ) {
  14608. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14609. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14610. }
  14611. let internalFormat = glFormat;
  14612. if ( glFormat === _gl.RED ) {
  14613. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14614. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14615. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14616. }
  14617. if ( glFormat === _gl.RED_INTEGER ) {
  14618. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14619. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14620. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14621. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14622. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14623. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14624. }
  14625. if ( glFormat === _gl.RG ) {
  14626. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14627. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14628. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14629. }
  14630. if ( glFormat === _gl.RG_INTEGER ) {
  14631. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  14632. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  14633. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  14634. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  14635. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  14636. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  14637. }
  14638. if ( glFormat === _gl.RGB ) {
  14639. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  14640. }
  14641. if ( glFormat === _gl.RGBA ) {
  14642. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14643. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14644. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14645. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14646. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14647. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14648. }
  14649. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14650. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14651. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14652. extensions.get( 'EXT_color_buffer_float' );
  14653. }
  14654. return internalFormat;
  14655. }
  14656. function getInternalDepthFormat( useStencil, depthType ) {
  14657. let glInternalFormat;
  14658. if ( useStencil ) {
  14659. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  14660. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14661. } else if ( depthType === FloatType ) {
  14662. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  14663. } else if ( depthType === UnsignedShortType ) {
  14664. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14665. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  14666. }
  14667. } else {
  14668. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  14669. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14670. } else if ( depthType === FloatType ) {
  14671. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14672. } else if ( depthType === UnsignedShortType ) {
  14673. glInternalFormat = _gl.DEPTH_COMPONENT16;
  14674. }
  14675. }
  14676. return glInternalFormat;
  14677. }
  14678. function getMipLevels( texture, image ) {
  14679. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14680. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14681. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14682. // user-defined mipmaps
  14683. return texture.mipmaps.length;
  14684. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14685. return image.mipmaps.length;
  14686. } else {
  14687. // texture without mipmaps (only base level)
  14688. return 1;
  14689. }
  14690. }
  14691. //
  14692. function onTextureDispose( event ) {
  14693. const texture = event.target;
  14694. texture.removeEventListener( 'dispose', onTextureDispose );
  14695. deallocateTexture( texture );
  14696. if ( texture.isVideoTexture ) {
  14697. _videoTextures.delete( texture );
  14698. }
  14699. }
  14700. function onRenderTargetDispose( event ) {
  14701. const renderTarget = event.target;
  14702. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14703. deallocateRenderTarget( renderTarget );
  14704. }
  14705. //
  14706. function deallocateTexture( texture ) {
  14707. const textureProperties = properties.get( texture );
  14708. if ( textureProperties.__webglInit === undefined ) return;
  14709. // check if it's necessary to remove the WebGLTexture object
  14710. const source = texture.source;
  14711. const webglTextures = _sources.get( source );
  14712. if ( webglTextures ) {
  14713. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14714. webglTexture.usedTimes --;
  14715. // the WebGLTexture object is not used anymore, remove it
  14716. if ( webglTexture.usedTimes === 0 ) {
  14717. deleteTexture( texture );
  14718. }
  14719. // remove the weak map entry if no WebGLTexture uses the source anymore
  14720. if ( Object.keys( webglTextures ).length === 0 ) {
  14721. _sources.delete( source );
  14722. }
  14723. }
  14724. properties.remove( texture );
  14725. }
  14726. function deleteTexture( texture ) {
  14727. const textureProperties = properties.get( texture );
  14728. _gl.deleteTexture( textureProperties.__webglTexture );
  14729. const source = texture.source;
  14730. const webglTextures = _sources.get( source );
  14731. delete webglTextures[ textureProperties.__cacheKey ];
  14732. info.memory.textures --;
  14733. }
  14734. function deallocateRenderTarget( renderTarget ) {
  14735. const renderTargetProperties = properties.get( renderTarget );
  14736. if ( renderTarget.depthTexture ) {
  14737. renderTarget.depthTexture.dispose();
  14738. }
  14739. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14740. for ( let i = 0; i < 6; i ++ ) {
  14741. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14742. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14743. } else {
  14744. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14745. }
  14746. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14747. }
  14748. } else {
  14749. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14750. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14751. } else {
  14752. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14753. }
  14754. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14755. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14756. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14757. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14758. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14759. }
  14760. }
  14761. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14762. }
  14763. const textures = renderTarget.textures;
  14764. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14765. const attachmentProperties = properties.get( textures[ i ] );
  14766. if ( attachmentProperties.__webglTexture ) {
  14767. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14768. info.memory.textures --;
  14769. }
  14770. properties.remove( textures[ i ] );
  14771. }
  14772. properties.remove( renderTarget );
  14773. }
  14774. //
  14775. let textureUnits = 0;
  14776. function resetTextureUnits() {
  14777. textureUnits = 0;
  14778. }
  14779. function allocateTextureUnit() {
  14780. const textureUnit = textureUnits;
  14781. if ( textureUnit >= capabilities.maxTextures ) {
  14782. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14783. }
  14784. textureUnits += 1;
  14785. return textureUnit;
  14786. }
  14787. function getTextureCacheKey( texture ) {
  14788. const array = [];
  14789. array.push( texture.wrapS );
  14790. array.push( texture.wrapT );
  14791. array.push( texture.wrapR || 0 );
  14792. array.push( texture.magFilter );
  14793. array.push( texture.minFilter );
  14794. array.push( texture.anisotropy );
  14795. array.push( texture.internalFormat );
  14796. array.push( texture.format );
  14797. array.push( texture.type );
  14798. array.push( texture.generateMipmaps );
  14799. array.push( texture.premultiplyAlpha );
  14800. array.push( texture.flipY );
  14801. array.push( texture.unpackAlignment );
  14802. array.push( texture.colorSpace );
  14803. return array.join();
  14804. }
  14805. //
  14806. function setTexture2D( texture, slot ) {
  14807. const textureProperties = properties.get( texture );
  14808. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14809. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14810. const image = texture.image;
  14811. if ( image === null ) {
  14812. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14813. } else if ( image.complete === false ) {
  14814. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14815. } else {
  14816. uploadTexture( textureProperties, texture, slot );
  14817. return;
  14818. }
  14819. }
  14820. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14821. }
  14822. function setTexture2DArray( texture, slot ) {
  14823. const textureProperties = properties.get( texture );
  14824. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14825. uploadTexture( textureProperties, texture, slot );
  14826. return;
  14827. }
  14828. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14829. }
  14830. function setTexture3D( texture, slot ) {
  14831. const textureProperties = properties.get( texture );
  14832. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14833. uploadTexture( textureProperties, texture, slot );
  14834. return;
  14835. }
  14836. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14837. }
  14838. function setTextureCube( texture, slot ) {
  14839. const textureProperties = properties.get( texture );
  14840. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14841. uploadCubeTexture( textureProperties, texture, slot );
  14842. return;
  14843. }
  14844. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14845. }
  14846. const wrappingToGL = {
  14847. [ RepeatWrapping ]: _gl.REPEAT,
  14848. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14849. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14850. };
  14851. const filterToGL = {
  14852. [ NearestFilter ]: _gl.NEAREST,
  14853. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14854. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14855. [ LinearFilter ]: _gl.LINEAR,
  14856. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14857. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14858. };
  14859. const compareToGL = {
  14860. [ NeverCompare ]: _gl.NEVER,
  14861. [ AlwaysCompare ]: _gl.ALWAYS,
  14862. [ LessCompare ]: _gl.LESS,
  14863. [ LessEqualCompare ]: _gl.LEQUAL,
  14864. [ EqualCompare ]: _gl.EQUAL,
  14865. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14866. [ GreaterCompare ]: _gl.GREATER,
  14867. [ NotEqualCompare ]: _gl.NOTEQUAL
  14868. };
  14869. function setTextureParameters( textureType, texture ) {
  14870. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  14871. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14872. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  14873. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  14874. }
  14875. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14876. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14877. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14878. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14879. }
  14880. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14881. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14882. if ( texture.compareFunction ) {
  14883. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14884. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14885. }
  14886. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14887. if ( texture.magFilter === NearestFilter ) return;
  14888. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14889. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  14890. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14891. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14892. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14893. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14894. }
  14895. }
  14896. }
  14897. function initTexture( textureProperties, texture ) {
  14898. let forceUpload = false;
  14899. if ( textureProperties.__webglInit === undefined ) {
  14900. textureProperties.__webglInit = true;
  14901. texture.addEventListener( 'dispose', onTextureDispose );
  14902. }
  14903. // create Source <-> WebGLTextures mapping if necessary
  14904. const source = texture.source;
  14905. let webglTextures = _sources.get( source );
  14906. if ( webglTextures === undefined ) {
  14907. webglTextures = {};
  14908. _sources.set( source, webglTextures );
  14909. }
  14910. // check if there is already a WebGLTexture object for the given texture parameters
  14911. const textureCacheKey = getTextureCacheKey( texture );
  14912. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14913. // if not, create a new instance of WebGLTexture
  14914. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14915. // create new entry
  14916. webglTextures[ textureCacheKey ] = {
  14917. texture: _gl.createTexture(),
  14918. usedTimes: 0
  14919. };
  14920. info.memory.textures ++;
  14921. // when a new instance of WebGLTexture was created, a texture upload is required
  14922. // even if the image contents are identical
  14923. forceUpload = true;
  14924. }
  14925. webglTextures[ textureCacheKey ].usedTimes ++;
  14926. // every time the texture cache key changes, it's necessary to check if an instance of
  14927. // WebGLTexture can be deleted in order to avoid a memory leak.
  14928. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14929. if ( webglTexture !== undefined ) {
  14930. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14931. if ( webglTexture.usedTimes === 0 ) {
  14932. deleteTexture( texture );
  14933. }
  14934. }
  14935. // store references to cache key and WebGLTexture object
  14936. textureProperties.__cacheKey = textureCacheKey;
  14937. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14938. }
  14939. return forceUpload;
  14940. }
  14941. function uploadTexture( textureProperties, texture, slot ) {
  14942. let textureType = _gl.TEXTURE_2D;
  14943. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14944. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14945. const forceUpload = initTexture( textureProperties, texture );
  14946. const source = texture.source;
  14947. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14948. const sourceProperties = properties.get( source );
  14949. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14950. state.activeTexture( _gl.TEXTURE0 + slot );
  14951. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14952. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14953. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14954. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14955. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14956. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14957. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14958. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  14959. image = verifyColorSpace( texture, image );
  14960. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14961. const glType = utils.convert( texture.type );
  14962. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14963. setTextureParameters( textureType, texture );
  14964. let mipmap;
  14965. const mipmaps = texture.mipmaps;
  14966. const useTexStorage = ( texture.isVideoTexture !== true );
  14967. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14968. const dataReady = source.dataReady;
  14969. const levels = getMipLevels( texture, image );
  14970. if ( texture.isDepthTexture ) {
  14971. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  14972. //
  14973. if ( allocateMemory ) {
  14974. if ( useTexStorage ) {
  14975. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14976. } else {
  14977. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14978. }
  14979. }
  14980. } else if ( texture.isDataTexture ) {
  14981. // use manually created mipmaps if available
  14982. // if there are no manual mipmaps
  14983. // set 0 level mipmap and then use GL to generate other mipmap levels
  14984. if ( mipmaps.length > 0 ) {
  14985. if ( useTexStorage && allocateMemory ) {
  14986. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14987. }
  14988. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14989. mipmap = mipmaps[ i ];
  14990. if ( useTexStorage ) {
  14991. if ( dataReady ) {
  14992. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14993. }
  14994. } else {
  14995. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14996. }
  14997. }
  14998. texture.generateMipmaps = false;
  14999. } else {
  15000. if ( useTexStorage ) {
  15001. if ( allocateMemory ) {
  15002. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15003. }
  15004. if ( dataReady ) {
  15005. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  15006. }
  15007. } else {
  15008. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15009. }
  15010. }
  15011. } else if ( texture.isCompressedTexture ) {
  15012. if ( texture.isCompressedArrayTexture ) {
  15013. if ( useTexStorage && allocateMemory ) {
  15014. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  15015. }
  15016. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15017. mipmap = mipmaps[ i ];
  15018. if ( texture.format !== RGBAFormat ) {
  15019. if ( glFormat !== null ) {
  15020. if ( useTexStorage ) {
  15021. if ( dataReady ) {
  15022. if ( texture.layerUpdates.size > 0 ) {
  15023. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  15024. for ( const layerIndex of texture.layerUpdates ) {
  15025. const layerData = mipmap.data.subarray(
  15026. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  15027. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  15028. );
  15029. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData, 0, 0 );
  15030. }
  15031. texture.clearLayerUpdates();
  15032. } else {
  15033. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  15034. }
  15035. }
  15036. } else {
  15037. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  15038. }
  15039. } else {
  15040. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15041. }
  15042. } else {
  15043. if ( useTexStorage ) {
  15044. if ( dataReady ) {
  15045. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  15046. }
  15047. } else {
  15048. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  15049. }
  15050. }
  15051. }
  15052. } else {
  15053. if ( useTexStorage && allocateMemory ) {
  15054. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  15055. }
  15056. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15057. mipmap = mipmaps[ i ];
  15058. if ( texture.format !== RGBAFormat ) {
  15059. if ( glFormat !== null ) {
  15060. if ( useTexStorage ) {
  15061. if ( dataReady ) {
  15062. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15063. }
  15064. } else {
  15065. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15066. }
  15067. } else {
  15068. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15069. }
  15070. } else {
  15071. if ( useTexStorage ) {
  15072. if ( dataReady ) {
  15073. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15074. }
  15075. } else {
  15076. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15077. }
  15078. }
  15079. }
  15080. }
  15081. } else if ( texture.isDataArrayTexture ) {
  15082. if ( useTexStorage ) {
  15083. if ( allocateMemory ) {
  15084. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  15085. }
  15086. if ( dataReady ) {
  15087. if ( texture.layerUpdates.size > 0 ) {
  15088. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  15089. for ( const layerIndex of texture.layerUpdates ) {
  15090. const layerData = image.data.subarray(
  15091. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  15092. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  15093. );
  15094. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  15095. }
  15096. texture.clearLayerUpdates();
  15097. } else {
  15098. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15099. }
  15100. }
  15101. } else {
  15102. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15103. }
  15104. } else if ( texture.isData3DTexture ) {
  15105. if ( useTexStorage ) {
  15106. if ( allocateMemory ) {
  15107. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  15108. }
  15109. if ( dataReady ) {
  15110. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15111. }
  15112. } else {
  15113. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15114. }
  15115. } else if ( texture.isFramebufferTexture ) {
  15116. if ( allocateMemory ) {
  15117. if ( useTexStorage ) {
  15118. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15119. } else {
  15120. let width = image.width, height = image.height;
  15121. for ( let i = 0; i < levels; i ++ ) {
  15122. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  15123. width >>= 1;
  15124. height >>= 1;
  15125. }
  15126. }
  15127. }
  15128. } else {
  15129. // regular Texture (image, video, canvas)
  15130. // use manually created mipmaps if available
  15131. // if there are no manual mipmaps
  15132. // set 0 level mipmap and then use GL to generate other mipmap levels
  15133. if ( mipmaps.length > 0 ) {
  15134. if ( useTexStorage && allocateMemory ) {
  15135. const dimensions = getDimensions( mipmaps[ 0 ] );
  15136. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  15137. }
  15138. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15139. mipmap = mipmaps[ i ];
  15140. if ( useTexStorage ) {
  15141. if ( dataReady ) {
  15142. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  15143. }
  15144. } else {
  15145. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  15146. }
  15147. }
  15148. texture.generateMipmaps = false;
  15149. } else {
  15150. if ( useTexStorage ) {
  15151. if ( allocateMemory ) {
  15152. const dimensions = getDimensions( image );
  15153. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  15154. }
  15155. if ( dataReady ) {
  15156. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  15157. }
  15158. } else {
  15159. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  15160. }
  15161. }
  15162. }
  15163. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15164. generateMipmap( textureType );
  15165. }
  15166. sourceProperties.__version = source.version;
  15167. if ( texture.onUpdate ) texture.onUpdate( texture );
  15168. }
  15169. textureProperties.__version = texture.version;
  15170. }
  15171. function uploadCubeTexture( textureProperties, texture, slot ) {
  15172. if ( texture.image.length !== 6 ) return;
  15173. const forceUpload = initTexture( textureProperties, texture );
  15174. const source = texture.source;
  15175. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  15176. const sourceProperties = properties.get( source );
  15177. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  15178. state.activeTexture( _gl.TEXTURE0 + slot );
  15179. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  15180. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  15181. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  15182. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15183. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15184. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15185. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  15186. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  15187. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15188. const cubeImage = [];
  15189. for ( let i = 0; i < 6; i ++ ) {
  15190. if ( ! isCompressed && ! isDataTexture ) {
  15191. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  15192. } else {
  15193. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15194. }
  15195. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  15196. }
  15197. const image = cubeImage[ 0 ],
  15198. glFormat = utils.convert( texture.format, texture.colorSpace ),
  15199. glType = utils.convert( texture.type ),
  15200. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15201. const useTexStorage = ( texture.isVideoTexture !== true );
  15202. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  15203. const dataReady = source.dataReady;
  15204. let levels = getMipLevels( texture, image );
  15205. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15206. let mipmaps;
  15207. if ( isCompressed ) {
  15208. if ( useTexStorage && allocateMemory ) {
  15209. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  15210. }
  15211. for ( let i = 0; i < 6; i ++ ) {
  15212. mipmaps = cubeImage[ i ].mipmaps;
  15213. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15214. const mipmap = mipmaps[ j ];
  15215. if ( texture.format !== RGBAFormat ) {
  15216. if ( glFormat !== null ) {
  15217. if ( useTexStorage ) {
  15218. if ( dataReady ) {
  15219. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15220. }
  15221. } else {
  15222. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15223. }
  15224. } else {
  15225. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15226. }
  15227. } else {
  15228. if ( useTexStorage ) {
  15229. if ( dataReady ) {
  15230. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15231. }
  15232. } else {
  15233. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15234. }
  15235. }
  15236. }
  15237. }
  15238. } else {
  15239. mipmaps = texture.mipmaps;
  15240. if ( useTexStorage && allocateMemory ) {
  15241. // TODO: Uniformly handle mipmap definitions
  15242. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  15243. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  15244. if ( mipmaps.length > 0 ) levels ++;
  15245. const dimensions = getDimensions( cubeImage[ 0 ] );
  15246. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  15247. }
  15248. for ( let i = 0; i < 6; i ++ ) {
  15249. if ( isDataTexture ) {
  15250. if ( useTexStorage ) {
  15251. if ( dataReady ) {
  15252. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  15253. }
  15254. } else {
  15255. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15256. }
  15257. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15258. const mipmap = mipmaps[ j ];
  15259. const mipmapImage = mipmap.image[ i ].image;
  15260. if ( useTexStorage ) {
  15261. if ( dataReady ) {
  15262. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  15263. }
  15264. } else {
  15265. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  15266. }
  15267. }
  15268. } else {
  15269. if ( useTexStorage ) {
  15270. if ( dataReady ) {
  15271. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  15272. }
  15273. } else {
  15274. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15275. }
  15276. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15277. const mipmap = mipmaps[ j ];
  15278. if ( useTexStorage ) {
  15279. if ( dataReady ) {
  15280. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  15281. }
  15282. } else {
  15283. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  15284. }
  15285. }
  15286. }
  15287. }
  15288. }
  15289. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15290. // We assume images for cube map have the same size.
  15291. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15292. }
  15293. sourceProperties.__version = source.version;
  15294. if ( texture.onUpdate ) texture.onUpdate( texture );
  15295. }
  15296. textureProperties.__version = texture.version;
  15297. }
  15298. // Render targets
  15299. // Setup storage for target texture and bind it to correct framebuffer
  15300. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  15301. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15302. const glType = utils.convert( texture.type );
  15303. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15304. const renderTargetProperties = properties.get( renderTarget );
  15305. if ( ! renderTargetProperties.__hasExternalTextures ) {
  15306. const width = Math.max( 1, renderTarget.width >> level );
  15307. const height = Math.max( 1, renderTarget.height >> level );
  15308. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  15309. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  15310. } else {
  15311. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  15312. }
  15313. }
  15314. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15315. if ( useMultisampledRTT( renderTarget ) ) {
  15316. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  15317. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15318. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15319. }
  15320. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15321. }
  15322. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15323. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15324. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15325. if ( renderTarget.depthBuffer ) {
  15326. // retrieve the depth attachment types
  15327. const depthTexture = renderTarget.depthTexture;
  15328. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  15329. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  15330. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15331. // set up the attachment
  15332. const samples = getRenderTargetSamples( renderTarget );
  15333. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  15334. if ( isUseMultisampledRTT ) {
  15335. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15336. } else if ( isMultisample ) {
  15337. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15338. } else {
  15339. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15340. }
  15341. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  15342. } else {
  15343. const textures = renderTarget.textures;
  15344. for ( let i = 0; i < textures.length; i ++ ) {
  15345. const texture = textures[ i ];
  15346. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15347. const glType = utils.convert( texture.type );
  15348. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15349. const samples = getRenderTargetSamples( renderTarget );
  15350. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15351. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15352. } else if ( useMultisampledRTT( renderTarget ) ) {
  15353. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15354. } else {
  15355. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15356. }
  15357. }
  15358. }
  15359. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15360. }
  15361. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15362. function setupDepthTexture( framebuffer, renderTarget ) {
  15363. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15364. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15365. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15366. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15367. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15368. }
  15369. // upload an empty depth texture with framebuffer size
  15370. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15371. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15372. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15373. renderTarget.depthTexture.image.width = renderTarget.width;
  15374. renderTarget.depthTexture.image.height = renderTarget.height;
  15375. renderTarget.depthTexture.needsUpdate = true;
  15376. }
  15377. setTexture2D( renderTarget.depthTexture, 0 );
  15378. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15379. const samples = getRenderTargetSamples( renderTarget );
  15380. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15381. if ( useMultisampledRTT( renderTarget ) ) {
  15382. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15383. } else {
  15384. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15385. }
  15386. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15387. if ( useMultisampledRTT( renderTarget ) ) {
  15388. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15389. } else {
  15390. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15391. }
  15392. } else {
  15393. throw new Error( 'Unknown depthTexture format' );
  15394. }
  15395. }
  15396. // Setup GL resources for a non-texture depth buffer
  15397. function setupDepthRenderbuffer( renderTarget ) {
  15398. const renderTargetProperties = properties.get( renderTarget );
  15399. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15400. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15401. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15402. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15403. } else {
  15404. if ( isCube ) {
  15405. renderTargetProperties.__webglDepthbuffer = [];
  15406. for ( let i = 0; i < 6; i ++ ) {
  15407. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15408. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15409. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15410. }
  15411. } else {
  15412. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15413. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15414. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15415. }
  15416. }
  15417. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15418. }
  15419. // rebind framebuffer with external textures
  15420. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15421. const renderTargetProperties = properties.get( renderTarget );
  15422. if ( colorTexture !== undefined ) {
  15423. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15424. }
  15425. if ( depthTexture !== undefined ) {
  15426. setupDepthRenderbuffer( renderTarget );
  15427. }
  15428. }
  15429. // Set up GL resources for the render target
  15430. function setupRenderTarget( renderTarget ) {
  15431. const texture = renderTarget.texture;
  15432. const renderTargetProperties = properties.get( renderTarget );
  15433. const textureProperties = properties.get( texture );
  15434. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15435. const textures = renderTarget.textures;
  15436. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15437. const isMultipleRenderTargets = ( textures.length > 1 );
  15438. if ( ! isMultipleRenderTargets ) {
  15439. if ( textureProperties.__webglTexture === undefined ) {
  15440. textureProperties.__webglTexture = _gl.createTexture();
  15441. }
  15442. textureProperties.__version = texture.version;
  15443. info.memory.textures ++;
  15444. }
  15445. // Setup framebuffer
  15446. if ( isCube ) {
  15447. renderTargetProperties.__webglFramebuffer = [];
  15448. for ( let i = 0; i < 6; i ++ ) {
  15449. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15450. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15451. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15452. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15453. }
  15454. } else {
  15455. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15456. }
  15457. }
  15458. } else {
  15459. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15460. renderTargetProperties.__webglFramebuffer = [];
  15461. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15462. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15463. }
  15464. } else {
  15465. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15466. }
  15467. if ( isMultipleRenderTargets ) {
  15468. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15469. const attachmentProperties = properties.get( textures[ i ] );
  15470. if ( attachmentProperties.__webglTexture === undefined ) {
  15471. attachmentProperties.__webglTexture = _gl.createTexture();
  15472. info.memory.textures ++;
  15473. }
  15474. }
  15475. }
  15476. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15477. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15478. renderTargetProperties.__webglColorRenderbuffer = [];
  15479. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15480. for ( let i = 0; i < textures.length; i ++ ) {
  15481. const texture = textures[ i ];
  15482. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15483. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15484. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15485. const glType = utils.convert( texture.type );
  15486. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15487. const samples = getRenderTargetSamples( renderTarget );
  15488. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15489. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15490. }
  15491. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15492. if ( renderTarget.depthBuffer ) {
  15493. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15494. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15495. }
  15496. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15497. }
  15498. }
  15499. // Setup color buffer
  15500. if ( isCube ) {
  15501. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15502. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15503. for ( let i = 0; i < 6; i ++ ) {
  15504. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15505. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15506. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15507. }
  15508. } else {
  15509. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15510. }
  15511. }
  15512. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15513. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15514. }
  15515. state.unbindTexture();
  15516. } else if ( isMultipleRenderTargets ) {
  15517. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15518. const attachment = textures[ i ];
  15519. const attachmentProperties = properties.get( attachment );
  15520. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15521. setTextureParameters( _gl.TEXTURE_2D, attachment );
  15522. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15523. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  15524. generateMipmap( _gl.TEXTURE_2D );
  15525. }
  15526. }
  15527. state.unbindTexture();
  15528. } else {
  15529. let glTextureType = _gl.TEXTURE_2D;
  15530. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15531. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15532. }
  15533. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15534. setTextureParameters( glTextureType, texture );
  15535. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15536. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15537. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15538. }
  15539. } else {
  15540. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15541. }
  15542. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15543. generateMipmap( glTextureType );
  15544. }
  15545. state.unbindTexture();
  15546. }
  15547. // Setup depth and stencil buffers
  15548. if ( renderTarget.depthBuffer ) {
  15549. setupDepthRenderbuffer( renderTarget );
  15550. }
  15551. }
  15552. function updateRenderTargetMipmap( renderTarget ) {
  15553. const textures = renderTarget.textures;
  15554. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15555. const texture = textures[ i ];
  15556. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15557. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15558. const webglTexture = properties.get( texture ).__webglTexture;
  15559. state.bindTexture( target, webglTexture );
  15560. generateMipmap( target );
  15561. state.unbindTexture();
  15562. }
  15563. }
  15564. }
  15565. const invalidationArrayRead = [];
  15566. const invalidationArrayDraw = [];
  15567. function updateMultisampleRenderTarget( renderTarget ) {
  15568. if ( renderTarget.samples > 0 ) {
  15569. if ( useMultisampledRTT( renderTarget ) === false ) {
  15570. const textures = renderTarget.textures;
  15571. const width = renderTarget.width;
  15572. const height = renderTarget.height;
  15573. let mask = _gl.COLOR_BUFFER_BIT;
  15574. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15575. const renderTargetProperties = properties.get( renderTarget );
  15576. const isMultipleRenderTargets = ( textures.length > 1 );
  15577. // If MRT we need to remove FBO attachments
  15578. if ( isMultipleRenderTargets ) {
  15579. for ( let i = 0; i < textures.length; i ++ ) {
  15580. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15581. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15582. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15583. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15584. }
  15585. }
  15586. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15587. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15588. for ( let i = 0; i < textures.length; i ++ ) {
  15589. if ( renderTarget.resolveDepthBuffer ) {
  15590. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15591. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  15592. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15593. }
  15594. if ( isMultipleRenderTargets ) {
  15595. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15596. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15597. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15598. }
  15599. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15600. if ( supportsInvalidateFramebuffer === true ) {
  15601. invalidationArrayRead.length = 0;
  15602. invalidationArrayDraw.length = 0;
  15603. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  15604. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  15605. invalidationArrayRead.push( depthStyle );
  15606. invalidationArrayDraw.push( depthStyle );
  15607. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  15608. }
  15609. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  15610. }
  15611. }
  15612. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15613. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15614. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15615. if ( isMultipleRenderTargets ) {
  15616. for ( let i = 0; i < textures.length; i ++ ) {
  15617. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15618. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15619. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15620. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15621. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15622. }
  15623. }
  15624. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15625. } else {
  15626. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  15627. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15628. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15629. }
  15630. }
  15631. }
  15632. }
  15633. function getRenderTargetSamples( renderTarget ) {
  15634. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15635. }
  15636. function useMultisampledRTT( renderTarget ) {
  15637. const renderTargetProperties = properties.get( renderTarget );
  15638. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15639. }
  15640. function updateVideoTexture( texture ) {
  15641. const frame = info.render.frame;
  15642. // Check the last frame we updated the VideoTexture
  15643. if ( _videoTextures.get( texture ) !== frame ) {
  15644. _videoTextures.set( texture, frame );
  15645. texture.update();
  15646. }
  15647. }
  15648. function verifyColorSpace( texture, image ) {
  15649. const colorSpace = texture.colorSpace;
  15650. const format = texture.format;
  15651. const type = texture.type;
  15652. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  15653. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15654. // sRGB
  15655. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15656. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15657. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15658. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15659. }
  15660. } else {
  15661. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15662. }
  15663. }
  15664. return image;
  15665. }
  15666. function getDimensions( image ) {
  15667. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  15668. // if intrinsic data are not available, fallback to width/height
  15669. _imageDimensions.width = image.naturalWidth || image.width;
  15670. _imageDimensions.height = image.naturalHeight || image.height;
  15671. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  15672. _imageDimensions.width = image.displayWidth;
  15673. _imageDimensions.height = image.displayHeight;
  15674. } else {
  15675. _imageDimensions.width = image.width;
  15676. _imageDimensions.height = image.height;
  15677. }
  15678. return _imageDimensions;
  15679. }
  15680. //
  15681. this.allocateTextureUnit = allocateTextureUnit;
  15682. this.resetTextureUnits = resetTextureUnits;
  15683. this.setTexture2D = setTexture2D;
  15684. this.setTexture2DArray = setTexture2DArray;
  15685. this.setTexture3D = setTexture3D;
  15686. this.setTextureCube = setTextureCube;
  15687. this.rebindTextures = rebindTextures;
  15688. this.setupRenderTarget = setupRenderTarget;
  15689. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15690. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15691. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15692. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15693. this.useMultisampledRTT = useMultisampledRTT;
  15694. }
  15695. function WebGLUtils( gl, extensions ) {
  15696. function convert( p, colorSpace = NoColorSpace ) {
  15697. let extension;
  15698. const transfer = ColorManagement.getTransfer( colorSpace );
  15699. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15700. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15701. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15702. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  15703. if ( p === ByteType ) return gl.BYTE;
  15704. if ( p === ShortType ) return gl.SHORT;
  15705. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15706. if ( p === IntType ) return gl.INT;
  15707. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15708. if ( p === FloatType ) return gl.FLOAT;
  15709. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  15710. if ( p === AlphaFormat ) return gl.ALPHA;
  15711. if ( p === RGBFormat ) return gl.RGB;
  15712. if ( p === RGBAFormat ) return gl.RGBA;
  15713. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15714. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15715. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15716. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15717. // WebGL2 formats.
  15718. if ( p === RedFormat ) return gl.RED;
  15719. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15720. if ( p === RGFormat ) return gl.RG;
  15721. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15722. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15723. // S3TC
  15724. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15725. if ( transfer === SRGBTransfer ) {
  15726. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15727. if ( extension !== null ) {
  15728. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15729. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15730. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15731. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15732. } else {
  15733. return null;
  15734. }
  15735. } else {
  15736. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15737. if ( extension !== null ) {
  15738. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15739. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15740. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15741. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15742. } else {
  15743. return null;
  15744. }
  15745. }
  15746. }
  15747. // PVRTC
  15748. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15749. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15750. if ( extension !== null ) {
  15751. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15752. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15753. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15754. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15755. } else {
  15756. return null;
  15757. }
  15758. }
  15759. // ETC
  15760. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15761. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15762. if ( extension !== null ) {
  15763. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15764. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15765. } else {
  15766. return null;
  15767. }
  15768. }
  15769. // ASTC
  15770. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15771. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15772. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15773. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15774. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15775. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15776. if ( extension !== null ) {
  15777. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15778. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15779. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15780. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15781. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15782. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15783. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15784. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15785. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15786. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15787. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15788. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15789. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15790. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15791. } else {
  15792. return null;
  15793. }
  15794. }
  15795. // BPTC
  15796. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15797. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15798. if ( extension !== null ) {
  15799. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15800. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15801. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15802. } else {
  15803. return null;
  15804. }
  15805. }
  15806. // RGTC
  15807. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15808. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15809. if ( extension !== null ) {
  15810. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15811. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15812. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15813. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15814. } else {
  15815. return null;
  15816. }
  15817. }
  15818. //
  15819. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  15820. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15821. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15822. }
  15823. return { convert: convert };
  15824. }
  15825. class ArrayCamera extends PerspectiveCamera {
  15826. constructor( array = [] ) {
  15827. super();
  15828. this.isArrayCamera = true;
  15829. this.cameras = array;
  15830. }
  15831. }
  15832. class Group extends Object3D {
  15833. constructor() {
  15834. super();
  15835. this.isGroup = true;
  15836. this.type = 'Group';
  15837. }
  15838. }
  15839. const _moveEvent = { type: 'move' };
  15840. class WebXRController {
  15841. constructor() {
  15842. this._targetRay = null;
  15843. this._grip = null;
  15844. this._hand = null;
  15845. }
  15846. getHandSpace() {
  15847. if ( this._hand === null ) {
  15848. this._hand = new Group();
  15849. this._hand.matrixAutoUpdate = false;
  15850. this._hand.visible = false;
  15851. this._hand.joints = {};
  15852. this._hand.inputState = { pinching: false };
  15853. }
  15854. return this._hand;
  15855. }
  15856. getTargetRaySpace() {
  15857. if ( this._targetRay === null ) {
  15858. this._targetRay = new Group();
  15859. this._targetRay.matrixAutoUpdate = false;
  15860. this._targetRay.visible = false;
  15861. this._targetRay.hasLinearVelocity = false;
  15862. this._targetRay.linearVelocity = new Vector3();
  15863. this._targetRay.hasAngularVelocity = false;
  15864. this._targetRay.angularVelocity = new Vector3();
  15865. }
  15866. return this._targetRay;
  15867. }
  15868. getGripSpace() {
  15869. if ( this._grip === null ) {
  15870. this._grip = new Group();
  15871. this._grip.matrixAutoUpdate = false;
  15872. this._grip.visible = false;
  15873. this._grip.hasLinearVelocity = false;
  15874. this._grip.linearVelocity = new Vector3();
  15875. this._grip.hasAngularVelocity = false;
  15876. this._grip.angularVelocity = new Vector3();
  15877. }
  15878. return this._grip;
  15879. }
  15880. dispatchEvent( event ) {
  15881. if ( this._targetRay !== null ) {
  15882. this._targetRay.dispatchEvent( event );
  15883. }
  15884. if ( this._grip !== null ) {
  15885. this._grip.dispatchEvent( event );
  15886. }
  15887. if ( this._hand !== null ) {
  15888. this._hand.dispatchEvent( event );
  15889. }
  15890. return this;
  15891. }
  15892. connect( inputSource ) {
  15893. if ( inputSource && inputSource.hand ) {
  15894. const hand = this._hand;
  15895. if ( hand ) {
  15896. for ( const inputjoint of inputSource.hand.values() ) {
  15897. // Initialize hand with joints when connected
  15898. this._getHandJoint( hand, inputjoint );
  15899. }
  15900. }
  15901. }
  15902. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15903. return this;
  15904. }
  15905. disconnect( inputSource ) {
  15906. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15907. if ( this._targetRay !== null ) {
  15908. this._targetRay.visible = false;
  15909. }
  15910. if ( this._grip !== null ) {
  15911. this._grip.visible = false;
  15912. }
  15913. if ( this._hand !== null ) {
  15914. this._hand.visible = false;
  15915. }
  15916. return this;
  15917. }
  15918. update( inputSource, frame, referenceSpace ) {
  15919. let inputPose = null;
  15920. let gripPose = null;
  15921. let handPose = null;
  15922. const targetRay = this._targetRay;
  15923. const grip = this._grip;
  15924. const hand = this._hand;
  15925. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15926. if ( hand && inputSource.hand ) {
  15927. handPose = true;
  15928. for ( const inputjoint of inputSource.hand.values() ) {
  15929. // Update the joints groups with the XRJoint poses
  15930. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15931. // The transform of this joint will be updated with the joint pose on each frame
  15932. const joint = this._getHandJoint( hand, inputjoint );
  15933. if ( jointPose !== null ) {
  15934. joint.matrix.fromArray( jointPose.transform.matrix );
  15935. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15936. joint.matrixWorldNeedsUpdate = true;
  15937. joint.jointRadius = jointPose.radius;
  15938. }
  15939. joint.visible = jointPose !== null;
  15940. }
  15941. // Custom events
  15942. // Check pinchz
  15943. const indexTip = hand.joints[ 'index-finger-tip' ];
  15944. const thumbTip = hand.joints[ 'thumb-tip' ];
  15945. const distance = indexTip.position.distanceTo( thumbTip.position );
  15946. const distanceToPinch = 0.02;
  15947. const threshold = 0.005;
  15948. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15949. hand.inputState.pinching = false;
  15950. this.dispatchEvent( {
  15951. type: 'pinchend',
  15952. handedness: inputSource.handedness,
  15953. target: this
  15954. } );
  15955. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15956. hand.inputState.pinching = true;
  15957. this.dispatchEvent( {
  15958. type: 'pinchstart',
  15959. handedness: inputSource.handedness,
  15960. target: this
  15961. } );
  15962. }
  15963. } else {
  15964. if ( grip !== null && inputSource.gripSpace ) {
  15965. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15966. if ( gripPose !== null ) {
  15967. grip.matrix.fromArray( gripPose.transform.matrix );
  15968. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15969. grip.matrixWorldNeedsUpdate = true;
  15970. if ( gripPose.linearVelocity ) {
  15971. grip.hasLinearVelocity = true;
  15972. grip.linearVelocity.copy( gripPose.linearVelocity );
  15973. } else {
  15974. grip.hasLinearVelocity = false;
  15975. }
  15976. if ( gripPose.angularVelocity ) {
  15977. grip.hasAngularVelocity = true;
  15978. grip.angularVelocity.copy( gripPose.angularVelocity );
  15979. } else {
  15980. grip.hasAngularVelocity = false;
  15981. }
  15982. }
  15983. }
  15984. }
  15985. if ( targetRay !== null ) {
  15986. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15987. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15988. if ( inputPose === null && gripPose !== null ) {
  15989. inputPose = gripPose;
  15990. }
  15991. if ( inputPose !== null ) {
  15992. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15993. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15994. targetRay.matrixWorldNeedsUpdate = true;
  15995. if ( inputPose.linearVelocity ) {
  15996. targetRay.hasLinearVelocity = true;
  15997. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15998. } else {
  15999. targetRay.hasLinearVelocity = false;
  16000. }
  16001. if ( inputPose.angularVelocity ) {
  16002. targetRay.hasAngularVelocity = true;
  16003. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16004. } else {
  16005. targetRay.hasAngularVelocity = false;
  16006. }
  16007. this.dispatchEvent( _moveEvent );
  16008. }
  16009. }
  16010. }
  16011. if ( targetRay !== null ) {
  16012. targetRay.visible = ( inputPose !== null );
  16013. }
  16014. if ( grip !== null ) {
  16015. grip.visible = ( gripPose !== null );
  16016. }
  16017. if ( hand !== null ) {
  16018. hand.visible = ( handPose !== null );
  16019. }
  16020. return this;
  16021. }
  16022. // private method
  16023. _getHandJoint( hand, inputjoint ) {
  16024. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16025. const joint = new Group();
  16026. joint.matrixAutoUpdate = false;
  16027. joint.visible = false;
  16028. hand.joints[ inputjoint.jointName ] = joint;
  16029. hand.add( joint );
  16030. }
  16031. return hand.joints[ inputjoint.jointName ];
  16032. }
  16033. }
  16034. const _occlusion_vertex = `
  16035. void main() {
  16036. gl_Position = vec4( position, 1.0 );
  16037. }`;
  16038. const _occlusion_fragment = `
  16039. uniform sampler2DArray depthColor;
  16040. uniform float depthWidth;
  16041. uniform float depthHeight;
  16042. void main() {
  16043. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  16044. if ( coord.x >= 1.0 ) {
  16045. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  16046. } else {
  16047. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  16048. }
  16049. }`;
  16050. class WebXRDepthSensing {
  16051. constructor() {
  16052. this.texture = null;
  16053. this.mesh = null;
  16054. this.depthNear = 0;
  16055. this.depthFar = 0;
  16056. }
  16057. init( renderer, depthData, renderState ) {
  16058. if ( this.texture === null ) {
  16059. const texture = new Texture();
  16060. const texProps = renderer.properties.get( texture );
  16061. texProps.__webglTexture = depthData.texture;
  16062. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  16063. this.depthNear = depthData.depthNear;
  16064. this.depthFar = depthData.depthFar;
  16065. }
  16066. this.texture = texture;
  16067. }
  16068. }
  16069. getMesh( cameraXR ) {
  16070. if ( this.texture !== null ) {
  16071. if ( this.mesh === null ) {
  16072. const viewport = cameraXR.cameras[ 0 ].viewport;
  16073. const material = new ShaderMaterial( {
  16074. vertexShader: _occlusion_vertex,
  16075. fragmentShader: _occlusion_fragment,
  16076. uniforms: {
  16077. depthColor: { value: this.texture },
  16078. depthWidth: { value: viewport.z },
  16079. depthHeight: { value: viewport.w }
  16080. }
  16081. } );
  16082. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  16083. }
  16084. }
  16085. return this.mesh;
  16086. }
  16087. reset() {
  16088. this.texture = null;
  16089. this.mesh = null;
  16090. }
  16091. getDepthTexture() {
  16092. return this.texture;
  16093. }
  16094. }
  16095. class WebXRManager extends EventDispatcher {
  16096. constructor( renderer, gl ) {
  16097. super();
  16098. const scope = this;
  16099. let session = null;
  16100. let framebufferScaleFactor = 1.0;
  16101. let referenceSpace = null;
  16102. let referenceSpaceType = 'local-floor';
  16103. // Set default foveation to maximum.
  16104. let foveation = 1.0;
  16105. let customReferenceSpace = null;
  16106. let pose = null;
  16107. let glBinding = null;
  16108. let glProjLayer = null;
  16109. let glBaseLayer = null;
  16110. let xrFrame = null;
  16111. const depthSensing = new WebXRDepthSensing();
  16112. const attributes = gl.getContextAttributes();
  16113. let initialRenderTarget = null;
  16114. let newRenderTarget = null;
  16115. const controllers = [];
  16116. const controllerInputSources = [];
  16117. const currentSize = new Vector2();
  16118. let currentPixelRatio = null;
  16119. //
  16120. const cameraL = new PerspectiveCamera();
  16121. cameraL.layers.enable( 1 );
  16122. cameraL.viewport = new Vector4();
  16123. const cameraR = new PerspectiveCamera();
  16124. cameraR.layers.enable( 2 );
  16125. cameraR.viewport = new Vector4();
  16126. const cameras = [ cameraL, cameraR ];
  16127. const cameraXR = new ArrayCamera();
  16128. cameraXR.layers.enable( 1 );
  16129. cameraXR.layers.enable( 2 );
  16130. let _currentDepthNear = null;
  16131. let _currentDepthFar = null;
  16132. //
  16133. this.cameraAutoUpdate = true;
  16134. this.enabled = false;
  16135. this.isPresenting = false;
  16136. this.getController = function ( index ) {
  16137. let controller = controllers[ index ];
  16138. if ( controller === undefined ) {
  16139. controller = new WebXRController();
  16140. controllers[ index ] = controller;
  16141. }
  16142. return controller.getTargetRaySpace();
  16143. };
  16144. this.getControllerGrip = function ( index ) {
  16145. let controller = controllers[ index ];
  16146. if ( controller === undefined ) {
  16147. controller = new WebXRController();
  16148. controllers[ index ] = controller;
  16149. }
  16150. return controller.getGripSpace();
  16151. };
  16152. this.getHand = function ( index ) {
  16153. let controller = controllers[ index ];
  16154. if ( controller === undefined ) {
  16155. controller = new WebXRController();
  16156. controllers[ index ] = controller;
  16157. }
  16158. return controller.getHandSpace();
  16159. };
  16160. //
  16161. function onSessionEvent( event ) {
  16162. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  16163. if ( controllerIndex === - 1 ) {
  16164. return;
  16165. }
  16166. const controller = controllers[ controllerIndex ];
  16167. if ( controller !== undefined ) {
  16168. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  16169. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  16170. }
  16171. }
  16172. function onSessionEnd() {
  16173. session.removeEventListener( 'select', onSessionEvent );
  16174. session.removeEventListener( 'selectstart', onSessionEvent );
  16175. session.removeEventListener( 'selectend', onSessionEvent );
  16176. session.removeEventListener( 'squeeze', onSessionEvent );
  16177. session.removeEventListener( 'squeezestart', onSessionEvent );
  16178. session.removeEventListener( 'squeezeend', onSessionEvent );
  16179. session.removeEventListener( 'end', onSessionEnd );
  16180. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  16181. for ( let i = 0; i < controllers.length; i ++ ) {
  16182. const inputSource = controllerInputSources[ i ];
  16183. if ( inputSource === null ) continue;
  16184. controllerInputSources[ i ] = null;
  16185. controllers[ i ].disconnect( inputSource );
  16186. }
  16187. _currentDepthNear = null;
  16188. _currentDepthFar = null;
  16189. depthSensing.reset();
  16190. // restore framebuffer/rendering state
  16191. renderer.setRenderTarget( initialRenderTarget );
  16192. glBaseLayer = null;
  16193. glProjLayer = null;
  16194. glBinding = null;
  16195. session = null;
  16196. newRenderTarget = null;
  16197. //
  16198. animation.stop();
  16199. scope.isPresenting = false;
  16200. renderer.setPixelRatio( currentPixelRatio );
  16201. renderer.setSize( currentSize.width, currentSize.height, false );
  16202. scope.dispatchEvent( { type: 'sessionend' } );
  16203. }
  16204. this.setFramebufferScaleFactor = function ( value ) {
  16205. framebufferScaleFactor = value;
  16206. if ( scope.isPresenting === true ) {
  16207. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  16208. }
  16209. };
  16210. this.setReferenceSpaceType = function ( value ) {
  16211. referenceSpaceType = value;
  16212. if ( scope.isPresenting === true ) {
  16213. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  16214. }
  16215. };
  16216. this.getReferenceSpace = function () {
  16217. return customReferenceSpace || referenceSpace;
  16218. };
  16219. this.setReferenceSpace = function ( space ) {
  16220. customReferenceSpace = space;
  16221. };
  16222. this.getBaseLayer = function () {
  16223. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  16224. };
  16225. this.getBinding = function () {
  16226. return glBinding;
  16227. };
  16228. this.getFrame = function () {
  16229. return xrFrame;
  16230. };
  16231. this.getSession = function () {
  16232. return session;
  16233. };
  16234. this.setSession = async function ( value ) {
  16235. session = value;
  16236. if ( session !== null ) {
  16237. initialRenderTarget = renderer.getRenderTarget();
  16238. session.addEventListener( 'select', onSessionEvent );
  16239. session.addEventListener( 'selectstart', onSessionEvent );
  16240. session.addEventListener( 'selectend', onSessionEvent );
  16241. session.addEventListener( 'squeeze', onSessionEvent );
  16242. session.addEventListener( 'squeezestart', onSessionEvent );
  16243. session.addEventListener( 'squeezeend', onSessionEvent );
  16244. session.addEventListener( 'end', onSessionEnd );
  16245. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  16246. if ( attributes.xrCompatible !== true ) {
  16247. await gl.makeXRCompatible();
  16248. }
  16249. currentPixelRatio = renderer.getPixelRatio();
  16250. renderer.getSize( currentSize );
  16251. if ( session.renderState.layers === undefined ) {
  16252. const layerInit = {
  16253. antialias: attributes.antialias,
  16254. alpha: true,
  16255. depth: attributes.depth,
  16256. stencil: attributes.stencil,
  16257. framebufferScaleFactor: framebufferScaleFactor
  16258. };
  16259. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  16260. session.updateRenderState( { baseLayer: glBaseLayer } );
  16261. renderer.setPixelRatio( 1 );
  16262. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  16263. newRenderTarget = new WebGLRenderTarget(
  16264. glBaseLayer.framebufferWidth,
  16265. glBaseLayer.framebufferHeight,
  16266. {
  16267. format: RGBAFormat,
  16268. type: UnsignedByteType,
  16269. colorSpace: renderer.outputColorSpace,
  16270. stencilBuffer: attributes.stencil
  16271. }
  16272. );
  16273. } else {
  16274. let depthFormat = null;
  16275. let depthType = null;
  16276. let glDepthFormat = null;
  16277. if ( attributes.depth ) {
  16278. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  16279. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  16280. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  16281. }
  16282. const projectionlayerInit = {
  16283. colorFormat: gl.RGBA8,
  16284. depthFormat: glDepthFormat,
  16285. scaleFactor: framebufferScaleFactor
  16286. };
  16287. glBinding = new XRWebGLBinding( session, gl );
  16288. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  16289. session.updateRenderState( { layers: [ glProjLayer ] } );
  16290. renderer.setPixelRatio( 1 );
  16291. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  16292. newRenderTarget = new WebGLRenderTarget(
  16293. glProjLayer.textureWidth,
  16294. glProjLayer.textureHeight,
  16295. {
  16296. format: RGBAFormat,
  16297. type: UnsignedByteType,
  16298. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  16299. stencilBuffer: attributes.stencil,
  16300. colorSpace: renderer.outputColorSpace,
  16301. samples: attributes.antialias ? 4 : 0,
  16302. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false )
  16303. } );
  16304. }
  16305. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16306. this.setFoveation( foveation );
  16307. customReferenceSpace = null;
  16308. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16309. animation.setContext( session );
  16310. animation.start();
  16311. scope.isPresenting = true;
  16312. scope.dispatchEvent( { type: 'sessionstart' } );
  16313. }
  16314. };
  16315. this.getEnvironmentBlendMode = function () {
  16316. if ( session !== null ) {
  16317. return session.environmentBlendMode;
  16318. }
  16319. };
  16320. this.getDepthTexture = function () {
  16321. return depthSensing.getDepthTexture();
  16322. };
  16323. function onInputSourcesChange( event ) {
  16324. // Notify disconnected
  16325. for ( let i = 0; i < event.removed.length; i ++ ) {
  16326. const inputSource = event.removed[ i ];
  16327. const index = controllerInputSources.indexOf( inputSource );
  16328. if ( index >= 0 ) {
  16329. controllerInputSources[ index ] = null;
  16330. controllers[ index ].disconnect( inputSource );
  16331. }
  16332. }
  16333. // Notify connected
  16334. for ( let i = 0; i < event.added.length; i ++ ) {
  16335. const inputSource = event.added[ i ];
  16336. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16337. if ( controllerIndex === - 1 ) {
  16338. // Assign input source a controller that currently has no input source
  16339. for ( let i = 0; i < controllers.length; i ++ ) {
  16340. if ( i >= controllerInputSources.length ) {
  16341. controllerInputSources.push( inputSource );
  16342. controllerIndex = i;
  16343. break;
  16344. } else if ( controllerInputSources[ i ] === null ) {
  16345. controllerInputSources[ i ] = inputSource;
  16346. controllerIndex = i;
  16347. break;
  16348. }
  16349. }
  16350. // If all controllers do currently receive input we ignore new ones
  16351. if ( controllerIndex === - 1 ) break;
  16352. }
  16353. const controller = controllers[ controllerIndex ];
  16354. if ( controller ) {
  16355. controller.connect( inputSource );
  16356. }
  16357. }
  16358. }
  16359. //
  16360. const cameraLPos = new Vector3();
  16361. const cameraRPos = new Vector3();
  16362. /**
  16363. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16364. * the cameras' projection and world matrices have already been set.
  16365. * And that near and far planes are identical for both cameras.
  16366. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16367. */
  16368. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16369. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16370. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16371. const ipd = cameraLPos.distanceTo( cameraRPos );
  16372. const projL = cameraL.projectionMatrix.elements;
  16373. const projR = cameraR.projectionMatrix.elements;
  16374. // VR systems will have identical far and near planes, and
  16375. // most likely identical top and bottom frustum extents.
  16376. // Use the left camera for these values.
  16377. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16378. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16379. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16380. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16381. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16382. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16383. const left = near * leftFov;
  16384. const right = near * rightFov;
  16385. // Calculate the new camera's position offset from the
  16386. // left camera. xOffset should be roughly half `ipd`.
  16387. const zOffset = ipd / ( - leftFov + rightFov );
  16388. const xOffset = zOffset * - leftFov;
  16389. // TODO: Better way to apply this offset?
  16390. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16391. camera.translateX( xOffset );
  16392. camera.translateZ( zOffset );
  16393. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16394. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16395. // Find the union of the frustum values of the cameras and scale
  16396. // the values so that the near plane's position does not change in world space,
  16397. // although must now be relative to the new union camera.
  16398. const near2 = near + zOffset;
  16399. const far2 = far + zOffset;
  16400. const left2 = left - xOffset;
  16401. const right2 = right + ( ipd - xOffset );
  16402. const top2 = topFov * far / far2 * near2;
  16403. const bottom2 = bottomFov * far / far2 * near2;
  16404. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16405. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16406. }
  16407. function updateCamera( camera, parent ) {
  16408. if ( parent === null ) {
  16409. camera.matrixWorld.copy( camera.matrix );
  16410. } else {
  16411. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16412. }
  16413. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16414. }
  16415. this.updateCamera = function ( camera ) {
  16416. if ( session === null ) return;
  16417. if ( depthSensing.texture !== null ) {
  16418. camera.near = depthSensing.depthNear;
  16419. camera.far = depthSensing.depthFar;
  16420. }
  16421. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16422. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16423. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16424. // Note that the new renderState won't apply until the next frame. See #18320
  16425. session.updateRenderState( {
  16426. depthNear: cameraXR.near,
  16427. depthFar: cameraXR.far
  16428. } );
  16429. _currentDepthNear = cameraXR.near;
  16430. _currentDepthFar = cameraXR.far;
  16431. cameraL.near = _currentDepthNear;
  16432. cameraL.far = _currentDepthFar;
  16433. cameraR.near = _currentDepthNear;
  16434. cameraR.far = _currentDepthFar;
  16435. cameraL.updateProjectionMatrix();
  16436. cameraR.updateProjectionMatrix();
  16437. camera.updateProjectionMatrix();
  16438. }
  16439. const parent = camera.parent;
  16440. const cameras = cameraXR.cameras;
  16441. updateCamera( cameraXR, parent );
  16442. for ( let i = 0; i < cameras.length; i ++ ) {
  16443. updateCamera( cameras[ i ], parent );
  16444. }
  16445. // update projection matrix for proper view frustum culling
  16446. if ( cameras.length === 2 ) {
  16447. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16448. } else {
  16449. // assume single camera setup (AR)
  16450. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16451. }
  16452. // update user camera and its children
  16453. updateUserCamera( camera, cameraXR, parent );
  16454. };
  16455. function updateUserCamera( camera, cameraXR, parent ) {
  16456. if ( parent === null ) {
  16457. camera.matrix.copy( cameraXR.matrixWorld );
  16458. } else {
  16459. camera.matrix.copy( parent.matrixWorld );
  16460. camera.matrix.invert();
  16461. camera.matrix.multiply( cameraXR.matrixWorld );
  16462. }
  16463. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16464. camera.updateMatrixWorld( true );
  16465. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16466. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16467. if ( camera.isPerspectiveCamera ) {
  16468. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16469. camera.zoom = 1;
  16470. }
  16471. }
  16472. this.getCamera = function () {
  16473. return cameraXR;
  16474. };
  16475. this.getFoveation = function () {
  16476. if ( glProjLayer === null && glBaseLayer === null ) {
  16477. return undefined;
  16478. }
  16479. return foveation;
  16480. };
  16481. this.setFoveation = function ( value ) {
  16482. // 0 = no foveation = full resolution
  16483. // 1 = maximum foveation = the edges render at lower resolution
  16484. foveation = value;
  16485. if ( glProjLayer !== null ) {
  16486. glProjLayer.fixedFoveation = value;
  16487. }
  16488. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16489. glBaseLayer.fixedFoveation = value;
  16490. }
  16491. };
  16492. this.hasDepthSensing = function () {
  16493. return depthSensing.texture !== null;
  16494. };
  16495. this.getDepthSensingMesh = function () {
  16496. return depthSensing.getMesh( cameraXR );
  16497. };
  16498. // Animation Loop
  16499. let onAnimationFrameCallback = null;
  16500. function onAnimationFrame( time, frame ) {
  16501. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16502. xrFrame = frame;
  16503. if ( pose !== null ) {
  16504. const views = pose.views;
  16505. if ( glBaseLayer !== null ) {
  16506. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16507. renderer.setRenderTarget( newRenderTarget );
  16508. }
  16509. let cameraXRNeedsUpdate = false;
  16510. // check if it's necessary to rebuild cameraXR's camera list
  16511. if ( views.length !== cameraXR.cameras.length ) {
  16512. cameraXR.cameras.length = 0;
  16513. cameraXRNeedsUpdate = true;
  16514. }
  16515. for ( let i = 0; i < views.length; i ++ ) {
  16516. const view = views[ i ];
  16517. let viewport = null;
  16518. if ( glBaseLayer !== null ) {
  16519. viewport = glBaseLayer.getViewport( view );
  16520. } else {
  16521. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16522. viewport = glSubImage.viewport;
  16523. // For side-by-side projection, we only produce a single texture for both eyes.
  16524. if ( i === 0 ) {
  16525. renderer.setRenderTargetTextures(
  16526. newRenderTarget,
  16527. glSubImage.colorTexture,
  16528. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16529. renderer.setRenderTarget( newRenderTarget );
  16530. }
  16531. }
  16532. let camera = cameras[ i ];
  16533. if ( camera === undefined ) {
  16534. camera = new PerspectiveCamera();
  16535. camera.layers.enable( i );
  16536. camera.viewport = new Vector4();
  16537. cameras[ i ] = camera;
  16538. }
  16539. camera.matrix.fromArray( view.transform.matrix );
  16540. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16541. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16542. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16543. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16544. if ( i === 0 ) {
  16545. cameraXR.matrix.copy( camera.matrix );
  16546. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16547. }
  16548. if ( cameraXRNeedsUpdate === true ) {
  16549. cameraXR.cameras.push( camera );
  16550. }
  16551. }
  16552. //
  16553. const enabledFeatures = session.enabledFeatures;
  16554. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  16555. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  16556. if ( depthData && depthData.isValid && depthData.texture ) {
  16557. depthSensing.init( renderer, depthData, session.renderState );
  16558. }
  16559. }
  16560. }
  16561. //
  16562. for ( let i = 0; i < controllers.length; i ++ ) {
  16563. const inputSource = controllerInputSources[ i ];
  16564. const controller = controllers[ i ];
  16565. if ( inputSource !== null && controller !== undefined ) {
  16566. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16567. }
  16568. }
  16569. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16570. if ( frame.detectedPlanes ) {
  16571. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16572. }
  16573. xrFrame = null;
  16574. }
  16575. const animation = new WebGLAnimation();
  16576. animation.setAnimationLoop( onAnimationFrame );
  16577. this.setAnimationLoop = function ( callback ) {
  16578. onAnimationFrameCallback = callback;
  16579. };
  16580. this.dispose = function () {};
  16581. }
  16582. }
  16583. const _e1 = /*@__PURE__*/ new Euler();
  16584. const _m1 = /*@__PURE__*/ new Matrix4();
  16585. function WebGLMaterials( renderer, properties ) {
  16586. function refreshTransformUniform( map, uniform ) {
  16587. if ( map.matrixAutoUpdate === true ) {
  16588. map.updateMatrix();
  16589. }
  16590. uniform.value.copy( map.matrix );
  16591. }
  16592. function refreshFogUniforms( uniforms, fog ) {
  16593. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16594. if ( fog.isFog ) {
  16595. uniforms.fogNear.value = fog.near;
  16596. uniforms.fogFar.value = fog.far;
  16597. } else if ( fog.isFogExp2 ) {
  16598. uniforms.fogDensity.value = fog.density;
  16599. }
  16600. }
  16601. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16602. if ( material.isMeshBasicMaterial ) {
  16603. refreshUniformsCommon( uniforms, material );
  16604. } else if ( material.isMeshLambertMaterial ) {
  16605. refreshUniformsCommon( uniforms, material );
  16606. } else if ( material.isMeshToonMaterial ) {
  16607. refreshUniformsCommon( uniforms, material );
  16608. refreshUniformsToon( uniforms, material );
  16609. } else if ( material.isMeshPhongMaterial ) {
  16610. refreshUniformsCommon( uniforms, material );
  16611. refreshUniformsPhong( uniforms, material );
  16612. } else if ( material.isMeshStandardMaterial ) {
  16613. refreshUniformsCommon( uniforms, material );
  16614. refreshUniformsStandard( uniforms, material );
  16615. if ( material.isMeshPhysicalMaterial ) {
  16616. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16617. }
  16618. } else if ( material.isMeshMatcapMaterial ) {
  16619. refreshUniformsCommon( uniforms, material );
  16620. refreshUniformsMatcap( uniforms, material );
  16621. } else if ( material.isMeshDepthMaterial ) {
  16622. refreshUniformsCommon( uniforms, material );
  16623. } else if ( material.isMeshDistanceMaterial ) {
  16624. refreshUniformsCommon( uniforms, material );
  16625. refreshUniformsDistance( uniforms, material );
  16626. } else if ( material.isMeshNormalMaterial ) {
  16627. refreshUniformsCommon( uniforms, material );
  16628. } else if ( material.isLineBasicMaterial ) {
  16629. refreshUniformsLine( uniforms, material );
  16630. if ( material.isLineDashedMaterial ) {
  16631. refreshUniformsDash( uniforms, material );
  16632. }
  16633. } else if ( material.isPointsMaterial ) {
  16634. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16635. } else if ( material.isSpriteMaterial ) {
  16636. refreshUniformsSprites( uniforms, material );
  16637. } else if ( material.isShadowMaterial ) {
  16638. uniforms.color.value.copy( material.color );
  16639. uniforms.opacity.value = material.opacity;
  16640. } else if ( material.isShaderMaterial ) {
  16641. material.uniformsNeedUpdate = false; // #15581
  16642. }
  16643. }
  16644. function refreshUniformsCommon( uniforms, material ) {
  16645. uniforms.opacity.value = material.opacity;
  16646. if ( material.color ) {
  16647. uniforms.diffuse.value.copy( material.color );
  16648. }
  16649. if ( material.emissive ) {
  16650. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16651. }
  16652. if ( material.map ) {
  16653. uniforms.map.value = material.map;
  16654. refreshTransformUniform( material.map, uniforms.mapTransform );
  16655. }
  16656. if ( material.alphaMap ) {
  16657. uniforms.alphaMap.value = material.alphaMap;
  16658. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16659. }
  16660. if ( material.bumpMap ) {
  16661. uniforms.bumpMap.value = material.bumpMap;
  16662. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16663. uniforms.bumpScale.value = material.bumpScale;
  16664. if ( material.side === BackSide ) {
  16665. uniforms.bumpScale.value *= - 1;
  16666. }
  16667. }
  16668. if ( material.normalMap ) {
  16669. uniforms.normalMap.value = material.normalMap;
  16670. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16671. uniforms.normalScale.value.copy( material.normalScale );
  16672. if ( material.side === BackSide ) {
  16673. uniforms.normalScale.value.negate();
  16674. }
  16675. }
  16676. if ( material.displacementMap ) {
  16677. uniforms.displacementMap.value = material.displacementMap;
  16678. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16679. uniforms.displacementScale.value = material.displacementScale;
  16680. uniforms.displacementBias.value = material.displacementBias;
  16681. }
  16682. if ( material.emissiveMap ) {
  16683. uniforms.emissiveMap.value = material.emissiveMap;
  16684. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16685. }
  16686. if ( material.specularMap ) {
  16687. uniforms.specularMap.value = material.specularMap;
  16688. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16689. }
  16690. if ( material.alphaTest > 0 ) {
  16691. uniforms.alphaTest.value = material.alphaTest;
  16692. }
  16693. const materialProperties = properties.get( material );
  16694. const envMap = materialProperties.envMap;
  16695. const envMapRotation = materialProperties.envMapRotation;
  16696. if ( envMap ) {
  16697. uniforms.envMap.value = envMap;
  16698. _e1.copy( envMapRotation );
  16699. // accommodate left-handed frame
  16700. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  16701. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  16702. // environment maps which are not cube render targets or PMREMs follow a different convention
  16703. _e1.y *= - 1;
  16704. _e1.z *= - 1;
  16705. }
  16706. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  16707. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16708. uniforms.reflectivity.value = material.reflectivity;
  16709. uniforms.ior.value = material.ior;
  16710. uniforms.refractionRatio.value = material.refractionRatio;
  16711. }
  16712. if ( material.lightMap ) {
  16713. uniforms.lightMap.value = material.lightMap;
  16714. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16715. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16716. }
  16717. if ( material.aoMap ) {
  16718. uniforms.aoMap.value = material.aoMap;
  16719. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16720. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16721. }
  16722. }
  16723. function refreshUniformsLine( uniforms, material ) {
  16724. uniforms.diffuse.value.copy( material.color );
  16725. uniforms.opacity.value = material.opacity;
  16726. if ( material.map ) {
  16727. uniforms.map.value = material.map;
  16728. refreshTransformUniform( material.map, uniforms.mapTransform );
  16729. }
  16730. }
  16731. function refreshUniformsDash( uniforms, material ) {
  16732. uniforms.dashSize.value = material.dashSize;
  16733. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16734. uniforms.scale.value = material.scale;
  16735. }
  16736. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16737. uniforms.diffuse.value.copy( material.color );
  16738. uniforms.opacity.value = material.opacity;
  16739. uniforms.size.value = material.size * pixelRatio;
  16740. uniforms.scale.value = height * 0.5;
  16741. if ( material.map ) {
  16742. uniforms.map.value = material.map;
  16743. refreshTransformUniform( material.map, uniforms.uvTransform );
  16744. }
  16745. if ( material.alphaMap ) {
  16746. uniforms.alphaMap.value = material.alphaMap;
  16747. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16748. }
  16749. if ( material.alphaTest > 0 ) {
  16750. uniforms.alphaTest.value = material.alphaTest;
  16751. }
  16752. }
  16753. function refreshUniformsSprites( uniforms, material ) {
  16754. uniforms.diffuse.value.copy( material.color );
  16755. uniforms.opacity.value = material.opacity;
  16756. uniforms.rotation.value = material.rotation;
  16757. if ( material.map ) {
  16758. uniforms.map.value = material.map;
  16759. refreshTransformUniform( material.map, uniforms.mapTransform );
  16760. }
  16761. if ( material.alphaMap ) {
  16762. uniforms.alphaMap.value = material.alphaMap;
  16763. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16764. }
  16765. if ( material.alphaTest > 0 ) {
  16766. uniforms.alphaTest.value = material.alphaTest;
  16767. }
  16768. }
  16769. function refreshUniformsPhong( uniforms, material ) {
  16770. uniforms.specular.value.copy( material.specular );
  16771. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16772. }
  16773. function refreshUniformsToon( uniforms, material ) {
  16774. if ( material.gradientMap ) {
  16775. uniforms.gradientMap.value = material.gradientMap;
  16776. }
  16777. }
  16778. function refreshUniformsStandard( uniforms, material ) {
  16779. uniforms.metalness.value = material.metalness;
  16780. if ( material.metalnessMap ) {
  16781. uniforms.metalnessMap.value = material.metalnessMap;
  16782. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16783. }
  16784. uniforms.roughness.value = material.roughness;
  16785. if ( material.roughnessMap ) {
  16786. uniforms.roughnessMap.value = material.roughnessMap;
  16787. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16788. }
  16789. if ( material.envMap ) {
  16790. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16791. uniforms.envMapIntensity.value = material.envMapIntensity;
  16792. }
  16793. }
  16794. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16795. uniforms.ior.value = material.ior; // also part of uniforms common
  16796. if ( material.sheen > 0 ) {
  16797. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16798. uniforms.sheenRoughness.value = material.sheenRoughness;
  16799. if ( material.sheenColorMap ) {
  16800. uniforms.sheenColorMap.value = material.sheenColorMap;
  16801. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16802. }
  16803. if ( material.sheenRoughnessMap ) {
  16804. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16805. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16806. }
  16807. }
  16808. if ( material.clearcoat > 0 ) {
  16809. uniforms.clearcoat.value = material.clearcoat;
  16810. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16811. if ( material.clearcoatMap ) {
  16812. uniforms.clearcoatMap.value = material.clearcoatMap;
  16813. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16814. }
  16815. if ( material.clearcoatRoughnessMap ) {
  16816. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16817. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16818. }
  16819. if ( material.clearcoatNormalMap ) {
  16820. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16821. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16822. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16823. if ( material.side === BackSide ) {
  16824. uniforms.clearcoatNormalScale.value.negate();
  16825. }
  16826. }
  16827. }
  16828. if ( material.dispersion > 0 ) {
  16829. uniforms.dispersion.value = material.dispersion;
  16830. }
  16831. if ( material.iridescence > 0 ) {
  16832. uniforms.iridescence.value = material.iridescence;
  16833. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16834. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16835. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16836. if ( material.iridescenceMap ) {
  16837. uniforms.iridescenceMap.value = material.iridescenceMap;
  16838. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16839. }
  16840. if ( material.iridescenceThicknessMap ) {
  16841. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16842. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16843. }
  16844. }
  16845. if ( material.transmission > 0 ) {
  16846. uniforms.transmission.value = material.transmission;
  16847. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16848. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16849. if ( material.transmissionMap ) {
  16850. uniforms.transmissionMap.value = material.transmissionMap;
  16851. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16852. }
  16853. uniforms.thickness.value = material.thickness;
  16854. if ( material.thicknessMap ) {
  16855. uniforms.thicknessMap.value = material.thicknessMap;
  16856. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16857. }
  16858. uniforms.attenuationDistance.value = material.attenuationDistance;
  16859. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16860. }
  16861. if ( material.anisotropy > 0 ) {
  16862. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16863. if ( material.anisotropyMap ) {
  16864. uniforms.anisotropyMap.value = material.anisotropyMap;
  16865. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16866. }
  16867. }
  16868. uniforms.specularIntensity.value = material.specularIntensity;
  16869. uniforms.specularColor.value.copy( material.specularColor );
  16870. if ( material.specularColorMap ) {
  16871. uniforms.specularColorMap.value = material.specularColorMap;
  16872. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16873. }
  16874. if ( material.specularIntensityMap ) {
  16875. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16876. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16877. }
  16878. }
  16879. function refreshUniformsMatcap( uniforms, material ) {
  16880. if ( material.matcap ) {
  16881. uniforms.matcap.value = material.matcap;
  16882. }
  16883. }
  16884. function refreshUniformsDistance( uniforms, material ) {
  16885. const light = properties.get( material ).light;
  16886. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16887. uniforms.nearDistance.value = light.shadow.camera.near;
  16888. uniforms.farDistance.value = light.shadow.camera.far;
  16889. }
  16890. return {
  16891. refreshFogUniforms: refreshFogUniforms,
  16892. refreshMaterialUniforms: refreshMaterialUniforms
  16893. };
  16894. }
  16895. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16896. let buffers = {};
  16897. let updateList = {};
  16898. let allocatedBindingPoints = [];
  16899. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  16900. function bind( uniformsGroup, program ) {
  16901. const webglProgram = program.program;
  16902. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16903. }
  16904. function update( uniformsGroup, program ) {
  16905. let buffer = buffers[ uniformsGroup.id ];
  16906. if ( buffer === undefined ) {
  16907. prepareUniformsGroup( uniformsGroup );
  16908. buffer = createBuffer( uniformsGroup );
  16909. buffers[ uniformsGroup.id ] = buffer;
  16910. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16911. }
  16912. // ensure to update the binding points/block indices mapping for this program
  16913. const webglProgram = program.program;
  16914. state.updateUBOMapping( uniformsGroup, webglProgram );
  16915. // update UBO once per frame
  16916. const frame = info.render.frame;
  16917. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16918. updateBufferData( uniformsGroup );
  16919. updateList[ uniformsGroup.id ] = frame;
  16920. }
  16921. }
  16922. function createBuffer( uniformsGroup ) {
  16923. // the setup of an UBO is independent of a particular shader program but global
  16924. const bindingPointIndex = allocateBindingPointIndex();
  16925. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16926. const buffer = gl.createBuffer();
  16927. const size = uniformsGroup.__size;
  16928. const usage = uniformsGroup.usage;
  16929. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16930. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16931. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16932. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16933. return buffer;
  16934. }
  16935. function allocateBindingPointIndex() {
  16936. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16937. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16938. allocatedBindingPoints.push( i );
  16939. return i;
  16940. }
  16941. }
  16942. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16943. return 0;
  16944. }
  16945. function updateBufferData( uniformsGroup ) {
  16946. const buffer = buffers[ uniformsGroup.id ];
  16947. const uniforms = uniformsGroup.uniforms;
  16948. const cache = uniformsGroup.__cache;
  16949. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16950. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16951. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16952. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16953. const uniform = uniformArray[ j ];
  16954. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  16955. const offset = uniform.__offset;
  16956. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16957. let arrayOffset = 0;
  16958. for ( let k = 0; k < values.length; k ++ ) {
  16959. const value = values[ k ];
  16960. const info = getUniformSize( value );
  16961. // TODO add integer and struct support
  16962. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16963. uniform.__data[ 0 ] = value;
  16964. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16965. } else if ( value.isMatrix3 ) {
  16966. // manually converting 3x3 to 3x4
  16967. uniform.__data[ 0 ] = value.elements[ 0 ];
  16968. uniform.__data[ 1 ] = value.elements[ 1 ];
  16969. uniform.__data[ 2 ] = value.elements[ 2 ];
  16970. uniform.__data[ 3 ] = 0;
  16971. uniform.__data[ 4 ] = value.elements[ 3 ];
  16972. uniform.__data[ 5 ] = value.elements[ 4 ];
  16973. uniform.__data[ 6 ] = value.elements[ 5 ];
  16974. uniform.__data[ 7 ] = 0;
  16975. uniform.__data[ 8 ] = value.elements[ 6 ];
  16976. uniform.__data[ 9 ] = value.elements[ 7 ];
  16977. uniform.__data[ 10 ] = value.elements[ 8 ];
  16978. uniform.__data[ 11 ] = 0;
  16979. } else {
  16980. value.toArray( uniform.__data, arrayOffset );
  16981. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16982. }
  16983. }
  16984. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16985. }
  16986. }
  16987. }
  16988. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16989. }
  16990. function hasUniformChanged( uniform, index, indexArray, cache ) {
  16991. const value = uniform.value;
  16992. const indexString = index + '_' + indexArray;
  16993. if ( cache[ indexString ] === undefined ) {
  16994. // cache entry does not exist so far
  16995. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16996. cache[ indexString ] = value;
  16997. } else {
  16998. cache[ indexString ] = value.clone();
  16999. }
  17000. return true;
  17001. } else {
  17002. const cachedObject = cache[ indexString ];
  17003. // compare current value with cached entry
  17004. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17005. if ( cachedObject !== value ) {
  17006. cache[ indexString ] = value;
  17007. return true;
  17008. }
  17009. } else {
  17010. if ( cachedObject.equals( value ) === false ) {
  17011. cachedObject.copy( value );
  17012. return true;
  17013. }
  17014. }
  17015. }
  17016. return false;
  17017. }
  17018. function prepareUniformsGroup( uniformsGroup ) {
  17019. // determine total buffer size according to the STD140 layout
  17020. // Hint: STD140 is the only supported layout in WebGL 2
  17021. const uniforms = uniformsGroup.uniforms;
  17022. let offset = 0; // global buffer offset in bytes
  17023. const chunkSize = 16; // size of a chunk in bytes
  17024. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  17025. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  17026. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  17027. const uniform = uniformArray[ j ];
  17028. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  17029. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  17030. const value = values[ k ];
  17031. const info = getUniformSize( value );
  17032. const chunkOffset = offset % chunkSize; // offset in the current chunk
  17033. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  17034. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  17035. offset += chunkPadding;
  17036. // Check for chunk overflow
  17037. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  17038. // Add padding and adjust offset
  17039. offset += ( chunkSize - chunkStart );
  17040. }
  17041. // the following two properties will be used for partial buffer updates
  17042. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  17043. uniform.__offset = offset;
  17044. // Update the global offset
  17045. offset += info.storage;
  17046. }
  17047. }
  17048. }
  17049. // ensure correct final padding
  17050. const chunkOffset = offset % chunkSize;
  17051. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  17052. //
  17053. uniformsGroup.__size = offset;
  17054. uniformsGroup.__cache = {};
  17055. return this;
  17056. }
  17057. function getUniformSize( value ) {
  17058. const info = {
  17059. boundary: 0, // bytes
  17060. storage: 0 // bytes
  17061. };
  17062. // determine sizes according to STD140
  17063. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17064. // float/int/bool
  17065. info.boundary = 4;
  17066. info.storage = 4;
  17067. } else if ( value.isVector2 ) {
  17068. // vec2
  17069. info.boundary = 8;
  17070. info.storage = 8;
  17071. } else if ( value.isVector3 || value.isColor ) {
  17072. // vec3
  17073. info.boundary = 16;
  17074. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  17075. } else if ( value.isVector4 ) {
  17076. // vec4
  17077. info.boundary = 16;
  17078. info.storage = 16;
  17079. } else if ( value.isMatrix3 ) {
  17080. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  17081. info.boundary = 48;
  17082. info.storage = 48;
  17083. } else if ( value.isMatrix4 ) {
  17084. // mat4
  17085. info.boundary = 64;
  17086. info.storage = 64;
  17087. } else if ( value.isTexture ) {
  17088. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  17089. } else {
  17090. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  17091. }
  17092. return info;
  17093. }
  17094. function onUniformsGroupsDispose( event ) {
  17095. const uniformsGroup = event.target;
  17096. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  17097. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  17098. allocatedBindingPoints.splice( index, 1 );
  17099. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  17100. delete buffers[ uniformsGroup.id ];
  17101. delete updateList[ uniformsGroup.id ];
  17102. }
  17103. function dispose() {
  17104. for ( const id in buffers ) {
  17105. gl.deleteBuffer( buffers[ id ] );
  17106. }
  17107. allocatedBindingPoints = [];
  17108. buffers = {};
  17109. updateList = {};
  17110. }
  17111. return {
  17112. bind: bind,
  17113. update: update,
  17114. dispose: dispose
  17115. };
  17116. }
  17117. class WebGLRenderer {
  17118. constructor( parameters = {} ) {
  17119. const {
  17120. canvas = createCanvasElement(),
  17121. context = null,
  17122. depth = true,
  17123. stencil = false,
  17124. alpha = false,
  17125. antialias = false,
  17126. premultipliedAlpha = true,
  17127. preserveDrawingBuffer = false,
  17128. powerPreference = 'default',
  17129. failIfMajorPerformanceCaveat = false,
  17130. } = parameters;
  17131. this.isWebGLRenderer = true;
  17132. let _alpha;
  17133. if ( context !== null ) {
  17134. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  17135. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  17136. }
  17137. _alpha = context.getContextAttributes().alpha;
  17138. } else {
  17139. _alpha = alpha;
  17140. }
  17141. const uintClearColor = new Uint32Array( 4 );
  17142. const intClearColor = new Int32Array( 4 );
  17143. let currentRenderList = null;
  17144. let currentRenderState = null;
  17145. // render() can be called from within a callback triggered by another render.
  17146. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  17147. const renderListStack = [];
  17148. const renderStateStack = [];
  17149. // public properties
  17150. this.domElement = canvas;
  17151. // Debug configuration container
  17152. this.debug = {
  17153. /**
  17154. * Enables error checking and reporting when shader programs are being compiled
  17155. * @type {boolean}
  17156. */
  17157. checkShaderErrors: true,
  17158. /**
  17159. * Callback for custom error reporting.
  17160. * @type {?Function}
  17161. */
  17162. onShaderError: null
  17163. };
  17164. // clearing
  17165. this.autoClear = true;
  17166. this.autoClearColor = true;
  17167. this.autoClearDepth = true;
  17168. this.autoClearStencil = true;
  17169. // scene graph
  17170. this.sortObjects = true;
  17171. // user-defined clipping
  17172. this.clippingPlanes = [];
  17173. this.localClippingEnabled = false;
  17174. // physically based shading
  17175. this._outputColorSpace = SRGBColorSpace;
  17176. // tone mapping
  17177. this.toneMapping = NoToneMapping;
  17178. this.toneMappingExposure = 1.0;
  17179. // internal properties
  17180. const _this = this;
  17181. let _isContextLost = false;
  17182. // internal state cache
  17183. let _currentActiveCubeFace = 0;
  17184. let _currentActiveMipmapLevel = 0;
  17185. let _currentRenderTarget = null;
  17186. let _currentMaterialId = - 1;
  17187. let _currentCamera = null;
  17188. const _currentViewport = new Vector4();
  17189. const _currentScissor = new Vector4();
  17190. let _currentScissorTest = null;
  17191. const _currentClearColor = new Color( 0x000000 );
  17192. let _currentClearAlpha = 0;
  17193. //
  17194. let _width = canvas.width;
  17195. let _height = canvas.height;
  17196. let _pixelRatio = 1;
  17197. let _opaqueSort = null;
  17198. let _transparentSort = null;
  17199. const _viewport = new Vector4( 0, 0, _width, _height );
  17200. const _scissor = new Vector4( 0, 0, _width, _height );
  17201. let _scissorTest = false;
  17202. // frustum
  17203. const _frustum = new Frustum();
  17204. // clipping
  17205. let _clippingEnabled = false;
  17206. let _localClippingEnabled = false;
  17207. // camera matrices cache
  17208. const _projScreenMatrix = new Matrix4();
  17209. const _vector3 = new Vector3();
  17210. const _vector4 = new Vector4();
  17211. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  17212. let _renderBackground = false;
  17213. function getTargetPixelRatio() {
  17214. return _currentRenderTarget === null ? _pixelRatio : 1;
  17215. }
  17216. // initialize
  17217. let _gl = context;
  17218. function getContext( contextName, contextAttributes ) {
  17219. return canvas.getContext( contextName, contextAttributes );
  17220. }
  17221. try {
  17222. const contextAttributes = {
  17223. alpha: true,
  17224. depth,
  17225. stencil,
  17226. antialias,
  17227. premultipliedAlpha,
  17228. preserveDrawingBuffer,
  17229. powerPreference,
  17230. failIfMajorPerformanceCaveat,
  17231. };
  17232. // OffscreenCanvas does not have setAttribute, see #22811
  17233. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  17234. // event listeners must be registered before WebGL context is created, see #12753
  17235. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17236. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17237. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17238. if ( _gl === null ) {
  17239. const contextName = 'webgl2';
  17240. _gl = getContext( contextName, contextAttributes );
  17241. if ( _gl === null ) {
  17242. if ( getContext( contextName ) ) {
  17243. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17244. } else {
  17245. throw new Error( 'Error creating WebGL context.' );
  17246. }
  17247. }
  17248. }
  17249. } catch ( error ) {
  17250. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17251. throw error;
  17252. }
  17253. let extensions, capabilities, state, info;
  17254. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  17255. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  17256. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17257. let utils, bindingStates, uniformsGroups;
  17258. function initGLContext() {
  17259. extensions = new WebGLExtensions( _gl );
  17260. extensions.init();
  17261. utils = new WebGLUtils( _gl, extensions );
  17262. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  17263. state = new WebGLState( _gl );
  17264. info = new WebGLInfo( _gl );
  17265. properties = new WebGLProperties();
  17266. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17267. cubemaps = new WebGLCubeMaps( _this );
  17268. cubeuvmaps = new WebGLCubeUVMaps( _this );
  17269. attributes = new WebGLAttributes( _gl );
  17270. bindingStates = new WebGLBindingStates( _gl, attributes );
  17271. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  17272. objects = new WebGLObjects( _gl, geometries, attributes, info );
  17273. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  17274. clipping = new WebGLClipping( properties );
  17275. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  17276. materials = new WebGLMaterials( _this, properties );
  17277. renderLists = new WebGLRenderLists();
  17278. renderStates = new WebGLRenderStates( extensions );
  17279. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  17280. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  17281. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  17282. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  17283. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  17284. info.programs = programCache.programs;
  17285. _this.capabilities = capabilities;
  17286. _this.extensions = extensions;
  17287. _this.properties = properties;
  17288. _this.renderLists = renderLists;
  17289. _this.shadowMap = shadowMap;
  17290. _this.state = state;
  17291. _this.info = info;
  17292. }
  17293. initGLContext();
  17294. // xr
  17295. const xr = new WebXRManager( _this, _gl );
  17296. this.xr = xr;
  17297. // API
  17298. this.getContext = function () {
  17299. return _gl;
  17300. };
  17301. this.getContextAttributes = function () {
  17302. return _gl.getContextAttributes();
  17303. };
  17304. this.forceContextLoss = function () {
  17305. const extension = extensions.get( 'WEBGL_lose_context' );
  17306. if ( extension ) extension.loseContext();
  17307. };
  17308. this.forceContextRestore = function () {
  17309. const extension = extensions.get( 'WEBGL_lose_context' );
  17310. if ( extension ) extension.restoreContext();
  17311. };
  17312. this.getPixelRatio = function () {
  17313. return _pixelRatio;
  17314. };
  17315. this.setPixelRatio = function ( value ) {
  17316. if ( value === undefined ) return;
  17317. _pixelRatio = value;
  17318. this.setSize( _width, _height, false );
  17319. };
  17320. this.getSize = function ( target ) {
  17321. return target.set( _width, _height );
  17322. };
  17323. this.setSize = function ( width, height, updateStyle = true ) {
  17324. if ( xr.isPresenting ) {
  17325. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17326. return;
  17327. }
  17328. _width = width;
  17329. _height = height;
  17330. canvas.width = Math.floor( width * _pixelRatio );
  17331. canvas.height = Math.floor( height * _pixelRatio );
  17332. if ( updateStyle === true ) {
  17333. canvas.style.width = width + 'px';
  17334. canvas.style.height = height + 'px';
  17335. }
  17336. this.setViewport( 0, 0, width, height );
  17337. };
  17338. this.getDrawingBufferSize = function ( target ) {
  17339. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17340. };
  17341. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17342. _width = width;
  17343. _height = height;
  17344. _pixelRatio = pixelRatio;
  17345. canvas.width = Math.floor( width * pixelRatio );
  17346. canvas.height = Math.floor( height * pixelRatio );
  17347. this.setViewport( 0, 0, width, height );
  17348. };
  17349. this.getCurrentViewport = function ( target ) {
  17350. return target.copy( _currentViewport );
  17351. };
  17352. this.getViewport = function ( target ) {
  17353. return target.copy( _viewport );
  17354. };
  17355. this.setViewport = function ( x, y, width, height ) {
  17356. if ( x.isVector4 ) {
  17357. _viewport.set( x.x, x.y, x.z, x.w );
  17358. } else {
  17359. _viewport.set( x, y, width, height );
  17360. }
  17361. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  17362. };
  17363. this.getScissor = function ( target ) {
  17364. return target.copy( _scissor );
  17365. };
  17366. this.setScissor = function ( x, y, width, height ) {
  17367. if ( x.isVector4 ) {
  17368. _scissor.set( x.x, x.y, x.z, x.w );
  17369. } else {
  17370. _scissor.set( x, y, width, height );
  17371. }
  17372. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  17373. };
  17374. this.getScissorTest = function () {
  17375. return _scissorTest;
  17376. };
  17377. this.setScissorTest = function ( boolean ) {
  17378. state.setScissorTest( _scissorTest = boolean );
  17379. };
  17380. this.setOpaqueSort = function ( method ) {
  17381. _opaqueSort = method;
  17382. };
  17383. this.setTransparentSort = function ( method ) {
  17384. _transparentSort = method;
  17385. };
  17386. // Clearing
  17387. this.getClearColor = function ( target ) {
  17388. return target.copy( background.getClearColor() );
  17389. };
  17390. this.setClearColor = function () {
  17391. background.setClearColor.apply( background, arguments );
  17392. };
  17393. this.getClearAlpha = function () {
  17394. return background.getClearAlpha();
  17395. };
  17396. this.setClearAlpha = function () {
  17397. background.setClearAlpha.apply( background, arguments );
  17398. };
  17399. this.clear = function ( color = true, depth = true, stencil = true ) {
  17400. let bits = 0;
  17401. if ( color ) {
  17402. // check if we're trying to clear an integer target
  17403. let isIntegerFormat = false;
  17404. if ( _currentRenderTarget !== null ) {
  17405. const targetFormat = _currentRenderTarget.texture.format;
  17406. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17407. targetFormat === RGIntegerFormat ||
  17408. targetFormat === RedIntegerFormat;
  17409. }
  17410. // use the appropriate clear functions to clear the target if it's a signed
  17411. // or unsigned integer target
  17412. if ( isIntegerFormat ) {
  17413. const targetType = _currentRenderTarget.texture.type;
  17414. const isUnsignedType = targetType === UnsignedByteType ||
  17415. targetType === UnsignedIntType ||
  17416. targetType === UnsignedShortType ||
  17417. targetType === UnsignedInt248Type ||
  17418. targetType === UnsignedShort4444Type ||
  17419. targetType === UnsignedShort5551Type;
  17420. const clearColor = background.getClearColor();
  17421. const a = background.getClearAlpha();
  17422. const r = clearColor.r;
  17423. const g = clearColor.g;
  17424. const b = clearColor.b;
  17425. if ( isUnsignedType ) {
  17426. uintClearColor[ 0 ] = r;
  17427. uintClearColor[ 1 ] = g;
  17428. uintClearColor[ 2 ] = b;
  17429. uintClearColor[ 3 ] = a;
  17430. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17431. } else {
  17432. intClearColor[ 0 ] = r;
  17433. intClearColor[ 1 ] = g;
  17434. intClearColor[ 2 ] = b;
  17435. intClearColor[ 3 ] = a;
  17436. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17437. }
  17438. } else {
  17439. bits |= _gl.COLOR_BUFFER_BIT;
  17440. }
  17441. }
  17442. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17443. if ( stencil ) {
  17444. bits |= _gl.STENCIL_BUFFER_BIT;
  17445. this.state.buffers.stencil.setMask( 0xffffffff );
  17446. }
  17447. _gl.clear( bits );
  17448. };
  17449. this.clearColor = function () {
  17450. this.clear( true, false, false );
  17451. };
  17452. this.clearDepth = function () {
  17453. this.clear( false, true, false );
  17454. };
  17455. this.clearStencil = function () {
  17456. this.clear( false, false, true );
  17457. };
  17458. //
  17459. this.dispose = function () {
  17460. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17461. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17462. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17463. renderLists.dispose();
  17464. renderStates.dispose();
  17465. properties.dispose();
  17466. cubemaps.dispose();
  17467. cubeuvmaps.dispose();
  17468. objects.dispose();
  17469. bindingStates.dispose();
  17470. uniformsGroups.dispose();
  17471. programCache.dispose();
  17472. xr.dispose();
  17473. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17474. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17475. animation.stop();
  17476. };
  17477. // Events
  17478. function onContextLost( event ) {
  17479. event.preventDefault();
  17480. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17481. _isContextLost = true;
  17482. }
  17483. function onContextRestore( /* event */ ) {
  17484. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17485. _isContextLost = false;
  17486. const infoAutoReset = info.autoReset;
  17487. const shadowMapEnabled = shadowMap.enabled;
  17488. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17489. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17490. const shadowMapType = shadowMap.type;
  17491. initGLContext();
  17492. info.autoReset = infoAutoReset;
  17493. shadowMap.enabled = shadowMapEnabled;
  17494. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17495. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17496. shadowMap.type = shadowMapType;
  17497. }
  17498. function onContextCreationError( event ) {
  17499. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17500. }
  17501. function onMaterialDispose( event ) {
  17502. const material = event.target;
  17503. material.removeEventListener( 'dispose', onMaterialDispose );
  17504. deallocateMaterial( material );
  17505. }
  17506. // Buffer deallocation
  17507. function deallocateMaterial( material ) {
  17508. releaseMaterialProgramReferences( material );
  17509. properties.remove( material );
  17510. }
  17511. function releaseMaterialProgramReferences( material ) {
  17512. const programs = properties.get( material ).programs;
  17513. if ( programs !== undefined ) {
  17514. programs.forEach( function ( program ) {
  17515. programCache.releaseProgram( program );
  17516. } );
  17517. if ( material.isShaderMaterial ) {
  17518. programCache.releaseShaderCache( material );
  17519. }
  17520. }
  17521. }
  17522. // Buffer rendering
  17523. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17524. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17525. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17526. const program = setProgram( camera, scene, geometry, material, object );
  17527. state.setMaterial( material, frontFaceCW );
  17528. //
  17529. let index = geometry.index;
  17530. let rangeFactor = 1;
  17531. if ( material.wireframe === true ) {
  17532. index = geometries.getWireframeAttribute( geometry );
  17533. if ( index === undefined ) return;
  17534. rangeFactor = 2;
  17535. }
  17536. //
  17537. const drawRange = geometry.drawRange;
  17538. const position = geometry.attributes.position;
  17539. let drawStart = drawRange.start * rangeFactor;
  17540. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17541. if ( group !== null ) {
  17542. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17543. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17544. }
  17545. if ( index !== null ) {
  17546. drawStart = Math.max( drawStart, 0 );
  17547. drawEnd = Math.min( drawEnd, index.count );
  17548. } else if ( position !== undefined && position !== null ) {
  17549. drawStart = Math.max( drawStart, 0 );
  17550. drawEnd = Math.min( drawEnd, position.count );
  17551. }
  17552. const drawCount = drawEnd - drawStart;
  17553. if ( drawCount < 0 || drawCount === Infinity ) return;
  17554. //
  17555. bindingStates.setup( object, material, program, geometry, index );
  17556. let attribute;
  17557. let renderer = bufferRenderer;
  17558. if ( index !== null ) {
  17559. attribute = attributes.get( index );
  17560. renderer = indexedBufferRenderer;
  17561. renderer.setIndex( attribute );
  17562. }
  17563. //
  17564. if ( object.isMesh ) {
  17565. if ( material.wireframe === true ) {
  17566. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17567. renderer.setMode( _gl.LINES );
  17568. } else {
  17569. renderer.setMode( _gl.TRIANGLES );
  17570. }
  17571. } else if ( object.isLine ) {
  17572. let lineWidth = material.linewidth;
  17573. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17574. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17575. if ( object.isLineSegments ) {
  17576. renderer.setMode( _gl.LINES );
  17577. } else if ( object.isLineLoop ) {
  17578. renderer.setMode( _gl.LINE_LOOP );
  17579. } else {
  17580. renderer.setMode( _gl.LINE_STRIP );
  17581. }
  17582. } else if ( object.isPoints ) {
  17583. renderer.setMode( _gl.POINTS );
  17584. } else if ( object.isSprite ) {
  17585. renderer.setMode( _gl.TRIANGLES );
  17586. }
  17587. if ( object.isBatchedMesh ) {
  17588. if ( object._multiDrawInstances !== null ) {
  17589. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  17590. } else {
  17591. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  17592. const starts = object._multiDrawStarts;
  17593. const counts = object._multiDrawCounts;
  17594. const drawCount = object._multiDrawCount;
  17595. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  17596. const uniforms = properties.get( material ).currentProgram.getUniforms();
  17597. for ( let i = 0; i < drawCount; i ++ ) {
  17598. uniforms.setValue( _gl, '_gl_DrawID', i );
  17599. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  17600. }
  17601. } else {
  17602. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17603. }
  17604. }
  17605. } else if ( object.isInstancedMesh ) {
  17606. renderer.renderInstances( drawStart, drawCount, object.count );
  17607. } else if ( geometry.isInstancedBufferGeometry ) {
  17608. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17609. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17610. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17611. } else {
  17612. renderer.render( drawStart, drawCount );
  17613. }
  17614. };
  17615. // Compile
  17616. function prepareMaterial( material, scene, object ) {
  17617. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17618. material.side = BackSide;
  17619. material.needsUpdate = true;
  17620. getProgram( material, scene, object );
  17621. material.side = FrontSide;
  17622. material.needsUpdate = true;
  17623. getProgram( material, scene, object );
  17624. material.side = DoubleSide;
  17625. } else {
  17626. getProgram( material, scene, object );
  17627. }
  17628. }
  17629. this.compile = function ( scene, camera, targetScene = null ) {
  17630. if ( targetScene === null ) targetScene = scene;
  17631. currentRenderState = renderStates.get( targetScene );
  17632. currentRenderState.init( camera );
  17633. renderStateStack.push( currentRenderState );
  17634. // gather lights from both the target scene and the new object that will be added to the scene.
  17635. targetScene.traverseVisible( function ( object ) {
  17636. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17637. currentRenderState.pushLight( object );
  17638. if ( object.castShadow ) {
  17639. currentRenderState.pushShadow( object );
  17640. }
  17641. }
  17642. } );
  17643. if ( scene !== targetScene ) {
  17644. scene.traverseVisible( function ( object ) {
  17645. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17646. currentRenderState.pushLight( object );
  17647. if ( object.castShadow ) {
  17648. currentRenderState.pushShadow( object );
  17649. }
  17650. }
  17651. } );
  17652. }
  17653. currentRenderState.setupLights();
  17654. // Only initialize materials in the new scene, not the targetScene.
  17655. const materials = new Set();
  17656. scene.traverse( function ( object ) {
  17657. const material = object.material;
  17658. if ( material ) {
  17659. if ( Array.isArray( material ) ) {
  17660. for ( let i = 0; i < material.length; i ++ ) {
  17661. const material2 = material[ i ];
  17662. prepareMaterial( material2, targetScene, object );
  17663. materials.add( material2 );
  17664. }
  17665. } else {
  17666. prepareMaterial( material, targetScene, object );
  17667. materials.add( material );
  17668. }
  17669. }
  17670. } );
  17671. renderStateStack.pop();
  17672. currentRenderState = null;
  17673. return materials;
  17674. };
  17675. // compileAsync
  17676. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17677. const materials = this.compile( scene, camera, targetScene );
  17678. // Wait for all the materials in the new object to indicate that they're
  17679. // ready to be used before resolving the promise.
  17680. return new Promise( ( resolve ) => {
  17681. function checkMaterialsReady() {
  17682. materials.forEach( function ( material ) {
  17683. const materialProperties = properties.get( material );
  17684. const program = materialProperties.currentProgram;
  17685. if ( program.isReady() ) {
  17686. // remove any programs that report they're ready to use from the list
  17687. materials.delete( material );
  17688. }
  17689. } );
  17690. // once the list of compiling materials is empty, call the callback
  17691. if ( materials.size === 0 ) {
  17692. resolve( scene );
  17693. return;
  17694. }
  17695. // if some materials are still not ready, wait a bit and check again
  17696. setTimeout( checkMaterialsReady, 10 );
  17697. }
  17698. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17699. // If we can check the compilation status of the materials without
  17700. // blocking then do so right away.
  17701. checkMaterialsReady();
  17702. } else {
  17703. // Otherwise start by waiting a bit to give the materials we just
  17704. // initialized a chance to finish.
  17705. setTimeout( checkMaterialsReady, 10 );
  17706. }
  17707. } );
  17708. };
  17709. // Animation Loop
  17710. let onAnimationFrameCallback = null;
  17711. function onAnimationFrame( time ) {
  17712. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17713. }
  17714. function onXRSessionStart() {
  17715. animation.stop();
  17716. }
  17717. function onXRSessionEnd() {
  17718. animation.start();
  17719. }
  17720. const animation = new WebGLAnimation();
  17721. animation.setAnimationLoop( onAnimationFrame );
  17722. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17723. this.setAnimationLoop = function ( callback ) {
  17724. onAnimationFrameCallback = callback;
  17725. xr.setAnimationLoop( callback );
  17726. ( callback === null ) ? animation.stop() : animation.start();
  17727. };
  17728. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17729. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17730. // Rendering
  17731. this.render = function ( scene, camera ) {
  17732. if ( camera !== undefined && camera.isCamera !== true ) {
  17733. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17734. return;
  17735. }
  17736. if ( _isContextLost === true ) return;
  17737. // update scene graph
  17738. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17739. // update camera matrices and frustum
  17740. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17741. if ( xr.enabled === true && xr.isPresenting === true ) {
  17742. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17743. camera = xr.getCamera(); // use XR camera for rendering
  17744. }
  17745. //
  17746. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17747. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17748. currentRenderState.init( camera );
  17749. renderStateStack.push( currentRenderState );
  17750. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17751. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17752. _localClippingEnabled = this.localClippingEnabled;
  17753. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17754. currentRenderList = renderLists.get( scene, renderListStack.length );
  17755. currentRenderList.init();
  17756. renderListStack.push( currentRenderList );
  17757. if ( xr.enabled === true && xr.isPresenting === true ) {
  17758. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  17759. if ( depthSensingMesh !== null ) {
  17760. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  17761. }
  17762. }
  17763. projectObject( scene, camera, 0, _this.sortObjects );
  17764. currentRenderList.finish();
  17765. if ( _this.sortObjects === true ) {
  17766. currentRenderList.sort( _opaqueSort, _transparentSort );
  17767. }
  17768. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  17769. if ( _renderBackground ) {
  17770. background.addToRenderList( currentRenderList, scene );
  17771. }
  17772. //
  17773. this.info.render.frame ++;
  17774. if ( _clippingEnabled === true ) clipping.beginShadows();
  17775. const shadowsArray = currentRenderState.state.shadowsArray;
  17776. shadowMap.render( shadowsArray, scene, camera );
  17777. if ( _clippingEnabled === true ) clipping.endShadows();
  17778. //
  17779. if ( this.info.autoReset === true ) this.info.reset();
  17780. // render scene
  17781. const opaqueObjects = currentRenderList.opaque;
  17782. const transmissiveObjects = currentRenderList.transmissive;
  17783. currentRenderState.setupLights();
  17784. if ( camera.isArrayCamera ) {
  17785. const cameras = camera.cameras;
  17786. if ( transmissiveObjects.length > 0 ) {
  17787. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17788. const camera2 = cameras[ i ];
  17789. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  17790. }
  17791. }
  17792. if ( _renderBackground ) background.render( scene );
  17793. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17794. const camera2 = cameras[ i ];
  17795. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17796. }
  17797. } else {
  17798. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17799. if ( _renderBackground ) background.render( scene );
  17800. renderScene( currentRenderList, scene, camera );
  17801. }
  17802. //
  17803. if ( _currentRenderTarget !== null ) {
  17804. // resolve multisample renderbuffers to a single-sample texture if necessary
  17805. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17806. // Generate mipmap if we're using any kind of mipmap filtering
  17807. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17808. }
  17809. //
  17810. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17811. // _gl.finish();
  17812. bindingStates.resetDefaultState();
  17813. _currentMaterialId = - 1;
  17814. _currentCamera = null;
  17815. renderStateStack.pop();
  17816. if ( renderStateStack.length > 0 ) {
  17817. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17818. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  17819. } else {
  17820. currentRenderState = null;
  17821. }
  17822. renderListStack.pop();
  17823. if ( renderListStack.length > 0 ) {
  17824. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17825. } else {
  17826. currentRenderList = null;
  17827. }
  17828. };
  17829. function projectObject( object, camera, groupOrder, sortObjects ) {
  17830. if ( object.visible === false ) return;
  17831. const visible = object.layers.test( camera.layers );
  17832. if ( visible ) {
  17833. if ( object.isGroup ) {
  17834. groupOrder = object.renderOrder;
  17835. } else if ( object.isLOD ) {
  17836. if ( object.autoUpdate === true ) object.update( camera );
  17837. } else if ( object.isLight ) {
  17838. currentRenderState.pushLight( object );
  17839. if ( object.castShadow ) {
  17840. currentRenderState.pushShadow( object );
  17841. }
  17842. } else if ( object.isSprite ) {
  17843. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17844. if ( sortObjects ) {
  17845. _vector4.setFromMatrixPosition( object.matrixWorld )
  17846. .applyMatrix4( _projScreenMatrix );
  17847. }
  17848. const geometry = objects.update( object );
  17849. const material = object.material;
  17850. if ( material.visible ) {
  17851. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  17852. }
  17853. }
  17854. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17855. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17856. const geometry = objects.update( object );
  17857. const material = object.material;
  17858. if ( sortObjects ) {
  17859. if ( object.boundingSphere !== undefined ) {
  17860. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17861. _vector4.copy( object.boundingSphere.center );
  17862. } else {
  17863. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17864. _vector4.copy( geometry.boundingSphere.center );
  17865. }
  17866. _vector4
  17867. .applyMatrix4( object.matrixWorld )
  17868. .applyMatrix4( _projScreenMatrix );
  17869. }
  17870. if ( Array.isArray( material ) ) {
  17871. const groups = geometry.groups;
  17872. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17873. const group = groups[ i ];
  17874. const groupMaterial = material[ group.materialIndex ];
  17875. if ( groupMaterial && groupMaterial.visible ) {
  17876. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  17877. }
  17878. }
  17879. } else if ( material.visible ) {
  17880. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  17881. }
  17882. }
  17883. }
  17884. }
  17885. const children = object.children;
  17886. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17887. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17888. }
  17889. }
  17890. function renderScene( currentRenderList, scene, camera, viewport ) {
  17891. const opaqueObjects = currentRenderList.opaque;
  17892. const transmissiveObjects = currentRenderList.transmissive;
  17893. const transparentObjects = currentRenderList.transparent;
  17894. currentRenderState.setupLightsView( camera );
  17895. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17896. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17897. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17898. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17899. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17900. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17901. state.buffers.depth.setTest( true );
  17902. state.buffers.depth.setMask( true );
  17903. state.buffers.color.setMask( true );
  17904. state.setPolygonOffset( false );
  17905. }
  17906. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17907. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17908. if ( overrideMaterial !== null ) {
  17909. return;
  17910. }
  17911. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  17912. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  17913. generateMipmaps: true,
  17914. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  17915. minFilter: LinearMipmapLinearFilter,
  17916. samples: 4,
  17917. stencilBuffer: stencil,
  17918. resolveDepthBuffer: false,
  17919. resolveStencilBuffer: false,
  17920. colorSpace: ColorManagement.workingColorSpace,
  17921. } );
  17922. // debug
  17923. /*
  17924. const geometry = new PlaneGeometry();
  17925. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17926. const mesh = new Mesh( geometry, material );
  17927. scene.add( mesh );
  17928. */
  17929. }
  17930. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  17931. const activeViewport = camera.viewport || _currentViewport;
  17932. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  17933. //
  17934. const currentRenderTarget = _this.getRenderTarget();
  17935. _this.setRenderTarget( transmissionRenderTarget );
  17936. _this.getClearColor( _currentClearColor );
  17937. _currentClearAlpha = _this.getClearAlpha();
  17938. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17939. _this.clear();
  17940. if ( _renderBackground ) background.render( scene );
  17941. // Turn off the features which can affect the frag color for opaque objects pass.
  17942. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17943. const currentToneMapping = _this.toneMapping;
  17944. _this.toneMapping = NoToneMapping;
  17945. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  17946. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  17947. const currentCameraViewport = camera.viewport;
  17948. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  17949. currentRenderState.setupLightsView( camera );
  17950. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17951. renderObjects( opaqueObjects, scene, camera );
  17952. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17953. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17954. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  17955. let renderTargetNeedsUpdate = false;
  17956. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17957. const renderItem = transmissiveObjects[ i ];
  17958. const object = renderItem.object;
  17959. const geometry = renderItem.geometry;
  17960. const material = renderItem.material;
  17961. const group = renderItem.group;
  17962. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17963. const currentSide = material.side;
  17964. material.side = BackSide;
  17965. material.needsUpdate = true;
  17966. renderObject( object, scene, camera, geometry, material, group );
  17967. material.side = currentSide;
  17968. material.needsUpdate = true;
  17969. renderTargetNeedsUpdate = true;
  17970. }
  17971. }
  17972. if ( renderTargetNeedsUpdate === true ) {
  17973. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17974. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17975. }
  17976. }
  17977. _this.setRenderTarget( currentRenderTarget );
  17978. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17979. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  17980. _this.toneMapping = currentToneMapping;
  17981. }
  17982. function renderObjects( renderList, scene, camera ) {
  17983. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17984. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17985. const renderItem = renderList[ i ];
  17986. const object = renderItem.object;
  17987. const geometry = renderItem.geometry;
  17988. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17989. const group = renderItem.group;
  17990. if ( object.layers.test( camera.layers ) ) {
  17991. renderObject( object, scene, camera, geometry, material, group );
  17992. }
  17993. }
  17994. }
  17995. function renderObject( object, scene, camera, geometry, material, group ) {
  17996. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17997. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17998. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17999. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  18000. material.side = BackSide;
  18001. material.needsUpdate = true;
  18002. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  18003. material.side = FrontSide;
  18004. material.needsUpdate = true;
  18005. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  18006. material.side = DoubleSide;
  18007. } else {
  18008. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  18009. }
  18010. object.onAfterRender( _this, scene, camera, geometry, material, group );
  18011. }
  18012. function getProgram( material, scene, object ) {
  18013. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  18014. const materialProperties = properties.get( material );
  18015. const lights = currentRenderState.state.lights;
  18016. const shadowsArray = currentRenderState.state.shadowsArray;
  18017. const lightsStateVersion = lights.state.version;
  18018. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  18019. const programCacheKey = programCache.getProgramCacheKey( parameters );
  18020. let programs = materialProperties.programs;
  18021. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  18022. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  18023. materialProperties.fog = scene.fog;
  18024. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  18025. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  18026. if ( programs === undefined ) {
  18027. // new material
  18028. material.addEventListener( 'dispose', onMaterialDispose );
  18029. programs = new Map();
  18030. materialProperties.programs = programs;
  18031. }
  18032. let program = programs.get( programCacheKey );
  18033. if ( program !== undefined ) {
  18034. // early out if program and light state is identical
  18035. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  18036. updateCommonMaterialProperties( material, parameters );
  18037. return program;
  18038. }
  18039. } else {
  18040. parameters.uniforms = programCache.getUniforms( material );
  18041. material.onBeforeCompile( parameters, _this );
  18042. program = programCache.acquireProgram( parameters, programCacheKey );
  18043. programs.set( programCacheKey, program );
  18044. materialProperties.uniforms = parameters.uniforms;
  18045. }
  18046. const uniforms = materialProperties.uniforms;
  18047. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  18048. uniforms.clippingPlanes = clipping.uniform;
  18049. }
  18050. updateCommonMaterialProperties( material, parameters );
  18051. // store the light setup it was created for
  18052. materialProperties.needsLights = materialNeedsLights( material );
  18053. materialProperties.lightsStateVersion = lightsStateVersion;
  18054. if ( materialProperties.needsLights ) {
  18055. // wire up the material to this renderer's lighting state
  18056. uniforms.ambientLightColor.value = lights.state.ambient;
  18057. uniforms.lightProbe.value = lights.state.probe;
  18058. uniforms.directionalLights.value = lights.state.directional;
  18059. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  18060. uniforms.spotLights.value = lights.state.spot;
  18061. uniforms.spotLightShadows.value = lights.state.spotShadow;
  18062. uniforms.rectAreaLights.value = lights.state.rectArea;
  18063. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  18064. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  18065. uniforms.pointLights.value = lights.state.point;
  18066. uniforms.pointLightShadows.value = lights.state.pointShadow;
  18067. uniforms.hemisphereLights.value = lights.state.hemi;
  18068. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  18069. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  18070. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  18071. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  18072. uniforms.spotLightMap.value = lights.state.spotLightMap;
  18073. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  18074. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  18075. // TODO (abelnation): add area lights shadow info to uniforms
  18076. }
  18077. materialProperties.currentProgram = program;
  18078. materialProperties.uniformsList = null;
  18079. return program;
  18080. }
  18081. function getUniformList( materialProperties ) {
  18082. if ( materialProperties.uniformsList === null ) {
  18083. const progUniforms = materialProperties.currentProgram.getUniforms();
  18084. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  18085. }
  18086. return materialProperties.uniformsList;
  18087. }
  18088. function updateCommonMaterialProperties( material, parameters ) {
  18089. const materialProperties = properties.get( material );
  18090. materialProperties.outputColorSpace = parameters.outputColorSpace;
  18091. materialProperties.batching = parameters.batching;
  18092. materialProperties.batchingColor = parameters.batchingColor;
  18093. materialProperties.instancing = parameters.instancing;
  18094. materialProperties.instancingColor = parameters.instancingColor;
  18095. materialProperties.instancingMorph = parameters.instancingMorph;
  18096. materialProperties.skinning = parameters.skinning;
  18097. materialProperties.morphTargets = parameters.morphTargets;
  18098. materialProperties.morphNormals = parameters.morphNormals;
  18099. materialProperties.morphColors = parameters.morphColors;
  18100. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  18101. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  18102. materialProperties.numIntersection = parameters.numClipIntersection;
  18103. materialProperties.vertexAlphas = parameters.vertexAlphas;
  18104. materialProperties.vertexTangents = parameters.vertexTangents;
  18105. materialProperties.toneMapping = parameters.toneMapping;
  18106. }
  18107. function setProgram( camera, scene, geometry, material, object ) {
  18108. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  18109. textures.resetTextureUnits();
  18110. const fog = scene.fog;
  18111. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  18112. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  18113. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  18114. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  18115. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  18116. const morphTargets = !! geometry.morphAttributes.position;
  18117. const morphNormals = !! geometry.morphAttributes.normal;
  18118. const morphColors = !! geometry.morphAttributes.color;
  18119. let toneMapping = NoToneMapping;
  18120. if ( material.toneMapped ) {
  18121. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  18122. toneMapping = _this.toneMapping;
  18123. }
  18124. }
  18125. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  18126. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  18127. const materialProperties = properties.get( material );
  18128. const lights = currentRenderState.state.lights;
  18129. if ( _clippingEnabled === true ) {
  18130. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  18131. const useCache =
  18132. camera === _currentCamera &&
  18133. material.id === _currentMaterialId;
  18134. // we might want to call this function with some ClippingGroup
  18135. // object instead of the material, once it becomes feasible
  18136. // (#8465, #8379)
  18137. clipping.setState( material, camera, useCache );
  18138. }
  18139. }
  18140. //
  18141. let needsProgramChange = false;
  18142. if ( material.version === materialProperties.__version ) {
  18143. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  18144. needsProgramChange = true;
  18145. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  18146. needsProgramChange = true;
  18147. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  18148. needsProgramChange = true;
  18149. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  18150. needsProgramChange = true;
  18151. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  18152. needsProgramChange = true;
  18153. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  18154. needsProgramChange = true;
  18155. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  18156. needsProgramChange = true;
  18157. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  18158. needsProgramChange = true;
  18159. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  18160. needsProgramChange = true;
  18161. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  18162. needsProgramChange = true;
  18163. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  18164. needsProgramChange = true;
  18165. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  18166. needsProgramChange = true;
  18167. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  18168. needsProgramChange = true;
  18169. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  18170. needsProgramChange = true;
  18171. } else if ( materialProperties.envMap !== envMap ) {
  18172. needsProgramChange = true;
  18173. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  18174. needsProgramChange = true;
  18175. } else if ( materialProperties.numClippingPlanes !== undefined &&
  18176. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  18177. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  18178. needsProgramChange = true;
  18179. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  18180. needsProgramChange = true;
  18181. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  18182. needsProgramChange = true;
  18183. } else if ( materialProperties.morphTargets !== morphTargets ) {
  18184. needsProgramChange = true;
  18185. } else if ( materialProperties.morphNormals !== morphNormals ) {
  18186. needsProgramChange = true;
  18187. } else if ( materialProperties.morphColors !== morphColors ) {
  18188. needsProgramChange = true;
  18189. } else if ( materialProperties.toneMapping !== toneMapping ) {
  18190. needsProgramChange = true;
  18191. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  18192. needsProgramChange = true;
  18193. }
  18194. } else {
  18195. needsProgramChange = true;
  18196. materialProperties.__version = material.version;
  18197. }
  18198. //
  18199. let program = materialProperties.currentProgram;
  18200. if ( needsProgramChange === true ) {
  18201. program = getProgram( material, scene, object );
  18202. }
  18203. let refreshProgram = false;
  18204. let refreshMaterial = false;
  18205. let refreshLights = false;
  18206. const p_uniforms = program.getUniforms(),
  18207. m_uniforms = materialProperties.uniforms;
  18208. if ( state.useProgram( program.program ) ) {
  18209. refreshProgram = true;
  18210. refreshMaterial = true;
  18211. refreshLights = true;
  18212. }
  18213. if ( material.id !== _currentMaterialId ) {
  18214. _currentMaterialId = material.id;
  18215. refreshMaterial = true;
  18216. }
  18217. if ( refreshProgram || _currentCamera !== camera ) {
  18218. // common camera uniforms
  18219. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  18220. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18221. const uCamPos = p_uniforms.map.cameraPosition;
  18222. if ( uCamPos !== undefined ) {
  18223. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18224. }
  18225. if ( capabilities.logarithmicDepthBuffer ) {
  18226. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18227. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18228. }
  18229. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  18230. if ( material.isMeshPhongMaterial ||
  18231. material.isMeshToonMaterial ||
  18232. material.isMeshLambertMaterial ||
  18233. material.isMeshBasicMaterial ||
  18234. material.isMeshStandardMaterial ||
  18235. material.isShaderMaterial ) {
  18236. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  18237. }
  18238. if ( _currentCamera !== camera ) {
  18239. _currentCamera = camera;
  18240. // lighting uniforms depend on the camera so enforce an update
  18241. // now, in case this material supports lights - or later, when
  18242. // the next material that does gets activated:
  18243. refreshMaterial = true; // set to true on material change
  18244. refreshLights = true; // remains set until update done
  18245. }
  18246. }
  18247. // skinning and morph target uniforms must be set even if material didn't change
  18248. // auto-setting of texture unit for bone and morph texture must go before other textures
  18249. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  18250. if ( object.isSkinnedMesh ) {
  18251. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18252. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18253. const skeleton = object.skeleton;
  18254. if ( skeleton ) {
  18255. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  18256. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  18257. }
  18258. }
  18259. if ( object.isBatchedMesh ) {
  18260. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  18261. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  18262. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  18263. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  18264. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  18265. if ( object._colorsTexture !== null ) {
  18266. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  18267. }
  18268. }
  18269. const morphAttributes = geometry.morphAttributes;
  18270. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  18271. morphtargets.update( object, geometry, program );
  18272. }
  18273. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  18274. materialProperties.receiveShadow = object.receiveShadow;
  18275. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  18276. }
  18277. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  18278. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  18279. m_uniforms.envMap.value = envMap;
  18280. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  18281. }
  18282. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  18283. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  18284. }
  18285. if ( refreshMaterial ) {
  18286. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18287. if ( materialProperties.needsLights ) {
  18288. // the current material requires lighting info
  18289. // note: all lighting uniforms are always set correctly
  18290. // they simply reference the renderer's state for their
  18291. // values
  18292. //
  18293. // use the current material's .needsUpdate flags to set
  18294. // the GL state when required
  18295. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18296. }
  18297. // refresh uniforms common to several materials
  18298. if ( fog && material.fog === true ) {
  18299. materials.refreshFogUniforms( m_uniforms, fog );
  18300. }
  18301. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  18302. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18303. }
  18304. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18305. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18306. material.uniformsNeedUpdate = false;
  18307. }
  18308. if ( material.isSpriteMaterial ) {
  18309. p_uniforms.setValue( _gl, 'center', object.center );
  18310. }
  18311. // common matrices
  18312. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18313. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18314. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18315. // UBOs
  18316. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  18317. const groups = material.uniformsGroups;
  18318. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  18319. const group = groups[ i ];
  18320. uniformsGroups.update( group, program );
  18321. uniformsGroups.bind( group, program );
  18322. }
  18323. }
  18324. return program;
  18325. }
  18326. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18327. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18328. uniforms.ambientLightColor.needsUpdate = value;
  18329. uniforms.lightProbe.needsUpdate = value;
  18330. uniforms.directionalLights.needsUpdate = value;
  18331. uniforms.directionalLightShadows.needsUpdate = value;
  18332. uniforms.pointLights.needsUpdate = value;
  18333. uniforms.pointLightShadows.needsUpdate = value;
  18334. uniforms.spotLights.needsUpdate = value;
  18335. uniforms.spotLightShadows.needsUpdate = value;
  18336. uniforms.rectAreaLights.needsUpdate = value;
  18337. uniforms.hemisphereLights.needsUpdate = value;
  18338. }
  18339. function materialNeedsLights( material ) {
  18340. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  18341. material.isMeshStandardMaterial || material.isShadowMaterial ||
  18342. ( material.isShaderMaterial && material.lights === true );
  18343. }
  18344. this.getActiveCubeFace = function () {
  18345. return _currentActiveCubeFace;
  18346. };
  18347. this.getActiveMipmapLevel = function () {
  18348. return _currentActiveMipmapLevel;
  18349. };
  18350. this.getRenderTarget = function () {
  18351. return _currentRenderTarget;
  18352. };
  18353. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  18354. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  18355. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  18356. const renderTargetProperties = properties.get( renderTarget );
  18357. renderTargetProperties.__hasExternalTextures = true;
  18358. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  18359. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  18360. // The multisample_render_to_texture extension doesn't work properly if there
  18361. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18362. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18363. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18364. renderTargetProperties.__useRenderToTexture = false;
  18365. }
  18366. }
  18367. };
  18368. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18369. const renderTargetProperties = properties.get( renderTarget );
  18370. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18371. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18372. };
  18373. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18374. _currentRenderTarget = renderTarget;
  18375. _currentActiveCubeFace = activeCubeFace;
  18376. _currentActiveMipmapLevel = activeMipmapLevel;
  18377. let useDefaultFramebuffer = true;
  18378. let framebuffer = null;
  18379. let isCube = false;
  18380. let isRenderTarget3D = false;
  18381. if ( renderTarget ) {
  18382. const renderTargetProperties = properties.get( renderTarget );
  18383. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18384. // We need to make sure to rebind the framebuffer.
  18385. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18386. useDefaultFramebuffer = false;
  18387. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18388. textures.setupRenderTarget( renderTarget );
  18389. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18390. // Color and depth texture must be rebound in order for the swapchain to update.
  18391. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18392. }
  18393. const texture = renderTarget.texture;
  18394. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18395. isRenderTarget3D = true;
  18396. }
  18397. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18398. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18399. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18400. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18401. } else {
  18402. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18403. }
  18404. isCube = true;
  18405. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18406. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18407. } else {
  18408. if ( Array.isArray( __webglFramebuffer ) ) {
  18409. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18410. } else {
  18411. framebuffer = __webglFramebuffer;
  18412. }
  18413. }
  18414. _currentViewport.copy( renderTarget.viewport );
  18415. _currentScissor.copy( renderTarget.scissor );
  18416. _currentScissorTest = renderTarget.scissorTest;
  18417. } else {
  18418. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18419. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18420. _currentScissorTest = _scissorTest;
  18421. }
  18422. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18423. if ( framebufferBound && useDefaultFramebuffer ) {
  18424. state.drawBuffers( renderTarget, framebuffer );
  18425. }
  18426. state.viewport( _currentViewport );
  18427. state.scissor( _currentScissor );
  18428. state.setScissorTest( _currentScissorTest );
  18429. if ( isCube ) {
  18430. const textureProperties = properties.get( renderTarget.texture );
  18431. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18432. } else if ( isRenderTarget3D ) {
  18433. const textureProperties = properties.get( renderTarget.texture );
  18434. const layer = activeCubeFace || 0;
  18435. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18436. }
  18437. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18438. };
  18439. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18440. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18441. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18442. return;
  18443. }
  18444. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18445. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18446. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18447. }
  18448. if ( framebuffer ) {
  18449. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18450. try {
  18451. const texture = renderTarget.texture;
  18452. const textureFormat = texture.format;
  18453. const textureType = texture.type;
  18454. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  18455. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18456. return;
  18457. }
  18458. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  18459. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18460. return;
  18461. }
  18462. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18463. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18464. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18465. }
  18466. } finally {
  18467. // restore framebuffer of current render target if necessary
  18468. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18469. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18470. }
  18471. }
  18472. };
  18473. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18474. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18475. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18476. }
  18477. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18478. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18479. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18480. }
  18481. if ( framebuffer ) {
  18482. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18483. try {
  18484. const texture = renderTarget.texture;
  18485. const textureFormat = texture.format;
  18486. const textureType = texture.type;
  18487. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  18488. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  18489. }
  18490. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  18491. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18492. }
  18493. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18494. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18495. const glBuffer = _gl.createBuffer();
  18496. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  18497. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  18498. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  18499. _gl.flush();
  18500. // check if the commands have finished every 8 ms
  18501. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  18502. await probeAsync( _gl, sync, 4 );
  18503. try {
  18504. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  18505. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  18506. } finally {
  18507. _gl.deleteBuffer( glBuffer );
  18508. _gl.deleteSync( sync );
  18509. }
  18510. return buffer;
  18511. }
  18512. } finally {
  18513. // restore framebuffer of current render target if necessary
  18514. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18515. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18516. }
  18517. }
  18518. };
  18519. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  18520. // support previous signature with position first
  18521. if ( texture.isTexture !== true ) {
  18522. // @deprecated, r165
  18523. warnOnce( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  18524. position = arguments[ 0 ] || null;
  18525. texture = arguments[ 1 ];
  18526. }
  18527. const levelScale = Math.pow( 2, - level );
  18528. const width = Math.floor( texture.image.width * levelScale );
  18529. const height = Math.floor( texture.image.height * levelScale );
  18530. const x = position !== null ? position.x : 0;
  18531. const y = position !== null ? position.y : 0;
  18532. textures.setTexture2D( texture, 0 );
  18533. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  18534. state.unbindTexture();
  18535. };
  18536. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  18537. // support previous signature with dstPosition first
  18538. if ( srcTexture.isTexture !== true ) {
  18539. // @deprecated, r165
  18540. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  18541. dstPosition = arguments[ 0 ] || null;
  18542. srcTexture = arguments[ 1 ];
  18543. dstTexture = arguments[ 2 ];
  18544. level = arguments[ 3 ] || 0;
  18545. srcRegion = null;
  18546. }
  18547. let width, height, minX, minY;
  18548. let dstX, dstY;
  18549. if ( srcRegion !== null ) {
  18550. width = srcRegion.max.x - srcRegion.min.x;
  18551. height = srcRegion.max.y - srcRegion.min.y;
  18552. minX = srcRegion.min.x;
  18553. minY = srcRegion.min.y;
  18554. } else {
  18555. width = srcTexture.image.width;
  18556. height = srcTexture.image.height;
  18557. minX = 0;
  18558. minY = 0;
  18559. }
  18560. if ( dstPosition !== null ) {
  18561. dstX = dstPosition.x;
  18562. dstY = dstPosition.y;
  18563. } else {
  18564. dstX = 0;
  18565. dstY = 0;
  18566. }
  18567. const glFormat = utils.convert( dstTexture.format );
  18568. const glType = utils.convert( dstTexture.type );
  18569. textures.setTexture2D( dstTexture, 0 );
  18570. // As another texture upload may have changed pixelStorei
  18571. // parameters, make sure they are correct for the dstTexture
  18572. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18573. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18574. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18575. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18576. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18577. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18578. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18579. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18580. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18581. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18582. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18583. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  18584. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  18585. if ( srcTexture.isDataTexture ) {
  18586. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  18587. } else {
  18588. if ( srcTexture.isCompressedTexture ) {
  18589. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  18590. } else {
  18591. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  18592. }
  18593. }
  18594. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  18595. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  18596. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  18597. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  18598. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  18599. // Generate mipmaps only when copying level 0
  18600. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18601. state.unbindTexture();
  18602. };
  18603. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  18604. // support previous signature with source box first
  18605. if ( srcTexture.isTexture !== true ) {
  18606. // @deprecated, r165
  18607. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  18608. srcRegion = arguments[ 0 ] || null;
  18609. dstPosition = arguments[ 1 ] || null;
  18610. srcTexture = arguments[ 2 ];
  18611. dstTexture = arguments[ 3 ];
  18612. level = arguments[ 4 ] || 0;
  18613. }
  18614. let width, height, depth, minX, minY, minZ;
  18615. let dstX, dstY, dstZ;
  18616. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18617. if ( srcRegion !== null ) {
  18618. width = srcRegion.max.x - srcRegion.min.x;
  18619. height = srcRegion.max.y - srcRegion.min.y;
  18620. depth = srcRegion.max.z - srcRegion.min.z;
  18621. minX = srcRegion.min.x;
  18622. minY = srcRegion.min.y;
  18623. minZ = srcRegion.min.z;
  18624. } else {
  18625. width = image.width;
  18626. height = image.height;
  18627. depth = image.depth;
  18628. minX = 0;
  18629. minY = 0;
  18630. minZ = 0;
  18631. }
  18632. if ( dstPosition !== null ) {
  18633. dstX = dstPosition.x;
  18634. dstY = dstPosition.y;
  18635. dstZ = dstPosition.z;
  18636. } else {
  18637. dstX = 0;
  18638. dstY = 0;
  18639. dstZ = 0;
  18640. }
  18641. const glFormat = utils.convert( dstTexture.format );
  18642. const glType = utils.convert( dstTexture.type );
  18643. let glTarget;
  18644. if ( dstTexture.isData3DTexture ) {
  18645. textures.setTexture3D( dstTexture, 0 );
  18646. glTarget = _gl.TEXTURE_3D;
  18647. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18648. textures.setTexture2DArray( dstTexture, 0 );
  18649. glTarget = _gl.TEXTURE_2D_ARRAY;
  18650. } else {
  18651. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18652. return;
  18653. }
  18654. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18655. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18656. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18657. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18658. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18659. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18660. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18661. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18662. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18663. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18664. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  18665. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  18666. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  18667. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18668. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  18669. } else {
  18670. if ( dstTexture.isCompressedArrayTexture ) {
  18671. _gl.compressedTexSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  18672. } else {
  18673. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  18674. }
  18675. }
  18676. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  18677. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  18678. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  18679. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  18680. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  18681. // Generate mipmaps only when copying level 0
  18682. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18683. state.unbindTexture();
  18684. };
  18685. this.initRenderTarget = function ( target ) {
  18686. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  18687. textures.setupRenderTarget( target );
  18688. }
  18689. };
  18690. this.initTexture = function ( texture ) {
  18691. if ( texture.isCubeTexture ) {
  18692. textures.setTextureCube( texture, 0 );
  18693. } else if ( texture.isData3DTexture ) {
  18694. textures.setTexture3D( texture, 0 );
  18695. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18696. textures.setTexture2DArray( texture, 0 );
  18697. } else {
  18698. textures.setTexture2D( texture, 0 );
  18699. }
  18700. state.unbindTexture();
  18701. };
  18702. this.resetState = function () {
  18703. _currentActiveCubeFace = 0;
  18704. _currentActiveMipmapLevel = 0;
  18705. _currentRenderTarget = null;
  18706. state.reset();
  18707. bindingStates.reset();
  18708. };
  18709. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18710. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18711. }
  18712. }
  18713. get coordinateSystem() {
  18714. return WebGLCoordinateSystem;
  18715. }
  18716. get outputColorSpace() {
  18717. return this._outputColorSpace;
  18718. }
  18719. set outputColorSpace( colorSpace ) {
  18720. this._outputColorSpace = colorSpace;
  18721. const gl = this.getContext();
  18722. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18723. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18724. }
  18725. }
  18726. class FogExp2 {
  18727. constructor( color, density = 0.00025 ) {
  18728. this.isFogExp2 = true;
  18729. this.name = '';
  18730. this.color = new Color( color );
  18731. this.density = density;
  18732. }
  18733. clone() {
  18734. return new FogExp2( this.color, this.density );
  18735. }
  18736. toJSON( /* meta */ ) {
  18737. return {
  18738. type: 'FogExp2',
  18739. name: this.name,
  18740. color: this.color.getHex(),
  18741. density: this.density
  18742. };
  18743. }
  18744. }
  18745. class Fog {
  18746. constructor( color, near = 1, far = 1000 ) {
  18747. this.isFog = true;
  18748. this.name = '';
  18749. this.color = new Color( color );
  18750. this.near = near;
  18751. this.far = far;
  18752. }
  18753. clone() {
  18754. return new Fog( this.color, this.near, this.far );
  18755. }
  18756. toJSON( /* meta */ ) {
  18757. return {
  18758. type: 'Fog',
  18759. name: this.name,
  18760. color: this.color.getHex(),
  18761. near: this.near,
  18762. far: this.far
  18763. };
  18764. }
  18765. }
  18766. class Scene extends Object3D {
  18767. constructor() {
  18768. super();
  18769. this.isScene = true;
  18770. this.type = 'Scene';
  18771. this.background = null;
  18772. this.environment = null;
  18773. this.fog = null;
  18774. this.backgroundBlurriness = 0;
  18775. this.backgroundIntensity = 1;
  18776. this.backgroundRotation = new Euler();
  18777. this.environmentIntensity = 1;
  18778. this.environmentRotation = new Euler();
  18779. this.overrideMaterial = null;
  18780. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18781. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18782. }
  18783. }
  18784. copy( source, recursive ) {
  18785. super.copy( source, recursive );
  18786. if ( source.background !== null ) this.background = source.background.clone();
  18787. if ( source.environment !== null ) this.environment = source.environment.clone();
  18788. if ( source.fog !== null ) this.fog = source.fog.clone();
  18789. this.backgroundBlurriness = source.backgroundBlurriness;
  18790. this.backgroundIntensity = source.backgroundIntensity;
  18791. this.backgroundRotation.copy( source.backgroundRotation );
  18792. this.environmentIntensity = source.environmentIntensity;
  18793. this.environmentRotation.copy( source.environmentRotation );
  18794. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18795. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18796. return this;
  18797. }
  18798. toJSON( meta ) {
  18799. const data = super.toJSON( meta );
  18800. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18801. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18802. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18803. data.object.backgroundRotation = this.backgroundRotation.toArray();
  18804. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  18805. data.object.environmentRotation = this.environmentRotation.toArray();
  18806. return data;
  18807. }
  18808. }
  18809. class InterleavedBuffer {
  18810. constructor( array, stride ) {
  18811. this.isInterleavedBuffer = true;
  18812. this.array = array;
  18813. this.stride = stride;
  18814. this.count = array !== undefined ? array.length / stride : 0;
  18815. this.usage = StaticDrawUsage;
  18816. this._updateRange = { offset: 0, count: - 1 };
  18817. this.updateRanges = [];
  18818. this.version = 0;
  18819. this.uuid = generateUUID();
  18820. }
  18821. onUploadCallback() {}
  18822. set needsUpdate( value ) {
  18823. if ( value === true ) this.version ++;
  18824. }
  18825. get updateRange() {
  18826. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  18827. return this._updateRange;
  18828. }
  18829. setUsage( value ) {
  18830. this.usage = value;
  18831. return this;
  18832. }
  18833. addUpdateRange( start, count ) {
  18834. this.updateRanges.push( { start, count } );
  18835. }
  18836. clearUpdateRanges() {
  18837. this.updateRanges.length = 0;
  18838. }
  18839. copy( source ) {
  18840. this.array = new source.array.constructor( source.array );
  18841. this.count = source.count;
  18842. this.stride = source.stride;
  18843. this.usage = source.usage;
  18844. return this;
  18845. }
  18846. copyAt( index1, attribute, index2 ) {
  18847. index1 *= this.stride;
  18848. index2 *= attribute.stride;
  18849. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18850. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18851. }
  18852. return this;
  18853. }
  18854. set( value, offset = 0 ) {
  18855. this.array.set( value, offset );
  18856. return this;
  18857. }
  18858. clone( data ) {
  18859. if ( data.arrayBuffers === undefined ) {
  18860. data.arrayBuffers = {};
  18861. }
  18862. if ( this.array.buffer._uuid === undefined ) {
  18863. this.array.buffer._uuid = generateUUID();
  18864. }
  18865. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18866. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18867. }
  18868. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18869. const ib = new this.constructor( array, this.stride );
  18870. ib.setUsage( this.usage );
  18871. return ib;
  18872. }
  18873. onUpload( callback ) {
  18874. this.onUploadCallback = callback;
  18875. return this;
  18876. }
  18877. toJSON( data ) {
  18878. if ( data.arrayBuffers === undefined ) {
  18879. data.arrayBuffers = {};
  18880. }
  18881. // generate UUID for array buffer if necessary
  18882. if ( this.array.buffer._uuid === undefined ) {
  18883. this.array.buffer._uuid = generateUUID();
  18884. }
  18885. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18886. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18887. }
  18888. //
  18889. return {
  18890. uuid: this.uuid,
  18891. buffer: this.array.buffer._uuid,
  18892. type: this.array.constructor.name,
  18893. stride: this.stride
  18894. };
  18895. }
  18896. }
  18897. const _vector$6 = /*@__PURE__*/ new Vector3();
  18898. class InterleavedBufferAttribute {
  18899. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18900. this.isInterleavedBufferAttribute = true;
  18901. this.name = '';
  18902. this.data = interleavedBuffer;
  18903. this.itemSize = itemSize;
  18904. this.offset = offset;
  18905. this.normalized = normalized;
  18906. }
  18907. get count() {
  18908. return this.data.count;
  18909. }
  18910. get array() {
  18911. return this.data.array;
  18912. }
  18913. set needsUpdate( value ) {
  18914. this.data.needsUpdate = value;
  18915. }
  18916. applyMatrix4( m ) {
  18917. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18918. _vector$6.fromBufferAttribute( this, i );
  18919. _vector$6.applyMatrix4( m );
  18920. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18921. }
  18922. return this;
  18923. }
  18924. applyNormalMatrix( m ) {
  18925. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18926. _vector$6.fromBufferAttribute( this, i );
  18927. _vector$6.applyNormalMatrix( m );
  18928. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18929. }
  18930. return this;
  18931. }
  18932. transformDirection( m ) {
  18933. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18934. _vector$6.fromBufferAttribute( this, i );
  18935. _vector$6.transformDirection( m );
  18936. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18937. }
  18938. return this;
  18939. }
  18940. getComponent( index, component ) {
  18941. let value = this.array[ index * this.data.stride + this.offset + component ];
  18942. if ( this.normalized ) value = denormalize( value, this.array );
  18943. return value;
  18944. }
  18945. setComponent( index, component, value ) {
  18946. if ( this.normalized ) value = normalize( value, this.array );
  18947. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  18948. return this;
  18949. }
  18950. setX( index, x ) {
  18951. if ( this.normalized ) x = normalize( x, this.array );
  18952. this.data.array[ index * this.data.stride + this.offset ] = x;
  18953. return this;
  18954. }
  18955. setY( index, y ) {
  18956. if ( this.normalized ) y = normalize( y, this.array );
  18957. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18958. return this;
  18959. }
  18960. setZ( index, z ) {
  18961. if ( this.normalized ) z = normalize( z, this.array );
  18962. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18963. return this;
  18964. }
  18965. setW( index, w ) {
  18966. if ( this.normalized ) w = normalize( w, this.array );
  18967. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18968. return this;
  18969. }
  18970. getX( index ) {
  18971. let x = this.data.array[ index * this.data.stride + this.offset ];
  18972. if ( this.normalized ) x = denormalize( x, this.array );
  18973. return x;
  18974. }
  18975. getY( index ) {
  18976. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18977. if ( this.normalized ) y = denormalize( y, this.array );
  18978. return y;
  18979. }
  18980. getZ( index ) {
  18981. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18982. if ( this.normalized ) z = denormalize( z, this.array );
  18983. return z;
  18984. }
  18985. getW( index ) {
  18986. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18987. if ( this.normalized ) w = denormalize( w, this.array );
  18988. return w;
  18989. }
  18990. setXY( index, x, y ) {
  18991. index = index * this.data.stride + this.offset;
  18992. if ( this.normalized ) {
  18993. x = normalize( x, this.array );
  18994. y = normalize( y, this.array );
  18995. }
  18996. this.data.array[ index + 0 ] = x;
  18997. this.data.array[ index + 1 ] = y;
  18998. return this;
  18999. }
  19000. setXYZ( index, x, y, z ) {
  19001. index = index * this.data.stride + this.offset;
  19002. if ( this.normalized ) {
  19003. x = normalize( x, this.array );
  19004. y = normalize( y, this.array );
  19005. z = normalize( z, this.array );
  19006. }
  19007. this.data.array[ index + 0 ] = x;
  19008. this.data.array[ index + 1 ] = y;
  19009. this.data.array[ index + 2 ] = z;
  19010. return this;
  19011. }
  19012. setXYZW( index, x, y, z, w ) {
  19013. index = index * this.data.stride + this.offset;
  19014. if ( this.normalized ) {
  19015. x = normalize( x, this.array );
  19016. y = normalize( y, this.array );
  19017. z = normalize( z, this.array );
  19018. w = normalize( w, this.array );
  19019. }
  19020. this.data.array[ index + 0 ] = x;
  19021. this.data.array[ index + 1 ] = y;
  19022. this.data.array[ index + 2 ] = z;
  19023. this.data.array[ index + 3 ] = w;
  19024. return this;
  19025. }
  19026. clone( data ) {
  19027. if ( data === undefined ) {
  19028. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  19029. const array = [];
  19030. for ( let i = 0; i < this.count; i ++ ) {
  19031. const index = i * this.data.stride + this.offset;
  19032. for ( let j = 0; j < this.itemSize; j ++ ) {
  19033. array.push( this.data.array[ index + j ] );
  19034. }
  19035. }
  19036. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  19037. } else {
  19038. if ( data.interleavedBuffers === undefined ) {
  19039. data.interleavedBuffers = {};
  19040. }
  19041. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  19042. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  19043. }
  19044. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  19045. }
  19046. }
  19047. toJSON( data ) {
  19048. if ( data === undefined ) {
  19049. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  19050. const array = [];
  19051. for ( let i = 0; i < this.count; i ++ ) {
  19052. const index = i * this.data.stride + this.offset;
  19053. for ( let j = 0; j < this.itemSize; j ++ ) {
  19054. array.push( this.data.array[ index + j ] );
  19055. }
  19056. }
  19057. // de-interleave data and save it as an ordinary buffer attribute for now
  19058. return {
  19059. itemSize: this.itemSize,
  19060. type: this.array.constructor.name,
  19061. array: array,
  19062. normalized: this.normalized
  19063. };
  19064. } else {
  19065. // save as true interleaved attribute
  19066. if ( data.interleavedBuffers === undefined ) {
  19067. data.interleavedBuffers = {};
  19068. }
  19069. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  19070. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  19071. }
  19072. return {
  19073. isInterleavedBufferAttribute: true,
  19074. itemSize: this.itemSize,
  19075. data: this.data.uuid,
  19076. offset: this.offset,
  19077. normalized: this.normalized
  19078. };
  19079. }
  19080. }
  19081. }
  19082. class SpriteMaterial extends Material {
  19083. constructor( parameters ) {
  19084. super();
  19085. this.isSpriteMaterial = true;
  19086. this.type = 'SpriteMaterial';
  19087. this.color = new Color( 0xffffff );
  19088. this.map = null;
  19089. this.alphaMap = null;
  19090. this.rotation = 0;
  19091. this.sizeAttenuation = true;
  19092. this.transparent = true;
  19093. this.fog = true;
  19094. this.setValues( parameters );
  19095. }
  19096. copy( source ) {
  19097. super.copy( source );
  19098. this.color.copy( source.color );
  19099. this.map = source.map;
  19100. this.alphaMap = source.alphaMap;
  19101. this.rotation = source.rotation;
  19102. this.sizeAttenuation = source.sizeAttenuation;
  19103. this.fog = source.fog;
  19104. return this;
  19105. }
  19106. }
  19107. let _geometry;
  19108. const _intersectPoint = /*@__PURE__*/ new Vector3();
  19109. const _worldScale = /*@__PURE__*/ new Vector3();
  19110. const _mvPosition = /*@__PURE__*/ new Vector3();
  19111. const _alignedPosition = /*@__PURE__*/ new Vector2();
  19112. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  19113. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  19114. const _vA = /*@__PURE__*/ new Vector3();
  19115. const _vB = /*@__PURE__*/ new Vector3();
  19116. const _vC = /*@__PURE__*/ new Vector3();
  19117. const _uvA = /*@__PURE__*/ new Vector2();
  19118. const _uvB = /*@__PURE__*/ new Vector2();
  19119. const _uvC = /*@__PURE__*/ new Vector2();
  19120. class Sprite extends Object3D {
  19121. constructor( material = new SpriteMaterial() ) {
  19122. super();
  19123. this.isSprite = true;
  19124. this.type = 'Sprite';
  19125. if ( _geometry === undefined ) {
  19126. _geometry = new BufferGeometry();
  19127. const float32Array = new Float32Array( [
  19128. - 0.5, - 0.5, 0, 0, 0,
  19129. 0.5, - 0.5, 0, 1, 0,
  19130. 0.5, 0.5, 0, 1, 1,
  19131. - 0.5, 0.5, 0, 0, 1
  19132. ] );
  19133. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  19134. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  19135. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  19136. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  19137. }
  19138. this.geometry = _geometry;
  19139. this.material = material;
  19140. this.center = new Vector2( 0.5, 0.5 );
  19141. }
  19142. raycast( raycaster, intersects ) {
  19143. if ( raycaster.camera === null ) {
  19144. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  19145. }
  19146. _worldScale.setFromMatrixScale( this.matrixWorld );
  19147. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  19148. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  19149. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  19150. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  19151. _worldScale.multiplyScalar( - _mvPosition.z );
  19152. }
  19153. const rotation = this.material.rotation;
  19154. let sin, cos;
  19155. if ( rotation !== 0 ) {
  19156. cos = Math.cos( rotation );
  19157. sin = Math.sin( rotation );
  19158. }
  19159. const center = this.center;
  19160. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19161. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19162. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19163. _uvA.set( 0, 0 );
  19164. _uvB.set( 1, 0 );
  19165. _uvC.set( 1, 1 );
  19166. // check first triangle
  19167. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  19168. if ( intersect === null ) {
  19169. // check second triangle
  19170. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19171. _uvB.set( 0, 1 );
  19172. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  19173. if ( intersect === null ) {
  19174. return;
  19175. }
  19176. }
  19177. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  19178. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19179. intersects.push( {
  19180. distance: distance,
  19181. point: _intersectPoint.clone(),
  19182. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  19183. face: null,
  19184. object: this
  19185. } );
  19186. }
  19187. copy( source, recursive ) {
  19188. super.copy( source, recursive );
  19189. if ( source.center !== undefined ) this.center.copy( source.center );
  19190. this.material = source.material;
  19191. return this;
  19192. }
  19193. }
  19194. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  19195. // compute position in camera space
  19196. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  19197. // to check if rotation is not zero
  19198. if ( sin !== undefined ) {
  19199. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  19200. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  19201. } else {
  19202. _rotatedPosition.copy( _alignedPosition );
  19203. }
  19204. vertexPosition.copy( mvPosition );
  19205. vertexPosition.x += _rotatedPosition.x;
  19206. vertexPosition.y += _rotatedPosition.y;
  19207. // transform to world space
  19208. vertexPosition.applyMatrix4( _viewWorldMatrix );
  19209. }
  19210. const _v1$2 = /*@__PURE__*/ new Vector3();
  19211. const _v2$1 = /*@__PURE__*/ new Vector3();
  19212. class LOD extends Object3D {
  19213. constructor() {
  19214. super();
  19215. this._currentLevel = 0;
  19216. this.type = 'LOD';
  19217. Object.defineProperties( this, {
  19218. levels: {
  19219. enumerable: true,
  19220. value: []
  19221. },
  19222. isLOD: {
  19223. value: true,
  19224. }
  19225. } );
  19226. this.autoUpdate = true;
  19227. }
  19228. copy( source ) {
  19229. super.copy( source, false );
  19230. const levels = source.levels;
  19231. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19232. const level = levels[ i ];
  19233. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  19234. }
  19235. this.autoUpdate = source.autoUpdate;
  19236. return this;
  19237. }
  19238. addLevel( object, distance = 0, hysteresis = 0 ) {
  19239. distance = Math.abs( distance );
  19240. const levels = this.levels;
  19241. let l;
  19242. for ( l = 0; l < levels.length; l ++ ) {
  19243. if ( distance < levels[ l ].distance ) {
  19244. break;
  19245. }
  19246. }
  19247. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  19248. this.add( object );
  19249. return this;
  19250. }
  19251. getCurrentLevel() {
  19252. return this._currentLevel;
  19253. }
  19254. getObjectForDistance( distance ) {
  19255. const levels = this.levels;
  19256. if ( levels.length > 0 ) {
  19257. let i, l;
  19258. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19259. let levelDistance = levels[ i ].distance;
  19260. if ( levels[ i ].object.visible ) {
  19261. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19262. }
  19263. if ( distance < levelDistance ) {
  19264. break;
  19265. }
  19266. }
  19267. return levels[ i - 1 ].object;
  19268. }
  19269. return null;
  19270. }
  19271. raycast( raycaster, intersects ) {
  19272. const levels = this.levels;
  19273. if ( levels.length > 0 ) {
  19274. _v1$2.setFromMatrixPosition( this.matrixWorld );
  19275. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  19276. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  19277. }
  19278. }
  19279. update( camera ) {
  19280. const levels = this.levels;
  19281. if ( levels.length > 1 ) {
  19282. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  19283. _v2$1.setFromMatrixPosition( this.matrixWorld );
  19284. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  19285. levels[ 0 ].object.visible = true;
  19286. let i, l;
  19287. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19288. let levelDistance = levels[ i ].distance;
  19289. if ( levels[ i ].object.visible ) {
  19290. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19291. }
  19292. if ( distance >= levelDistance ) {
  19293. levels[ i - 1 ].object.visible = false;
  19294. levels[ i ].object.visible = true;
  19295. } else {
  19296. break;
  19297. }
  19298. }
  19299. this._currentLevel = i - 1;
  19300. for ( ; i < l; i ++ ) {
  19301. levels[ i ].object.visible = false;
  19302. }
  19303. }
  19304. }
  19305. toJSON( meta ) {
  19306. const data = super.toJSON( meta );
  19307. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  19308. data.object.levels = [];
  19309. const levels = this.levels;
  19310. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19311. const level = levels[ i ];
  19312. data.object.levels.push( {
  19313. object: level.object.uuid,
  19314. distance: level.distance,
  19315. hysteresis: level.hysteresis
  19316. } );
  19317. }
  19318. return data;
  19319. }
  19320. }
  19321. const _basePosition = /*@__PURE__*/ new Vector3();
  19322. const _skinIndex = /*@__PURE__*/ new Vector4();
  19323. const _skinWeight = /*@__PURE__*/ new Vector4();
  19324. const _vector3 = /*@__PURE__*/ new Vector3();
  19325. const _matrix4 = /*@__PURE__*/ new Matrix4();
  19326. const _vertex = /*@__PURE__*/ new Vector3();
  19327. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19328. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  19329. const _ray$2 = /*@__PURE__*/ new Ray();
  19330. class SkinnedMesh extends Mesh {
  19331. constructor( geometry, material ) {
  19332. super( geometry, material );
  19333. this.isSkinnedMesh = true;
  19334. this.type = 'SkinnedMesh';
  19335. this.bindMode = AttachedBindMode;
  19336. this.bindMatrix = new Matrix4();
  19337. this.bindMatrixInverse = new Matrix4();
  19338. this.boundingBox = null;
  19339. this.boundingSphere = null;
  19340. }
  19341. computeBoundingBox() {
  19342. const geometry = this.geometry;
  19343. if ( this.boundingBox === null ) {
  19344. this.boundingBox = new Box3();
  19345. }
  19346. this.boundingBox.makeEmpty();
  19347. const positionAttribute = geometry.getAttribute( 'position' );
  19348. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19349. this.getVertexPosition( i, _vertex );
  19350. this.boundingBox.expandByPoint( _vertex );
  19351. }
  19352. }
  19353. computeBoundingSphere() {
  19354. const geometry = this.geometry;
  19355. if ( this.boundingSphere === null ) {
  19356. this.boundingSphere = new Sphere();
  19357. }
  19358. this.boundingSphere.makeEmpty();
  19359. const positionAttribute = geometry.getAttribute( 'position' );
  19360. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19361. this.getVertexPosition( i, _vertex );
  19362. this.boundingSphere.expandByPoint( _vertex );
  19363. }
  19364. }
  19365. copy( source, recursive ) {
  19366. super.copy( source, recursive );
  19367. this.bindMode = source.bindMode;
  19368. this.bindMatrix.copy( source.bindMatrix );
  19369. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  19370. this.skeleton = source.skeleton;
  19371. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19372. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19373. return this;
  19374. }
  19375. raycast( raycaster, intersects ) {
  19376. const material = this.material;
  19377. const matrixWorld = this.matrixWorld;
  19378. if ( material === undefined ) return;
  19379. // test with bounding sphere in world space
  19380. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19381. _sphere$4.copy( this.boundingSphere );
  19382. _sphere$4.applyMatrix4( matrixWorld );
  19383. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19384. // convert ray to local space of skinned mesh
  19385. _inverseMatrix$2.copy( matrixWorld ).invert();
  19386. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  19387. // test with bounding box in local space
  19388. if ( this.boundingBox !== null ) {
  19389. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  19390. }
  19391. // test for intersections with geometry
  19392. this._computeIntersections( raycaster, intersects, _ray$2 );
  19393. }
  19394. getVertexPosition( index, target ) {
  19395. super.getVertexPosition( index, target );
  19396. this.applyBoneTransform( index, target );
  19397. return target;
  19398. }
  19399. bind( skeleton, bindMatrix ) {
  19400. this.skeleton = skeleton;
  19401. if ( bindMatrix === undefined ) {
  19402. this.updateMatrixWorld( true );
  19403. this.skeleton.calculateInverses();
  19404. bindMatrix = this.matrixWorld;
  19405. }
  19406. this.bindMatrix.copy( bindMatrix );
  19407. this.bindMatrixInverse.copy( bindMatrix ).invert();
  19408. }
  19409. pose() {
  19410. this.skeleton.pose();
  19411. }
  19412. normalizeSkinWeights() {
  19413. const vector = new Vector4();
  19414. const skinWeight = this.geometry.attributes.skinWeight;
  19415. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  19416. vector.fromBufferAttribute( skinWeight, i );
  19417. const scale = 1.0 / vector.manhattanLength();
  19418. if ( scale !== Infinity ) {
  19419. vector.multiplyScalar( scale );
  19420. } else {
  19421. vector.set( 1, 0, 0, 0 ); // do something reasonable
  19422. }
  19423. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  19424. }
  19425. }
  19426. updateMatrixWorld( force ) {
  19427. super.updateMatrixWorld( force );
  19428. if ( this.bindMode === AttachedBindMode ) {
  19429. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  19430. } else if ( this.bindMode === DetachedBindMode ) {
  19431. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  19432. } else {
  19433. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  19434. }
  19435. }
  19436. applyBoneTransform( index, vector ) {
  19437. const skeleton = this.skeleton;
  19438. const geometry = this.geometry;
  19439. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  19440. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  19441. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  19442. vector.set( 0, 0, 0 );
  19443. for ( let i = 0; i < 4; i ++ ) {
  19444. const weight = _skinWeight.getComponent( i );
  19445. if ( weight !== 0 ) {
  19446. const boneIndex = _skinIndex.getComponent( i );
  19447. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  19448. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  19449. }
  19450. }
  19451. return vector.applyMatrix4( this.bindMatrixInverse );
  19452. }
  19453. }
  19454. class Bone extends Object3D {
  19455. constructor() {
  19456. super();
  19457. this.isBone = true;
  19458. this.type = 'Bone';
  19459. }
  19460. }
  19461. class DataTexture extends Texture {
  19462. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  19463. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19464. this.isDataTexture = true;
  19465. this.image = { data: data, width: width, height: height };
  19466. this.generateMipmaps = false;
  19467. this.flipY = false;
  19468. this.unpackAlignment = 1;
  19469. }
  19470. }
  19471. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  19472. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  19473. class Skeleton {
  19474. constructor( bones = [], boneInverses = [] ) {
  19475. this.uuid = generateUUID();
  19476. this.bones = bones.slice( 0 );
  19477. this.boneInverses = boneInverses;
  19478. this.boneMatrices = null;
  19479. this.boneTexture = null;
  19480. this.init();
  19481. }
  19482. init() {
  19483. const bones = this.bones;
  19484. const boneInverses = this.boneInverses;
  19485. this.boneMatrices = new Float32Array( bones.length * 16 );
  19486. // calculate inverse bone matrices if necessary
  19487. if ( boneInverses.length === 0 ) {
  19488. this.calculateInverses();
  19489. } else {
  19490. // handle special case
  19491. if ( bones.length !== boneInverses.length ) {
  19492. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19493. this.boneInverses = [];
  19494. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19495. this.boneInverses.push( new Matrix4() );
  19496. }
  19497. }
  19498. }
  19499. }
  19500. calculateInverses() {
  19501. this.boneInverses.length = 0;
  19502. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19503. const inverse = new Matrix4();
  19504. if ( this.bones[ i ] ) {
  19505. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19506. }
  19507. this.boneInverses.push( inverse );
  19508. }
  19509. }
  19510. pose() {
  19511. // recover the bind-time world matrices
  19512. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19513. const bone = this.bones[ i ];
  19514. if ( bone ) {
  19515. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19516. }
  19517. }
  19518. // compute the local matrices, positions, rotations and scales
  19519. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19520. const bone = this.bones[ i ];
  19521. if ( bone ) {
  19522. if ( bone.parent && bone.parent.isBone ) {
  19523. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19524. bone.matrix.multiply( bone.matrixWorld );
  19525. } else {
  19526. bone.matrix.copy( bone.matrixWorld );
  19527. }
  19528. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19529. }
  19530. }
  19531. }
  19532. update() {
  19533. const bones = this.bones;
  19534. const boneInverses = this.boneInverses;
  19535. const boneMatrices = this.boneMatrices;
  19536. const boneTexture = this.boneTexture;
  19537. // flatten bone matrices to array
  19538. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19539. // compute the offset between the current and the original transform
  19540. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19541. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19542. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19543. }
  19544. if ( boneTexture !== null ) {
  19545. boneTexture.needsUpdate = true;
  19546. }
  19547. }
  19548. clone() {
  19549. return new Skeleton( this.bones, this.boneInverses );
  19550. }
  19551. computeBoneTexture() {
  19552. // layout (1 matrix = 4 pixels)
  19553. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19554. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19555. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19556. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19557. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19558. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19559. size = Math.ceil( size / 4 ) * 4;
  19560. size = Math.max( size, 4 );
  19561. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19562. boneMatrices.set( this.boneMatrices ); // copy current values
  19563. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19564. boneTexture.needsUpdate = true;
  19565. this.boneMatrices = boneMatrices;
  19566. this.boneTexture = boneTexture;
  19567. return this;
  19568. }
  19569. getBoneByName( name ) {
  19570. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19571. const bone = this.bones[ i ];
  19572. if ( bone.name === name ) {
  19573. return bone;
  19574. }
  19575. }
  19576. return undefined;
  19577. }
  19578. dispose( ) {
  19579. if ( this.boneTexture !== null ) {
  19580. this.boneTexture.dispose();
  19581. this.boneTexture = null;
  19582. }
  19583. }
  19584. fromJSON( json, bones ) {
  19585. this.uuid = json.uuid;
  19586. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19587. const uuid = json.bones[ i ];
  19588. let bone = bones[ uuid ];
  19589. if ( bone === undefined ) {
  19590. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19591. bone = new Bone();
  19592. }
  19593. this.bones.push( bone );
  19594. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19595. }
  19596. this.init();
  19597. return this;
  19598. }
  19599. toJSON() {
  19600. const data = {
  19601. metadata: {
  19602. version: 4.6,
  19603. type: 'Skeleton',
  19604. generator: 'Skeleton.toJSON'
  19605. },
  19606. bones: [],
  19607. boneInverses: []
  19608. };
  19609. data.uuid = this.uuid;
  19610. const bones = this.bones;
  19611. const boneInverses = this.boneInverses;
  19612. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19613. const bone = bones[ i ];
  19614. data.bones.push( bone.uuid );
  19615. const boneInverse = boneInverses[ i ];
  19616. data.boneInverses.push( boneInverse.toArray() );
  19617. }
  19618. return data;
  19619. }
  19620. }
  19621. class InstancedBufferAttribute extends BufferAttribute {
  19622. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19623. super( array, itemSize, normalized );
  19624. this.isInstancedBufferAttribute = true;
  19625. this.meshPerAttribute = meshPerAttribute;
  19626. }
  19627. copy( source ) {
  19628. super.copy( source );
  19629. this.meshPerAttribute = source.meshPerAttribute;
  19630. return this;
  19631. }
  19632. toJSON() {
  19633. const data = super.toJSON();
  19634. data.meshPerAttribute = this.meshPerAttribute;
  19635. data.isInstancedBufferAttribute = true;
  19636. return data;
  19637. }
  19638. }
  19639. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19640. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19641. const _instanceIntersects = [];
  19642. const _box3 = /*@__PURE__*/ new Box3();
  19643. const _identity = /*@__PURE__*/ new Matrix4();
  19644. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19645. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19646. class InstancedMesh extends Mesh {
  19647. constructor( geometry, material, count ) {
  19648. super( geometry, material );
  19649. this.isInstancedMesh = true;
  19650. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19651. this.instanceColor = null;
  19652. this.morphTexture = null;
  19653. this.count = count;
  19654. this.boundingBox = null;
  19655. this.boundingSphere = null;
  19656. for ( let i = 0; i < count; i ++ ) {
  19657. this.setMatrixAt( i, _identity );
  19658. }
  19659. }
  19660. computeBoundingBox() {
  19661. const geometry = this.geometry;
  19662. const count = this.count;
  19663. if ( this.boundingBox === null ) {
  19664. this.boundingBox = new Box3();
  19665. }
  19666. if ( geometry.boundingBox === null ) {
  19667. geometry.computeBoundingBox();
  19668. }
  19669. this.boundingBox.makeEmpty();
  19670. for ( let i = 0; i < count; i ++ ) {
  19671. this.getMatrixAt( i, _instanceLocalMatrix );
  19672. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19673. this.boundingBox.union( _box3 );
  19674. }
  19675. }
  19676. computeBoundingSphere() {
  19677. const geometry = this.geometry;
  19678. const count = this.count;
  19679. if ( this.boundingSphere === null ) {
  19680. this.boundingSphere = new Sphere();
  19681. }
  19682. if ( geometry.boundingSphere === null ) {
  19683. geometry.computeBoundingSphere();
  19684. }
  19685. this.boundingSphere.makeEmpty();
  19686. for ( let i = 0; i < count; i ++ ) {
  19687. this.getMatrixAt( i, _instanceLocalMatrix );
  19688. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19689. this.boundingSphere.union( _sphere$3 );
  19690. }
  19691. }
  19692. copy( source, recursive ) {
  19693. super.copy( source, recursive );
  19694. this.instanceMatrix.copy( source.instanceMatrix );
  19695. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19696. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19697. this.count = source.count;
  19698. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19699. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19700. return this;
  19701. }
  19702. getColorAt( index, color ) {
  19703. color.fromArray( this.instanceColor.array, index * 3 );
  19704. }
  19705. getMatrixAt( index, matrix ) {
  19706. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19707. }
  19708. getMorphAt( index, object ) {
  19709. const objectInfluences = object.morphTargetInfluences;
  19710. const array = this.morphTexture.source.data.data;
  19711. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19712. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19713. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19714. objectInfluences[ i ] = array[ dataIndex + i ];
  19715. }
  19716. }
  19717. raycast( raycaster, intersects ) {
  19718. const matrixWorld = this.matrixWorld;
  19719. const raycastTimes = this.count;
  19720. _mesh$1.geometry = this.geometry;
  19721. _mesh$1.material = this.material;
  19722. if ( _mesh$1.material === undefined ) return;
  19723. // test with bounding sphere first
  19724. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19725. _sphere$3.copy( this.boundingSphere );
  19726. _sphere$3.applyMatrix4( matrixWorld );
  19727. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19728. // now test each instance
  19729. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19730. // calculate the world matrix for each instance
  19731. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19732. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19733. // the mesh represents this single instance
  19734. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19735. _mesh$1.raycast( raycaster, _instanceIntersects );
  19736. // process the result of raycast
  19737. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19738. const intersect = _instanceIntersects[ i ];
  19739. intersect.instanceId = instanceId;
  19740. intersect.object = this;
  19741. intersects.push( intersect );
  19742. }
  19743. _instanceIntersects.length = 0;
  19744. }
  19745. }
  19746. setColorAt( index, color ) {
  19747. if ( this.instanceColor === null ) {
  19748. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19749. }
  19750. color.toArray( this.instanceColor.array, index * 3 );
  19751. }
  19752. setMatrixAt( index, matrix ) {
  19753. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19754. }
  19755. setMorphAt( index, object ) {
  19756. const objectInfluences = object.morphTargetInfluences;
  19757. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19758. if ( this.morphTexture === null ) {
  19759. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19760. }
  19761. const array = this.morphTexture.source.data.data;
  19762. let morphInfluencesSum = 0;
  19763. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19764. morphInfluencesSum += objectInfluences[ i ];
  19765. }
  19766. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19767. const dataIndex = len * index;
  19768. array[ dataIndex ] = morphBaseInfluence;
  19769. array.set( objectInfluences, dataIndex + 1 );
  19770. }
  19771. updateMorphTargets() {
  19772. }
  19773. dispose() {
  19774. this.dispatchEvent( { type: 'dispose' } );
  19775. if ( this.morphTexture !== null ) {
  19776. this.morphTexture.dispose();
  19777. this.morphTexture = null;
  19778. }
  19779. return this;
  19780. }
  19781. }
  19782. function sortOpaque( a, b ) {
  19783. return a.z - b.z;
  19784. }
  19785. function sortTransparent( a, b ) {
  19786. return b.z - a.z;
  19787. }
  19788. class MultiDrawRenderList {
  19789. constructor() {
  19790. this.index = 0;
  19791. this.pool = [];
  19792. this.list = [];
  19793. }
  19794. push( drawRange, z, index ) {
  19795. const pool = this.pool;
  19796. const list = this.list;
  19797. if ( this.index >= pool.length ) {
  19798. pool.push( {
  19799. start: - 1,
  19800. count: - 1,
  19801. z: - 1,
  19802. index: - 1,
  19803. } );
  19804. }
  19805. const item = pool[ this.index ];
  19806. list.push( item );
  19807. this.index ++;
  19808. item.start = drawRange.start;
  19809. item.count = drawRange.count;
  19810. item.z = z;
  19811. item.index = index;
  19812. }
  19813. reset() {
  19814. this.list.length = 0;
  19815. this.index = 0;
  19816. }
  19817. }
  19818. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19819. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19820. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19821. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19822. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19823. const _frustum = /*@__PURE__*/ new Frustum();
  19824. const _box$1 = /*@__PURE__*/ new Box3();
  19825. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19826. const _vector$5 = /*@__PURE__*/ new Vector3();
  19827. const _forward = /*@__PURE__*/ new Vector3();
  19828. const _temp = /*@__PURE__*/ new Vector3();
  19829. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19830. const _mesh = /*@__PURE__*/ new Mesh();
  19831. const _batchIntersects = [];
  19832. // @TODO: SkinnedMesh support?
  19833. // @TODO: geometry.groups support?
  19834. // @TODO: geometry.drawRange support?
  19835. // @TODO: geometry.morphAttributes support?
  19836. // @TODO: Support uniform parameter per geometry
  19837. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19838. // copies data from attribute "src" into "target" starting at "targetOffset"
  19839. function copyAttributeData( src, target, targetOffset = 0 ) {
  19840. const itemSize = target.itemSize;
  19841. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19842. // use the component getters and setters if the array data cannot
  19843. // be copied directly
  19844. const vertexCount = src.count;
  19845. for ( let i = 0; i < vertexCount; i ++ ) {
  19846. for ( let c = 0; c < itemSize; c ++ ) {
  19847. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19848. }
  19849. }
  19850. } else {
  19851. // faster copy approach using typed array set function
  19852. target.array.set( src.array, targetOffset * itemSize );
  19853. }
  19854. target.needsUpdate = true;
  19855. }
  19856. class BatchedMesh extends Mesh {
  19857. get maxInstanceCount() {
  19858. return this._maxInstanceCount;
  19859. }
  19860. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19861. super( new BufferGeometry(), material );
  19862. this.isBatchedMesh = true;
  19863. this.perObjectFrustumCulled = true;
  19864. this.sortObjects = true;
  19865. this.boundingBox = null;
  19866. this.boundingSphere = null;
  19867. this.customSort = null;
  19868. // stores visible, active, and geometry id per object
  19869. this._drawInfo = [];
  19870. // geometry information
  19871. this._drawRanges = [];
  19872. this._reservedRanges = [];
  19873. this._bounds = [];
  19874. this._maxInstanceCount = maxInstanceCount;
  19875. this._maxVertexCount = maxVertexCount;
  19876. this._maxIndexCount = maxIndexCount;
  19877. this._geometryInitialized = false;
  19878. this._geometryCount = 0;
  19879. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19880. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19881. this._multiDrawCount = 0;
  19882. this._multiDrawInstances = null;
  19883. this._visibilityChanged = true;
  19884. // Local matrix per geometry by using data texture
  19885. this._matricesTexture = null;
  19886. this._indirectTexture = null;
  19887. this._colorsTexture = null;
  19888. this._initMatricesTexture();
  19889. this._initIndirectTexture();
  19890. }
  19891. _initMatricesTexture() {
  19892. // layout (1 matrix = 4 pixels)
  19893. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19894. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19895. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19896. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19897. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19898. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19899. size = Math.ceil( size / 4 ) * 4;
  19900. size = Math.max( size, 4 );
  19901. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19902. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19903. this._matricesTexture = matricesTexture;
  19904. }
  19905. _initIndirectTexture() {
  19906. let size = Math.sqrt( this._maxInstanceCount );
  19907. size = Math.ceil( size );
  19908. const indirectArray = new Uint32Array( size * size );
  19909. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19910. this._indirectTexture = indirectTexture;
  19911. }
  19912. _initColorsTexture() {
  19913. let size = Math.sqrt( this._maxIndexCount );
  19914. size = Math.ceil( size );
  19915. // 4 floats per RGBA pixel initialized to white
  19916. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19917. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19918. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19919. this._colorsTexture = colorsTexture;
  19920. }
  19921. _initializeGeometry( reference ) {
  19922. const geometry = this.geometry;
  19923. const maxVertexCount = this._maxVertexCount;
  19924. const maxIndexCount = this._maxIndexCount;
  19925. if ( this._geometryInitialized === false ) {
  19926. for ( const attributeName in reference.attributes ) {
  19927. const srcAttribute = reference.getAttribute( attributeName );
  19928. const { array, itemSize, normalized } = srcAttribute;
  19929. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19930. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19931. geometry.setAttribute( attributeName, dstAttribute );
  19932. }
  19933. if ( reference.getIndex() !== null ) {
  19934. // Reserve last u16 index for primitive restart.
  19935. const indexArray = maxVertexCount > 65535
  19936. ? new Uint32Array( maxIndexCount )
  19937. : new Uint16Array( maxIndexCount );
  19938. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19939. }
  19940. this._geometryInitialized = true;
  19941. }
  19942. }
  19943. // Make sure the geometry is compatible with the existing combined geometry attributes
  19944. _validateGeometry( geometry ) {
  19945. // check to ensure the geometries are using consistent attributes and indices
  19946. const batchGeometry = this.geometry;
  19947. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19948. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  19949. }
  19950. for ( const attributeName in batchGeometry.attributes ) {
  19951. if ( ! geometry.hasAttribute( attributeName ) ) {
  19952. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19953. }
  19954. const srcAttribute = geometry.getAttribute( attributeName );
  19955. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19956. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19957. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19958. }
  19959. }
  19960. }
  19961. setCustomSort( func ) {
  19962. this.customSort = func;
  19963. return this;
  19964. }
  19965. computeBoundingBox() {
  19966. if ( this.boundingBox === null ) {
  19967. this.boundingBox = new Box3();
  19968. }
  19969. const geometryCount = this._geometryCount;
  19970. const boundingBox = this.boundingBox;
  19971. const drawInfo = this._drawInfo;
  19972. boundingBox.makeEmpty();
  19973. for ( let i = 0; i < geometryCount; i ++ ) {
  19974. if ( drawInfo[ i ].active === false ) continue;
  19975. const geometryId = drawInfo[ i ].geometryIndex;
  19976. this.getMatrixAt( i, _matrix$1 );
  19977. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19978. boundingBox.union( _box$1 );
  19979. }
  19980. }
  19981. computeBoundingSphere() {
  19982. if ( this.boundingSphere === null ) {
  19983. this.boundingSphere = new Sphere();
  19984. }
  19985. const boundingSphere = this.boundingSphere;
  19986. const drawInfo = this._drawInfo;
  19987. boundingSphere.makeEmpty();
  19988. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  19989. if ( drawInfo[ i ].active === false ) continue;
  19990. const geometryId = drawInfo[ i ].geometryIndex;
  19991. this.getMatrixAt( i, _matrix$1 );
  19992. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19993. boundingSphere.union( _sphere$2 );
  19994. }
  19995. }
  19996. addInstance( geometryId ) {
  19997. // ensure we're not over geometry
  19998. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  19999. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  20000. }
  20001. this._drawInfo.push( {
  20002. visible: true,
  20003. active: true,
  20004. geometryIndex: geometryId,
  20005. } );
  20006. // initialize the matrix
  20007. const drawId = this._drawInfo.length - 1;
  20008. const matricesTexture = this._matricesTexture;
  20009. const matricesArray = matricesTexture.image.data;
  20010. _identityMatrix.toArray( matricesArray, drawId * 16 );
  20011. matricesTexture.needsUpdate = true;
  20012. const colorsTexture = this._colorsTexture;
  20013. if ( colorsTexture ) {
  20014. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20015. colorsTexture.needsUpdate = true;
  20016. }
  20017. return drawId;
  20018. }
  20019. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  20020. this._initializeGeometry( geometry );
  20021. this._validateGeometry( geometry );
  20022. // ensure we're not over geometry
  20023. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  20024. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  20025. }
  20026. // get the necessary range fo the geometry
  20027. const reservedRange = {
  20028. vertexStart: - 1,
  20029. vertexCount: - 1,
  20030. indexStart: - 1,
  20031. indexCount: - 1,
  20032. };
  20033. let lastRange = null;
  20034. const reservedRanges = this._reservedRanges;
  20035. const drawRanges = this._drawRanges;
  20036. const bounds = this._bounds;
  20037. if ( this._geometryCount !== 0 ) {
  20038. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  20039. }
  20040. if ( vertexCount === - 1 ) {
  20041. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  20042. } else {
  20043. reservedRange.vertexCount = vertexCount;
  20044. }
  20045. if ( lastRange === null ) {
  20046. reservedRange.vertexStart = 0;
  20047. } else {
  20048. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  20049. }
  20050. const index = geometry.getIndex();
  20051. const hasIndex = index !== null;
  20052. if ( hasIndex ) {
  20053. if ( indexCount === - 1 ) {
  20054. reservedRange.indexCount = index.count;
  20055. } else {
  20056. reservedRange.indexCount = indexCount;
  20057. }
  20058. if ( lastRange === null ) {
  20059. reservedRange.indexStart = 0;
  20060. } else {
  20061. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  20062. }
  20063. }
  20064. if (
  20065. reservedRange.indexStart !== - 1 &&
  20066. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  20067. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  20068. ) {
  20069. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20070. }
  20071. // update id
  20072. const geometryId = this._geometryCount;
  20073. this._geometryCount ++;
  20074. // add the reserved range and draw range objects
  20075. reservedRanges.push( reservedRange );
  20076. drawRanges.push( {
  20077. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  20078. count: - 1
  20079. } );
  20080. bounds.push( {
  20081. boxInitialized: false,
  20082. box: new Box3(),
  20083. sphereInitialized: false,
  20084. sphere: new Sphere()
  20085. } );
  20086. // update the geometry
  20087. this.setGeometryAt( geometryId, geometry );
  20088. return geometryId;
  20089. }
  20090. setGeometryAt( geometryId, geometry ) {
  20091. if ( geometryId >= this._geometryCount ) {
  20092. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  20093. }
  20094. this._validateGeometry( geometry );
  20095. const batchGeometry = this.geometry;
  20096. const hasIndex = batchGeometry.getIndex() !== null;
  20097. const dstIndex = batchGeometry.getIndex();
  20098. const srcIndex = geometry.getIndex();
  20099. const reservedRange = this._reservedRanges[ geometryId ];
  20100. if (
  20101. hasIndex &&
  20102. srcIndex.count > reservedRange.indexCount ||
  20103. geometry.attributes.position.count > reservedRange.vertexCount
  20104. ) {
  20105. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  20106. }
  20107. // copy geometry over
  20108. const vertexStart = reservedRange.vertexStart;
  20109. const vertexCount = reservedRange.vertexCount;
  20110. for ( const attributeName in batchGeometry.attributes ) {
  20111. // copy attribute data
  20112. const srcAttribute = geometry.getAttribute( attributeName );
  20113. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20114. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20115. // fill the rest in with zeroes
  20116. const itemSize = srcAttribute.itemSize;
  20117. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  20118. const index = vertexStart + i;
  20119. for ( let c = 0; c < itemSize; c ++ ) {
  20120. dstAttribute.setComponent( index, c, 0 );
  20121. }
  20122. }
  20123. dstAttribute.needsUpdate = true;
  20124. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  20125. }
  20126. // copy index
  20127. if ( hasIndex ) {
  20128. const indexStart = reservedRange.indexStart;
  20129. // copy index data over
  20130. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20131. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20132. }
  20133. // fill the rest in with zeroes
  20134. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  20135. dstIndex.setX( indexStart + i, vertexStart );
  20136. }
  20137. dstIndex.needsUpdate = true;
  20138. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  20139. }
  20140. // store the bounding boxes
  20141. const bound = this._bounds[ geometryId ];
  20142. if ( geometry.boundingBox !== null ) {
  20143. bound.box.copy( geometry.boundingBox );
  20144. bound.boxInitialized = true;
  20145. } else {
  20146. bound.boxInitialized = false;
  20147. }
  20148. if ( geometry.boundingSphere !== null ) {
  20149. bound.sphere.copy( geometry.boundingSphere );
  20150. bound.sphereInitialized = true;
  20151. } else {
  20152. bound.sphereInitialized = false;
  20153. }
  20154. // set drawRange count
  20155. const drawRange = this._drawRanges[ geometryId ];
  20156. const posAttr = geometry.getAttribute( 'position' );
  20157. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  20158. this._visibilityChanged = true;
  20159. return geometryId;
  20160. }
  20161. /*
  20162. deleteGeometry( geometryId ) {
  20163. // TODO: delete geometry and associated instances
  20164. }
  20165. */
  20166. /*
  20167. deleteInstance( instanceId ) {
  20168. // Note: User needs to call optimize() afterward to pack the data.
  20169. const drawInfo = this._drawInfo;
  20170. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20171. return this;
  20172. }
  20173. drawInfo[ instanceId ].active = false;
  20174. this._visibilityChanged = true;
  20175. return this;
  20176. }
  20177. */
  20178. // get bounding box and compute it if it doesn't exist
  20179. getBoundingBoxAt( geometryId, target ) {
  20180. if ( geometryId >= this._geometryCount ) {
  20181. return null;
  20182. }
  20183. // compute bounding box
  20184. const bound = this._bounds[ geometryId ];
  20185. const box = bound.box;
  20186. const geometry = this.geometry;
  20187. if ( bound.boxInitialized === false ) {
  20188. box.makeEmpty();
  20189. const index = geometry.index;
  20190. const position = geometry.attributes.position;
  20191. const drawRange = this._drawRanges[ geometryId ];
  20192. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20193. let iv = i;
  20194. if ( index ) {
  20195. iv = index.getX( iv );
  20196. }
  20197. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20198. }
  20199. bound.boxInitialized = true;
  20200. }
  20201. target.copy( box );
  20202. return target;
  20203. }
  20204. // get bounding sphere and compute it if it doesn't exist
  20205. getBoundingSphereAt( geometryId, target ) {
  20206. if ( geometryId >= this._geometryCount ) {
  20207. return null;
  20208. }
  20209. // compute bounding sphere
  20210. const bound = this._bounds[ geometryId ];
  20211. const sphere = bound.sphere;
  20212. const geometry = this.geometry;
  20213. if ( bound.sphereInitialized === false ) {
  20214. sphere.makeEmpty();
  20215. this.getBoundingBoxAt( geometryId, _box$1 );
  20216. _box$1.getCenter( sphere.center );
  20217. const index = geometry.index;
  20218. const position = geometry.attributes.position;
  20219. const drawRange = this._drawRanges[ geometryId ];
  20220. let maxRadiusSq = 0;
  20221. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20222. let iv = i;
  20223. if ( index ) {
  20224. iv = index.getX( iv );
  20225. }
  20226. _vector$5.fromBufferAttribute( position, iv );
  20227. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20228. }
  20229. sphere.radius = Math.sqrt( maxRadiusSq );
  20230. bound.sphereInitialized = true;
  20231. }
  20232. target.copy( sphere );
  20233. return target;
  20234. }
  20235. setMatrixAt( instanceId, matrix ) {
  20236. // @TODO: Map geometryId to index of the arrays because
  20237. // optimize() can make geometryId mismatch the index
  20238. const drawInfo = this._drawInfo;
  20239. const matricesTexture = this._matricesTexture;
  20240. const matricesArray = this._matricesTexture.image.data;
  20241. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20242. return this;
  20243. }
  20244. matrix.toArray( matricesArray, instanceId * 16 );
  20245. matricesTexture.needsUpdate = true;
  20246. return this;
  20247. }
  20248. getMatrixAt( instanceId, matrix ) {
  20249. const drawInfo = this._drawInfo;
  20250. const matricesArray = this._matricesTexture.image.data;
  20251. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20252. return null;
  20253. }
  20254. return matrix.fromArray( matricesArray, instanceId * 16 );
  20255. }
  20256. setColorAt( instanceId, color ) {
  20257. if ( this._colorsTexture === null ) {
  20258. this._initColorsTexture();
  20259. }
  20260. // @TODO: Map id to index of the arrays because
  20261. // optimize() can make id mismatch the index
  20262. const colorsTexture = this._colorsTexture;
  20263. const colorsArray = this._colorsTexture.image.data;
  20264. const drawInfo = this._drawInfo;
  20265. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20266. return this;
  20267. }
  20268. color.toArray( colorsArray, instanceId * 4 );
  20269. colorsTexture.needsUpdate = true;
  20270. return this;
  20271. }
  20272. getColorAt( instanceId, color ) {
  20273. const colorsArray = this._colorsTexture.image.data;
  20274. const drawInfo = this._drawInfo;
  20275. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20276. return null;
  20277. }
  20278. return color.fromArray( colorsArray, instanceId * 4 );
  20279. }
  20280. setVisibleAt( instanceId, value ) {
  20281. // if the geometry is out of range, not active, or visibility state
  20282. // does not change then return early
  20283. const drawInfo = this._drawInfo;
  20284. if (
  20285. instanceId >= drawInfo.length ||
  20286. drawInfo[ instanceId ].active === false ||
  20287. drawInfo[ instanceId ].visible === value
  20288. ) {
  20289. return this;
  20290. }
  20291. drawInfo[ instanceId ].visible = value;
  20292. this._visibilityChanged = true;
  20293. return this;
  20294. }
  20295. getVisibleAt( instanceId ) {
  20296. // return early if the geometry is out of range or not active
  20297. const drawInfo = this._drawInfo;
  20298. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20299. return false;
  20300. }
  20301. return drawInfo[ instanceId ].visible;
  20302. }
  20303. raycast( raycaster, intersects ) {
  20304. const drawInfo = this._drawInfo;
  20305. const drawRanges = this._drawRanges;
  20306. const matrixWorld = this.matrixWorld;
  20307. const batchGeometry = this.geometry;
  20308. // iterate over each geometry
  20309. _mesh.material = this.material;
  20310. _mesh.geometry.index = batchGeometry.index;
  20311. _mesh.geometry.attributes = batchGeometry.attributes;
  20312. if ( _mesh.geometry.boundingBox === null ) {
  20313. _mesh.geometry.boundingBox = new Box3();
  20314. }
  20315. if ( _mesh.geometry.boundingSphere === null ) {
  20316. _mesh.geometry.boundingSphere = new Sphere();
  20317. }
  20318. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20319. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  20320. continue;
  20321. }
  20322. const geometryId = drawInfo[ i ].geometryIndex;
  20323. const drawRange = drawRanges[ geometryId ];
  20324. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  20325. // ge the intersects
  20326. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20327. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20328. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20329. _mesh.raycast( raycaster, _batchIntersects );
  20330. // add batch id to the intersects
  20331. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20332. const intersect = _batchIntersects[ j ];
  20333. intersect.object = this;
  20334. intersect.batchId = i;
  20335. intersects.push( intersect );
  20336. }
  20337. _batchIntersects.length = 0;
  20338. }
  20339. _mesh.material = null;
  20340. _mesh.geometry.index = null;
  20341. _mesh.geometry.attributes = {};
  20342. _mesh.geometry.setDrawRange( 0, Infinity );
  20343. }
  20344. copy( source ) {
  20345. super.copy( source );
  20346. this.geometry = source.geometry.clone();
  20347. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20348. this.sortObjects = source.sortObjects;
  20349. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20350. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20351. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  20352. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  20353. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  20354. this._bounds = source._bounds.map( bound => ( {
  20355. boxInitialized: bound.boxInitialized,
  20356. box: bound.box.clone(),
  20357. sphereInitialized: bound.sphereInitialized,
  20358. sphere: bound.sphere.clone()
  20359. } ) );
  20360. this._maxInstanceCount = source._maxInstanceCount;
  20361. this._maxVertexCount = source._maxVertexCount;
  20362. this._maxIndexCount = source._maxIndexCount;
  20363. this._geometryInitialized = source._geometryInitialized;
  20364. this._geometryCount = source._geometryCount;
  20365. this._multiDrawCounts = source._multiDrawCounts.slice();
  20366. this._multiDrawStarts = source._multiDrawStarts.slice();
  20367. this._matricesTexture = source._matricesTexture.clone();
  20368. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20369. if ( this._colorsTexture !== null ) {
  20370. this._colorsTexture = source._colorsTexture.clone();
  20371. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20372. }
  20373. return this;
  20374. }
  20375. dispose() {
  20376. // Assuming the geometry is not shared with other meshes
  20377. this.geometry.dispose();
  20378. this._matricesTexture.dispose();
  20379. this._matricesTexture = null;
  20380. this._indirectTexture.dispose();
  20381. this._indirectTexture = null;
  20382. if ( this._colorsTexture !== null ) {
  20383. this._colorsTexture.dispose();
  20384. this._colorsTexture = null;
  20385. }
  20386. return this;
  20387. }
  20388. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20389. // if visibility has not changed and frustum culling and object sorting is not required
  20390. // then skip iterating over all items
  20391. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20392. return;
  20393. }
  20394. // the indexed version of the multi draw function requires specifying the start
  20395. // offset in bytes.
  20396. const index = geometry.getIndex();
  20397. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20398. const drawInfo = this._drawInfo;
  20399. const multiDrawStarts = this._multiDrawStarts;
  20400. const multiDrawCounts = this._multiDrawCounts;
  20401. const drawRanges = this._drawRanges;
  20402. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20403. const indirectTexture = this._indirectTexture;
  20404. const indirectArray = indirectTexture.image.data;
  20405. // prepare the frustum in the local frame
  20406. if ( perObjectFrustumCulled ) {
  20407. _projScreenMatrix$2
  20408. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20409. .multiply( this.matrixWorld );
  20410. _frustum.setFromProjectionMatrix(
  20411. _projScreenMatrix$2,
  20412. renderer.coordinateSystem
  20413. );
  20414. }
  20415. let count = 0;
  20416. if ( this.sortObjects ) {
  20417. // get the camera position in the local frame
  20418. _invMatrixWorld.copy( this.matrixWorld ).invert();
  20419. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  20420. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  20421. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20422. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  20423. const geometryId = drawInfo[ i ].geometryIndex;
  20424. // get the bounds in world space
  20425. this.getMatrixAt( i, _matrix$1 );
  20426. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20427. // determine whether the batched geometry is within the frustum
  20428. let culled = false;
  20429. if ( perObjectFrustumCulled ) {
  20430. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20431. }
  20432. if ( ! culled ) {
  20433. // get the distance from camera used for sorting
  20434. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  20435. _renderList.push( drawRanges[ geometryId ], z, i );
  20436. }
  20437. }
  20438. }
  20439. // Sort the draw ranges and prep for rendering
  20440. const list = _renderList.list;
  20441. const customSort = this.customSort;
  20442. if ( customSort === null ) {
  20443. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20444. } else {
  20445. customSort.call( this, list, camera );
  20446. }
  20447. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20448. const item = list[ i ];
  20449. multiDrawStarts[ count ] = item.start * bytesPerElement;
  20450. multiDrawCounts[ count ] = item.count;
  20451. indirectArray[ count ] = item.index;
  20452. count ++;
  20453. }
  20454. _renderList.reset();
  20455. } else {
  20456. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20457. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  20458. const geometryId = drawInfo[ i ].geometryIndex;
  20459. // determine whether the batched geometry is within the frustum
  20460. let culled = false;
  20461. if ( perObjectFrustumCulled ) {
  20462. // get the bounds in world space
  20463. this.getMatrixAt( i, _matrix$1 );
  20464. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20465. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20466. }
  20467. if ( ! culled ) {
  20468. const range = drawRanges[ geometryId ];
  20469. multiDrawStarts[ count ] = range.start * bytesPerElement;
  20470. multiDrawCounts[ count ] = range.count;
  20471. indirectArray[ count ] = i;
  20472. count ++;
  20473. }
  20474. }
  20475. }
  20476. }
  20477. indirectTexture.needsUpdate = true;
  20478. this._multiDrawCount = count;
  20479. this._visibilityChanged = false;
  20480. }
  20481. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20482. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20483. }
  20484. }
  20485. class LineBasicMaterial extends Material {
  20486. constructor( parameters ) {
  20487. super();
  20488. this.isLineBasicMaterial = true;
  20489. this.type = 'LineBasicMaterial';
  20490. this.color = new Color( 0xffffff );
  20491. this.map = null;
  20492. this.linewidth = 1;
  20493. this.linecap = 'round';
  20494. this.linejoin = 'round';
  20495. this.fog = true;
  20496. this.setValues( parameters );
  20497. }
  20498. copy( source ) {
  20499. super.copy( source );
  20500. this.color.copy( source.color );
  20501. this.map = source.map;
  20502. this.linewidth = source.linewidth;
  20503. this.linecap = source.linecap;
  20504. this.linejoin = source.linejoin;
  20505. this.fog = source.fog;
  20506. return this;
  20507. }
  20508. }
  20509. const _vStart = /*@__PURE__*/ new Vector3();
  20510. const _vEnd = /*@__PURE__*/ new Vector3();
  20511. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20512. const _ray$1 = /*@__PURE__*/ new Ray();
  20513. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20514. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20515. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20516. class Line extends Object3D {
  20517. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20518. super();
  20519. this.isLine = true;
  20520. this.type = 'Line';
  20521. this.geometry = geometry;
  20522. this.material = material;
  20523. this.updateMorphTargets();
  20524. }
  20525. copy( source, recursive ) {
  20526. super.copy( source, recursive );
  20527. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20528. this.geometry = source.geometry;
  20529. return this;
  20530. }
  20531. computeLineDistances() {
  20532. const geometry = this.geometry;
  20533. // we assume non-indexed geometry
  20534. if ( geometry.index === null ) {
  20535. const positionAttribute = geometry.attributes.position;
  20536. const lineDistances = [ 0 ];
  20537. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20538. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20539. _vEnd.fromBufferAttribute( positionAttribute, i );
  20540. lineDistances[ i ] = lineDistances[ i - 1 ];
  20541. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20542. }
  20543. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20544. } else {
  20545. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20546. }
  20547. return this;
  20548. }
  20549. raycast( raycaster, intersects ) {
  20550. const geometry = this.geometry;
  20551. const matrixWorld = this.matrixWorld;
  20552. const threshold = raycaster.params.Line.threshold;
  20553. const drawRange = geometry.drawRange;
  20554. // Checking boundingSphere distance to ray
  20555. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20556. _sphere$1.copy( geometry.boundingSphere );
  20557. _sphere$1.applyMatrix4( matrixWorld );
  20558. _sphere$1.radius += threshold;
  20559. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20560. //
  20561. _inverseMatrix$1.copy( matrixWorld ).invert();
  20562. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20563. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20564. const localThresholdSq = localThreshold * localThreshold;
  20565. const step = this.isLineSegments ? 2 : 1;
  20566. const index = geometry.index;
  20567. const attributes = geometry.attributes;
  20568. const positionAttribute = attributes.position;
  20569. if ( index !== null ) {
  20570. const start = Math.max( 0, drawRange.start );
  20571. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20572. for ( let i = start, l = end - 1; i < l; i += step ) {
  20573. const a = index.getX( i );
  20574. const b = index.getX( i + 1 );
  20575. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  20576. if ( intersect ) {
  20577. intersects.push( intersect );
  20578. }
  20579. }
  20580. if ( this.isLineLoop ) {
  20581. const a = index.getX( end - 1 );
  20582. const b = index.getX( start );
  20583. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  20584. if ( intersect ) {
  20585. intersects.push( intersect );
  20586. }
  20587. }
  20588. } else {
  20589. const start = Math.max( 0, drawRange.start );
  20590. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20591. for ( let i = start, l = end - 1; i < l; i += step ) {
  20592. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  20593. if ( intersect ) {
  20594. intersects.push( intersect );
  20595. }
  20596. }
  20597. if ( this.isLineLoop ) {
  20598. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  20599. if ( intersect ) {
  20600. intersects.push( intersect );
  20601. }
  20602. }
  20603. }
  20604. }
  20605. updateMorphTargets() {
  20606. const geometry = this.geometry;
  20607. const morphAttributes = geometry.morphAttributes;
  20608. const keys = Object.keys( morphAttributes );
  20609. if ( keys.length > 0 ) {
  20610. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20611. if ( morphAttribute !== undefined ) {
  20612. this.morphTargetInfluences = [];
  20613. this.morphTargetDictionary = {};
  20614. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20615. const name = morphAttribute[ m ].name || String( m );
  20616. this.morphTargetInfluences.push( 0 );
  20617. this.morphTargetDictionary[ name ] = m;
  20618. }
  20619. }
  20620. }
  20621. }
  20622. }
  20623. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  20624. const positionAttribute = object.geometry.attributes.position;
  20625. _vStart.fromBufferAttribute( positionAttribute, a );
  20626. _vEnd.fromBufferAttribute( positionAttribute, b );
  20627. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20628. if ( distSq > thresholdSq ) return;
  20629. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20630. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20631. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20632. return {
  20633. distance: distance,
  20634. // What do we want? intersection point on the ray or on the segment??
  20635. // point: raycaster.ray.at( distance ),
  20636. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20637. index: a,
  20638. face: null,
  20639. faceIndex: null,
  20640. object: object
  20641. };
  20642. }
  20643. const _start = /*@__PURE__*/ new Vector3();
  20644. const _end = /*@__PURE__*/ new Vector3();
  20645. class LineSegments extends Line {
  20646. constructor( geometry, material ) {
  20647. super( geometry, material );
  20648. this.isLineSegments = true;
  20649. this.type = 'LineSegments';
  20650. }
  20651. computeLineDistances() {
  20652. const geometry = this.geometry;
  20653. // we assume non-indexed geometry
  20654. if ( geometry.index === null ) {
  20655. const positionAttribute = geometry.attributes.position;
  20656. const lineDistances = [];
  20657. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20658. _start.fromBufferAttribute( positionAttribute, i );
  20659. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20660. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20661. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20662. }
  20663. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20664. } else {
  20665. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20666. }
  20667. return this;
  20668. }
  20669. }
  20670. class LineLoop extends Line {
  20671. constructor( geometry, material ) {
  20672. super( geometry, material );
  20673. this.isLineLoop = true;
  20674. this.type = 'LineLoop';
  20675. }
  20676. }
  20677. class PointsMaterial extends Material {
  20678. constructor( parameters ) {
  20679. super();
  20680. this.isPointsMaterial = true;
  20681. this.type = 'PointsMaterial';
  20682. this.color = new Color( 0xffffff );
  20683. this.map = null;
  20684. this.alphaMap = null;
  20685. this.size = 1;
  20686. this.sizeAttenuation = true;
  20687. this.fog = true;
  20688. this.setValues( parameters );
  20689. }
  20690. copy( source ) {
  20691. super.copy( source );
  20692. this.color.copy( source.color );
  20693. this.map = source.map;
  20694. this.alphaMap = source.alphaMap;
  20695. this.size = source.size;
  20696. this.sizeAttenuation = source.sizeAttenuation;
  20697. this.fog = source.fog;
  20698. return this;
  20699. }
  20700. }
  20701. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20702. const _ray = /*@__PURE__*/ new Ray();
  20703. const _sphere = /*@__PURE__*/ new Sphere();
  20704. const _position$2 = /*@__PURE__*/ new Vector3();
  20705. class Points extends Object3D {
  20706. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20707. super();
  20708. this.isPoints = true;
  20709. this.type = 'Points';
  20710. this.geometry = geometry;
  20711. this.material = material;
  20712. this.updateMorphTargets();
  20713. }
  20714. copy( source, recursive ) {
  20715. super.copy( source, recursive );
  20716. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20717. this.geometry = source.geometry;
  20718. return this;
  20719. }
  20720. raycast( raycaster, intersects ) {
  20721. const geometry = this.geometry;
  20722. const matrixWorld = this.matrixWorld;
  20723. const threshold = raycaster.params.Points.threshold;
  20724. const drawRange = geometry.drawRange;
  20725. // Checking boundingSphere distance to ray
  20726. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20727. _sphere.copy( geometry.boundingSphere );
  20728. _sphere.applyMatrix4( matrixWorld );
  20729. _sphere.radius += threshold;
  20730. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20731. //
  20732. _inverseMatrix.copy( matrixWorld ).invert();
  20733. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20734. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20735. const localThresholdSq = localThreshold * localThreshold;
  20736. const index = geometry.index;
  20737. const attributes = geometry.attributes;
  20738. const positionAttribute = attributes.position;
  20739. if ( index !== null ) {
  20740. const start = Math.max( 0, drawRange.start );
  20741. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20742. for ( let i = start, il = end; i < il; i ++ ) {
  20743. const a = index.getX( i );
  20744. _position$2.fromBufferAttribute( positionAttribute, a );
  20745. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20746. }
  20747. } else {
  20748. const start = Math.max( 0, drawRange.start );
  20749. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20750. for ( let i = start, l = end; i < l; i ++ ) {
  20751. _position$2.fromBufferAttribute( positionAttribute, i );
  20752. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20753. }
  20754. }
  20755. }
  20756. updateMorphTargets() {
  20757. const geometry = this.geometry;
  20758. const morphAttributes = geometry.morphAttributes;
  20759. const keys = Object.keys( morphAttributes );
  20760. if ( keys.length > 0 ) {
  20761. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20762. if ( morphAttribute !== undefined ) {
  20763. this.morphTargetInfluences = [];
  20764. this.morphTargetDictionary = {};
  20765. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20766. const name = morphAttribute[ m ].name || String( m );
  20767. this.morphTargetInfluences.push( 0 );
  20768. this.morphTargetDictionary[ name ] = m;
  20769. }
  20770. }
  20771. }
  20772. }
  20773. }
  20774. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20775. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20776. if ( rayPointDistanceSq < localThresholdSq ) {
  20777. const intersectPoint = new Vector3();
  20778. _ray.closestPointToPoint( point, intersectPoint );
  20779. intersectPoint.applyMatrix4( matrixWorld );
  20780. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20781. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20782. intersects.push( {
  20783. distance: distance,
  20784. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20785. point: intersectPoint,
  20786. index: index,
  20787. face: null,
  20788. object: object
  20789. } );
  20790. }
  20791. }
  20792. class VideoTexture extends Texture {
  20793. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20794. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20795. this.isVideoTexture = true;
  20796. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20797. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20798. this.generateMipmaps = false;
  20799. const scope = this;
  20800. function updateVideo() {
  20801. scope.needsUpdate = true;
  20802. video.requestVideoFrameCallback( updateVideo );
  20803. }
  20804. if ( 'requestVideoFrameCallback' in video ) {
  20805. video.requestVideoFrameCallback( updateVideo );
  20806. }
  20807. }
  20808. clone() {
  20809. return new this.constructor( this.image ).copy( this );
  20810. }
  20811. update() {
  20812. const video = this.image;
  20813. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20814. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20815. this.needsUpdate = true;
  20816. }
  20817. }
  20818. }
  20819. class FramebufferTexture extends Texture {
  20820. constructor( width, height ) {
  20821. super( { width, height } );
  20822. this.isFramebufferTexture = true;
  20823. this.magFilter = NearestFilter;
  20824. this.minFilter = NearestFilter;
  20825. this.generateMipmaps = false;
  20826. this.needsUpdate = true;
  20827. }
  20828. }
  20829. class CompressedTexture extends Texture {
  20830. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20831. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20832. this.isCompressedTexture = true;
  20833. this.image = { width: width, height: height };
  20834. this.mipmaps = mipmaps;
  20835. // no flipping for cube textures
  20836. // (also flipping doesn't work for compressed textures )
  20837. this.flipY = false;
  20838. // can't generate mipmaps for compressed textures
  20839. // mips must be embedded in DDS files
  20840. this.generateMipmaps = false;
  20841. }
  20842. }
  20843. class CompressedArrayTexture extends CompressedTexture {
  20844. constructor( mipmaps, width, height, depth, format, type ) {
  20845. super( mipmaps, width, height, format, type );
  20846. this.isCompressedArrayTexture = true;
  20847. this.image.depth = depth;
  20848. this.wrapR = ClampToEdgeWrapping;
  20849. this.layerUpdates = new Set();
  20850. }
  20851. addLayerUpdate( layerIndex ) {
  20852. this.layerUpdates.add( layerIndex );
  20853. }
  20854. clearLayerUpdates() {
  20855. this.layerUpdates.clear();
  20856. }
  20857. }
  20858. class CompressedCubeTexture extends CompressedTexture {
  20859. constructor( images, format, type ) {
  20860. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20861. this.isCompressedCubeTexture = true;
  20862. this.isCubeTexture = true;
  20863. this.image = images;
  20864. }
  20865. }
  20866. class CanvasTexture extends Texture {
  20867. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20868. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20869. this.isCanvasTexture = true;
  20870. this.needsUpdate = true;
  20871. }
  20872. }
  20873. /**
  20874. * Extensible curve object.
  20875. *
  20876. * Some common of curve methods:
  20877. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20878. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20879. * .getPoints(), .getSpacedPoints()
  20880. * .getLength()
  20881. * .updateArcLengths()
  20882. *
  20883. * This following curves inherit from THREE.Curve:
  20884. *
  20885. * -- 2D curves --
  20886. * THREE.ArcCurve
  20887. * THREE.CubicBezierCurve
  20888. * THREE.EllipseCurve
  20889. * THREE.LineCurve
  20890. * THREE.QuadraticBezierCurve
  20891. * THREE.SplineCurve
  20892. *
  20893. * -- 3D curves --
  20894. * THREE.CatmullRomCurve3
  20895. * THREE.CubicBezierCurve3
  20896. * THREE.LineCurve3
  20897. * THREE.QuadraticBezierCurve3
  20898. *
  20899. * A series of curves can be represented as a THREE.CurvePath.
  20900. *
  20901. **/
  20902. class Curve {
  20903. constructor() {
  20904. this.type = 'Curve';
  20905. this.arcLengthDivisions = 200;
  20906. }
  20907. // Virtual base class method to overwrite and implement in subclasses
  20908. // - t [0 .. 1]
  20909. getPoint( /* t, optionalTarget */ ) {
  20910. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20911. return null;
  20912. }
  20913. // Get point at relative position in curve according to arc length
  20914. // - u [0 .. 1]
  20915. getPointAt( u, optionalTarget ) {
  20916. const t = this.getUtoTmapping( u );
  20917. return this.getPoint( t, optionalTarget );
  20918. }
  20919. // Get sequence of points using getPoint( t )
  20920. getPoints( divisions = 5 ) {
  20921. const points = [];
  20922. for ( let d = 0; d <= divisions; d ++ ) {
  20923. points.push( this.getPoint( d / divisions ) );
  20924. }
  20925. return points;
  20926. }
  20927. // Get sequence of points using getPointAt( u )
  20928. getSpacedPoints( divisions = 5 ) {
  20929. const points = [];
  20930. for ( let d = 0; d <= divisions; d ++ ) {
  20931. points.push( this.getPointAt( d / divisions ) );
  20932. }
  20933. return points;
  20934. }
  20935. // Get total curve arc length
  20936. getLength() {
  20937. const lengths = this.getLengths();
  20938. return lengths[ lengths.length - 1 ];
  20939. }
  20940. // Get list of cumulative segment lengths
  20941. getLengths( divisions = this.arcLengthDivisions ) {
  20942. if ( this.cacheArcLengths &&
  20943. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20944. ! this.needsUpdate ) {
  20945. return this.cacheArcLengths;
  20946. }
  20947. this.needsUpdate = false;
  20948. const cache = [];
  20949. let current, last = this.getPoint( 0 );
  20950. let sum = 0;
  20951. cache.push( 0 );
  20952. for ( let p = 1; p <= divisions; p ++ ) {
  20953. current = this.getPoint( p / divisions );
  20954. sum += current.distanceTo( last );
  20955. cache.push( sum );
  20956. last = current;
  20957. }
  20958. this.cacheArcLengths = cache;
  20959. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20960. }
  20961. updateArcLengths() {
  20962. this.needsUpdate = true;
  20963. this.getLengths();
  20964. }
  20965. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20966. getUtoTmapping( u, distance ) {
  20967. const arcLengths = this.getLengths();
  20968. let i = 0;
  20969. const il = arcLengths.length;
  20970. let targetArcLength; // The targeted u distance value to get
  20971. if ( distance ) {
  20972. targetArcLength = distance;
  20973. } else {
  20974. targetArcLength = u * arcLengths[ il - 1 ];
  20975. }
  20976. // binary search for the index with largest value smaller than target u distance
  20977. let low = 0, high = il - 1, comparison;
  20978. while ( low <= high ) {
  20979. 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
  20980. comparison = arcLengths[ i ] - targetArcLength;
  20981. if ( comparison < 0 ) {
  20982. low = i + 1;
  20983. } else if ( comparison > 0 ) {
  20984. high = i - 1;
  20985. } else {
  20986. high = i;
  20987. break;
  20988. // DONE
  20989. }
  20990. }
  20991. i = high;
  20992. if ( arcLengths[ i ] === targetArcLength ) {
  20993. return i / ( il - 1 );
  20994. }
  20995. // we could get finer grain at lengths, or use simple interpolation between two points
  20996. const lengthBefore = arcLengths[ i ];
  20997. const lengthAfter = arcLengths[ i + 1 ];
  20998. const segmentLength = lengthAfter - lengthBefore;
  20999. // determine where we are between the 'before' and 'after' points
  21000. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21001. // add that fractional amount to t
  21002. const t = ( i + segmentFraction ) / ( il - 1 );
  21003. return t;
  21004. }
  21005. // Returns a unit vector tangent at t
  21006. // In case any sub curve does not implement its tangent derivation,
  21007. // 2 points a small delta apart will be used to find its gradient
  21008. // which seems to give a reasonable approximation
  21009. getTangent( t, optionalTarget ) {
  21010. const delta = 0.0001;
  21011. let t1 = t - delta;
  21012. let t2 = t + delta;
  21013. // Capping in case of danger
  21014. if ( t1 < 0 ) t1 = 0;
  21015. if ( t2 > 1 ) t2 = 1;
  21016. const pt1 = this.getPoint( t1 );
  21017. const pt2 = this.getPoint( t2 );
  21018. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  21019. tangent.copy( pt2 ).sub( pt1 ).normalize();
  21020. return tangent;
  21021. }
  21022. getTangentAt( u, optionalTarget ) {
  21023. const t = this.getUtoTmapping( u );
  21024. return this.getTangent( t, optionalTarget );
  21025. }
  21026. computeFrenetFrames( segments, closed ) {
  21027. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21028. const normal = new Vector3();
  21029. const tangents = [];
  21030. const normals = [];
  21031. const binormals = [];
  21032. const vec = new Vector3();
  21033. const mat = new Matrix4();
  21034. // compute the tangent vectors for each segment on the curve
  21035. for ( let i = 0; i <= segments; i ++ ) {
  21036. const u = i / segments;
  21037. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  21038. }
  21039. // select an initial normal vector perpendicular to the first tangent vector,
  21040. // and in the direction of the minimum tangent xyz component
  21041. normals[ 0 ] = new Vector3();
  21042. binormals[ 0 ] = new Vector3();
  21043. let min = Number.MAX_VALUE;
  21044. const tx = Math.abs( tangents[ 0 ].x );
  21045. const ty = Math.abs( tangents[ 0 ].y );
  21046. const tz = Math.abs( tangents[ 0 ].z );
  21047. if ( tx <= min ) {
  21048. min = tx;
  21049. normal.set( 1, 0, 0 );
  21050. }
  21051. if ( ty <= min ) {
  21052. min = ty;
  21053. normal.set( 0, 1, 0 );
  21054. }
  21055. if ( tz <= min ) {
  21056. normal.set( 0, 0, 1 );
  21057. }
  21058. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21059. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21060. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21061. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21062. for ( let i = 1; i <= segments; i ++ ) {
  21063. normals[ i ] = normals[ i - 1 ].clone();
  21064. binormals[ i ] = binormals[ i - 1 ].clone();
  21065. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21066. if ( vec.length() > Number.EPSILON ) {
  21067. vec.normalize();
  21068. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21069. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21070. }
  21071. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21072. }
  21073. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21074. if ( closed === true ) {
  21075. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21076. theta /= segments;
  21077. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21078. theta = - theta;
  21079. }
  21080. for ( let i = 1; i <= segments; i ++ ) {
  21081. // twist a little...
  21082. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21083. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21084. }
  21085. }
  21086. return {
  21087. tangents: tangents,
  21088. normals: normals,
  21089. binormals: binormals
  21090. };
  21091. }
  21092. clone() {
  21093. return new this.constructor().copy( this );
  21094. }
  21095. copy( source ) {
  21096. this.arcLengthDivisions = source.arcLengthDivisions;
  21097. return this;
  21098. }
  21099. toJSON() {
  21100. const data = {
  21101. metadata: {
  21102. version: 4.6,
  21103. type: 'Curve',
  21104. generator: 'Curve.toJSON'
  21105. }
  21106. };
  21107. data.arcLengthDivisions = this.arcLengthDivisions;
  21108. data.type = this.type;
  21109. return data;
  21110. }
  21111. fromJSON( json ) {
  21112. this.arcLengthDivisions = json.arcLengthDivisions;
  21113. return this;
  21114. }
  21115. }
  21116. class EllipseCurve extends Curve {
  21117. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  21118. super();
  21119. this.isEllipseCurve = true;
  21120. this.type = 'EllipseCurve';
  21121. this.aX = aX;
  21122. this.aY = aY;
  21123. this.xRadius = xRadius;
  21124. this.yRadius = yRadius;
  21125. this.aStartAngle = aStartAngle;
  21126. this.aEndAngle = aEndAngle;
  21127. this.aClockwise = aClockwise;
  21128. this.aRotation = aRotation;
  21129. }
  21130. getPoint( t, optionalTarget = new Vector2() ) {
  21131. const point = optionalTarget;
  21132. const twoPi = Math.PI * 2;
  21133. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21134. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21135. // ensures that deltaAngle is 0 .. 2 PI
  21136. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21137. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21138. if ( deltaAngle < Number.EPSILON ) {
  21139. if ( samePoints ) {
  21140. deltaAngle = 0;
  21141. } else {
  21142. deltaAngle = twoPi;
  21143. }
  21144. }
  21145. if ( this.aClockwise === true && ! samePoints ) {
  21146. if ( deltaAngle === twoPi ) {
  21147. deltaAngle = - twoPi;
  21148. } else {
  21149. deltaAngle = deltaAngle - twoPi;
  21150. }
  21151. }
  21152. const angle = this.aStartAngle + t * deltaAngle;
  21153. let x = this.aX + this.xRadius * Math.cos( angle );
  21154. let y = this.aY + this.yRadius * Math.sin( angle );
  21155. if ( this.aRotation !== 0 ) {
  21156. const cos = Math.cos( this.aRotation );
  21157. const sin = Math.sin( this.aRotation );
  21158. const tx = x - this.aX;
  21159. const ty = y - this.aY;
  21160. // Rotate the point about the center of the ellipse.
  21161. x = tx * cos - ty * sin + this.aX;
  21162. y = tx * sin + ty * cos + this.aY;
  21163. }
  21164. return point.set( x, y );
  21165. }
  21166. copy( source ) {
  21167. super.copy( source );
  21168. this.aX = source.aX;
  21169. this.aY = source.aY;
  21170. this.xRadius = source.xRadius;
  21171. this.yRadius = source.yRadius;
  21172. this.aStartAngle = source.aStartAngle;
  21173. this.aEndAngle = source.aEndAngle;
  21174. this.aClockwise = source.aClockwise;
  21175. this.aRotation = source.aRotation;
  21176. return this;
  21177. }
  21178. toJSON() {
  21179. const data = super.toJSON();
  21180. data.aX = this.aX;
  21181. data.aY = this.aY;
  21182. data.xRadius = this.xRadius;
  21183. data.yRadius = this.yRadius;
  21184. data.aStartAngle = this.aStartAngle;
  21185. data.aEndAngle = this.aEndAngle;
  21186. data.aClockwise = this.aClockwise;
  21187. data.aRotation = this.aRotation;
  21188. return data;
  21189. }
  21190. fromJSON( json ) {
  21191. super.fromJSON( json );
  21192. this.aX = json.aX;
  21193. this.aY = json.aY;
  21194. this.xRadius = json.xRadius;
  21195. this.yRadius = json.yRadius;
  21196. this.aStartAngle = json.aStartAngle;
  21197. this.aEndAngle = json.aEndAngle;
  21198. this.aClockwise = json.aClockwise;
  21199. this.aRotation = json.aRotation;
  21200. return this;
  21201. }
  21202. }
  21203. class ArcCurve extends EllipseCurve {
  21204. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21205. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21206. this.isArcCurve = true;
  21207. this.type = 'ArcCurve';
  21208. }
  21209. }
  21210. /**
  21211. * Centripetal CatmullRom Curve - which is useful for avoiding
  21212. * cusps and self-intersections in non-uniform catmull rom curves.
  21213. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21214. *
  21215. * curve.type accepts centripetal(default), chordal and catmullrom
  21216. * curve.tension is used for catmullrom which defaults to 0.5
  21217. */
  21218. /*
  21219. Based on an optimized c++ solution in
  21220. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21221. - http://ideone.com/NoEbVM
  21222. This CubicPoly class could be used for reusing some variables and calculations,
  21223. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21224. which can be placed in CurveUtils.
  21225. */
  21226. function CubicPoly() {
  21227. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  21228. /*
  21229. * Compute coefficients for a cubic polynomial
  21230. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21231. * such that
  21232. * p(0) = x0, p(1) = x1
  21233. * and
  21234. * p'(0) = t0, p'(1) = t1.
  21235. */
  21236. function init( x0, x1, t0, t1 ) {
  21237. c0 = x0;
  21238. c1 = t0;
  21239. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21240. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21241. }
  21242. return {
  21243. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  21244. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21245. },
  21246. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21247. // compute tangents when parameterized in [t1,t2]
  21248. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21249. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21250. // rescale tangents for parametrization in [0,1]
  21251. t1 *= dt1;
  21252. t2 *= dt1;
  21253. init( x1, x2, t1, t2 );
  21254. },
  21255. calc: function ( t ) {
  21256. const t2 = t * t;
  21257. const t3 = t2 * t;
  21258. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21259. }
  21260. };
  21261. }
  21262. //
  21263. const tmp = /*@__PURE__*/ new Vector3();
  21264. const px = /*@__PURE__*/ new CubicPoly();
  21265. const py = /*@__PURE__*/ new CubicPoly();
  21266. const pz = /*@__PURE__*/ new CubicPoly();
  21267. class CatmullRomCurve3 extends Curve {
  21268. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  21269. super();
  21270. this.isCatmullRomCurve3 = true;
  21271. this.type = 'CatmullRomCurve3';
  21272. this.points = points;
  21273. this.closed = closed;
  21274. this.curveType = curveType;
  21275. this.tension = tension;
  21276. }
  21277. getPoint( t, optionalTarget = new Vector3() ) {
  21278. const point = optionalTarget;
  21279. const points = this.points;
  21280. const l = points.length;
  21281. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21282. let intPoint = Math.floor( p );
  21283. let weight = p - intPoint;
  21284. if ( this.closed ) {
  21285. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  21286. } else if ( weight === 0 && intPoint === l - 1 ) {
  21287. intPoint = l - 2;
  21288. weight = 1;
  21289. }
  21290. let p0, p3; // 4 points (p1 & p2 defined below)
  21291. if ( this.closed || intPoint > 0 ) {
  21292. p0 = points[ ( intPoint - 1 ) % l ];
  21293. } else {
  21294. // extrapolate first point
  21295. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21296. p0 = tmp;
  21297. }
  21298. const p1 = points[ intPoint % l ];
  21299. const p2 = points[ ( intPoint + 1 ) % l ];
  21300. if ( this.closed || intPoint + 2 < l ) {
  21301. p3 = points[ ( intPoint + 2 ) % l ];
  21302. } else {
  21303. // extrapolate last point
  21304. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21305. p3 = tmp;
  21306. }
  21307. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  21308. // init Centripetal / Chordal Catmull-Rom
  21309. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21310. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21311. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21312. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21313. // safety check for repeated points
  21314. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21315. if ( dt0 < 1e-4 ) dt0 = dt1;
  21316. if ( dt2 < 1e-4 ) dt2 = dt1;
  21317. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21318. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21319. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21320. } else if ( this.curveType === 'catmullrom' ) {
  21321. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  21322. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  21323. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  21324. }
  21325. point.set(
  21326. px.calc( weight ),
  21327. py.calc( weight ),
  21328. pz.calc( weight )
  21329. );
  21330. return point;
  21331. }
  21332. copy( source ) {
  21333. super.copy( source );
  21334. this.points = [];
  21335. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21336. const point = source.points[ i ];
  21337. this.points.push( point.clone() );
  21338. }
  21339. this.closed = source.closed;
  21340. this.curveType = source.curveType;
  21341. this.tension = source.tension;
  21342. return this;
  21343. }
  21344. toJSON() {
  21345. const data = super.toJSON();
  21346. data.points = [];
  21347. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21348. const point = this.points[ i ];
  21349. data.points.push( point.toArray() );
  21350. }
  21351. data.closed = this.closed;
  21352. data.curveType = this.curveType;
  21353. data.tension = this.tension;
  21354. return data;
  21355. }
  21356. fromJSON( json ) {
  21357. super.fromJSON( json );
  21358. this.points = [];
  21359. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21360. const point = json.points[ i ];
  21361. this.points.push( new Vector3().fromArray( point ) );
  21362. }
  21363. this.closed = json.closed;
  21364. this.curveType = json.curveType;
  21365. this.tension = json.tension;
  21366. return this;
  21367. }
  21368. }
  21369. /**
  21370. * Bezier Curves formulas obtained from
  21371. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  21372. */
  21373. function CatmullRom( t, p0, p1, p2, p3 ) {
  21374. const v0 = ( p2 - p0 ) * 0.5;
  21375. const v1 = ( p3 - p1 ) * 0.5;
  21376. const t2 = t * t;
  21377. const t3 = t * t2;
  21378. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21379. }
  21380. //
  21381. function QuadraticBezierP0( t, p ) {
  21382. const k = 1 - t;
  21383. return k * k * p;
  21384. }
  21385. function QuadraticBezierP1( t, p ) {
  21386. return 2 * ( 1 - t ) * t * p;
  21387. }
  21388. function QuadraticBezierP2( t, p ) {
  21389. return t * t * p;
  21390. }
  21391. function QuadraticBezier( t, p0, p1, p2 ) {
  21392. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  21393. QuadraticBezierP2( t, p2 );
  21394. }
  21395. //
  21396. function CubicBezierP0( t, p ) {
  21397. const k = 1 - t;
  21398. return k * k * k * p;
  21399. }
  21400. function CubicBezierP1( t, p ) {
  21401. const k = 1 - t;
  21402. return 3 * k * k * t * p;
  21403. }
  21404. function CubicBezierP2( t, p ) {
  21405. return 3 * ( 1 - t ) * t * t * p;
  21406. }
  21407. function CubicBezierP3( t, p ) {
  21408. return t * t * t * p;
  21409. }
  21410. function CubicBezier( t, p0, p1, p2, p3 ) {
  21411. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21412. CubicBezierP3( t, p3 );
  21413. }
  21414. class CubicBezierCurve extends Curve {
  21415. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21416. super();
  21417. this.isCubicBezierCurve = true;
  21418. this.type = 'CubicBezierCurve';
  21419. this.v0 = v0;
  21420. this.v1 = v1;
  21421. this.v2 = v2;
  21422. this.v3 = v3;
  21423. }
  21424. getPoint( t, optionalTarget = new Vector2() ) {
  21425. const point = optionalTarget;
  21426. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21427. point.set(
  21428. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21429. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21430. );
  21431. return point;
  21432. }
  21433. copy( source ) {
  21434. super.copy( source );
  21435. this.v0.copy( source.v0 );
  21436. this.v1.copy( source.v1 );
  21437. this.v2.copy( source.v2 );
  21438. this.v3.copy( source.v3 );
  21439. return this;
  21440. }
  21441. toJSON() {
  21442. const data = super.toJSON();
  21443. data.v0 = this.v0.toArray();
  21444. data.v1 = this.v1.toArray();
  21445. data.v2 = this.v2.toArray();
  21446. data.v3 = this.v3.toArray();
  21447. return data;
  21448. }
  21449. fromJSON( json ) {
  21450. super.fromJSON( json );
  21451. this.v0.fromArray( json.v0 );
  21452. this.v1.fromArray( json.v1 );
  21453. this.v2.fromArray( json.v2 );
  21454. this.v3.fromArray( json.v3 );
  21455. return this;
  21456. }
  21457. }
  21458. class CubicBezierCurve3 extends Curve {
  21459. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21460. super();
  21461. this.isCubicBezierCurve3 = true;
  21462. this.type = 'CubicBezierCurve3';
  21463. this.v0 = v0;
  21464. this.v1 = v1;
  21465. this.v2 = v2;
  21466. this.v3 = v3;
  21467. }
  21468. getPoint( t, optionalTarget = new Vector3() ) {
  21469. const point = optionalTarget;
  21470. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21471. point.set(
  21472. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21473. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21474. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21475. );
  21476. return point;
  21477. }
  21478. copy( source ) {
  21479. super.copy( source );
  21480. this.v0.copy( source.v0 );
  21481. this.v1.copy( source.v1 );
  21482. this.v2.copy( source.v2 );
  21483. this.v3.copy( source.v3 );
  21484. return this;
  21485. }
  21486. toJSON() {
  21487. const data = super.toJSON();
  21488. data.v0 = this.v0.toArray();
  21489. data.v1 = this.v1.toArray();
  21490. data.v2 = this.v2.toArray();
  21491. data.v3 = this.v3.toArray();
  21492. return data;
  21493. }
  21494. fromJSON( json ) {
  21495. super.fromJSON( json );
  21496. this.v0.fromArray( json.v0 );
  21497. this.v1.fromArray( json.v1 );
  21498. this.v2.fromArray( json.v2 );
  21499. this.v3.fromArray( json.v3 );
  21500. return this;
  21501. }
  21502. }
  21503. class LineCurve extends Curve {
  21504. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21505. super();
  21506. this.isLineCurve = true;
  21507. this.type = 'LineCurve';
  21508. this.v1 = v1;
  21509. this.v2 = v2;
  21510. }
  21511. getPoint( t, optionalTarget = new Vector2() ) {
  21512. const point = optionalTarget;
  21513. if ( t === 1 ) {
  21514. point.copy( this.v2 );
  21515. } else {
  21516. point.copy( this.v2 ).sub( this.v1 );
  21517. point.multiplyScalar( t ).add( this.v1 );
  21518. }
  21519. return point;
  21520. }
  21521. // Line curve is linear, so we can overwrite default getPointAt
  21522. getPointAt( u, optionalTarget ) {
  21523. return this.getPoint( u, optionalTarget );
  21524. }
  21525. getTangent( t, optionalTarget = new Vector2() ) {
  21526. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21527. }
  21528. getTangentAt( u, optionalTarget ) {
  21529. return this.getTangent( u, optionalTarget );
  21530. }
  21531. copy( source ) {
  21532. super.copy( source );
  21533. this.v1.copy( source.v1 );
  21534. this.v2.copy( source.v2 );
  21535. return this;
  21536. }
  21537. toJSON() {
  21538. const data = super.toJSON();
  21539. data.v1 = this.v1.toArray();
  21540. data.v2 = this.v2.toArray();
  21541. return data;
  21542. }
  21543. fromJSON( json ) {
  21544. super.fromJSON( json );
  21545. this.v1.fromArray( json.v1 );
  21546. this.v2.fromArray( json.v2 );
  21547. return this;
  21548. }
  21549. }
  21550. class LineCurve3 extends Curve {
  21551. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21552. super();
  21553. this.isLineCurve3 = true;
  21554. this.type = 'LineCurve3';
  21555. this.v1 = v1;
  21556. this.v2 = v2;
  21557. }
  21558. getPoint( t, optionalTarget = new Vector3() ) {
  21559. const point = optionalTarget;
  21560. if ( t === 1 ) {
  21561. point.copy( this.v2 );
  21562. } else {
  21563. point.copy( this.v2 ).sub( this.v1 );
  21564. point.multiplyScalar( t ).add( this.v1 );
  21565. }
  21566. return point;
  21567. }
  21568. // Line curve is linear, so we can overwrite default getPointAt
  21569. getPointAt( u, optionalTarget ) {
  21570. return this.getPoint( u, optionalTarget );
  21571. }
  21572. getTangent( t, optionalTarget = new Vector3() ) {
  21573. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21574. }
  21575. getTangentAt( u, optionalTarget ) {
  21576. return this.getTangent( u, optionalTarget );
  21577. }
  21578. copy( source ) {
  21579. super.copy( source );
  21580. this.v1.copy( source.v1 );
  21581. this.v2.copy( source.v2 );
  21582. return this;
  21583. }
  21584. toJSON() {
  21585. const data = super.toJSON();
  21586. data.v1 = this.v1.toArray();
  21587. data.v2 = this.v2.toArray();
  21588. return data;
  21589. }
  21590. fromJSON( json ) {
  21591. super.fromJSON( json );
  21592. this.v1.fromArray( json.v1 );
  21593. this.v2.fromArray( json.v2 );
  21594. return this;
  21595. }
  21596. }
  21597. class QuadraticBezierCurve extends Curve {
  21598. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21599. super();
  21600. this.isQuadraticBezierCurve = true;
  21601. this.type = 'QuadraticBezierCurve';
  21602. this.v0 = v0;
  21603. this.v1 = v1;
  21604. this.v2 = v2;
  21605. }
  21606. getPoint( t, optionalTarget = new Vector2() ) {
  21607. const point = optionalTarget;
  21608. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21609. point.set(
  21610. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21611. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21612. );
  21613. return point;
  21614. }
  21615. copy( source ) {
  21616. super.copy( source );
  21617. this.v0.copy( source.v0 );
  21618. this.v1.copy( source.v1 );
  21619. this.v2.copy( source.v2 );
  21620. return this;
  21621. }
  21622. toJSON() {
  21623. const data = super.toJSON();
  21624. data.v0 = this.v0.toArray();
  21625. data.v1 = this.v1.toArray();
  21626. data.v2 = this.v2.toArray();
  21627. return data;
  21628. }
  21629. fromJSON( json ) {
  21630. super.fromJSON( json );
  21631. this.v0.fromArray( json.v0 );
  21632. this.v1.fromArray( json.v1 );
  21633. this.v2.fromArray( json.v2 );
  21634. return this;
  21635. }
  21636. }
  21637. class QuadraticBezierCurve3 extends Curve {
  21638. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21639. super();
  21640. this.isQuadraticBezierCurve3 = true;
  21641. this.type = 'QuadraticBezierCurve3';
  21642. this.v0 = v0;
  21643. this.v1 = v1;
  21644. this.v2 = v2;
  21645. }
  21646. getPoint( t, optionalTarget = new Vector3() ) {
  21647. const point = optionalTarget;
  21648. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21649. point.set(
  21650. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21651. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21652. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21653. );
  21654. return point;
  21655. }
  21656. copy( source ) {
  21657. super.copy( source );
  21658. this.v0.copy( source.v0 );
  21659. this.v1.copy( source.v1 );
  21660. this.v2.copy( source.v2 );
  21661. return this;
  21662. }
  21663. toJSON() {
  21664. const data = super.toJSON();
  21665. data.v0 = this.v0.toArray();
  21666. data.v1 = this.v1.toArray();
  21667. data.v2 = this.v2.toArray();
  21668. return data;
  21669. }
  21670. fromJSON( json ) {
  21671. super.fromJSON( json );
  21672. this.v0.fromArray( json.v0 );
  21673. this.v1.fromArray( json.v1 );
  21674. this.v2.fromArray( json.v2 );
  21675. return this;
  21676. }
  21677. }
  21678. class SplineCurve extends Curve {
  21679. constructor( points = [] ) {
  21680. super();
  21681. this.isSplineCurve = true;
  21682. this.type = 'SplineCurve';
  21683. this.points = points;
  21684. }
  21685. getPoint( t, optionalTarget = new Vector2() ) {
  21686. const point = optionalTarget;
  21687. const points = this.points;
  21688. const p = ( points.length - 1 ) * t;
  21689. const intPoint = Math.floor( p );
  21690. const weight = p - intPoint;
  21691. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21692. const p1 = points[ intPoint ];
  21693. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21694. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21695. point.set(
  21696. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21697. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21698. );
  21699. return point;
  21700. }
  21701. copy( source ) {
  21702. super.copy( source );
  21703. this.points = [];
  21704. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21705. const point = source.points[ i ];
  21706. this.points.push( point.clone() );
  21707. }
  21708. return this;
  21709. }
  21710. toJSON() {
  21711. const data = super.toJSON();
  21712. data.points = [];
  21713. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21714. const point = this.points[ i ];
  21715. data.points.push( point.toArray() );
  21716. }
  21717. return data;
  21718. }
  21719. fromJSON( json ) {
  21720. super.fromJSON( json );
  21721. this.points = [];
  21722. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21723. const point = json.points[ i ];
  21724. this.points.push( new Vector2().fromArray( point ) );
  21725. }
  21726. return this;
  21727. }
  21728. }
  21729. var Curves = /*#__PURE__*/Object.freeze({
  21730. __proto__: null,
  21731. ArcCurve: ArcCurve,
  21732. CatmullRomCurve3: CatmullRomCurve3,
  21733. CubicBezierCurve: CubicBezierCurve,
  21734. CubicBezierCurve3: CubicBezierCurve3,
  21735. EllipseCurve: EllipseCurve,
  21736. LineCurve: LineCurve,
  21737. LineCurve3: LineCurve3,
  21738. QuadraticBezierCurve: QuadraticBezierCurve,
  21739. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21740. SplineCurve: SplineCurve
  21741. });
  21742. /**************************************************************
  21743. * Curved Path - a curve path is simply a array of connected
  21744. * curves, but retains the api of a curve
  21745. **************************************************************/
  21746. class CurvePath extends Curve {
  21747. constructor() {
  21748. super();
  21749. this.type = 'CurvePath';
  21750. this.curves = [];
  21751. this.autoClose = false; // Automatically closes the path
  21752. }
  21753. add( curve ) {
  21754. this.curves.push( curve );
  21755. }
  21756. closePath() {
  21757. // Add a line curve if start and end of lines are not connected
  21758. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21759. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21760. if ( ! startPoint.equals( endPoint ) ) {
  21761. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21762. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21763. }
  21764. return this;
  21765. }
  21766. // To get accurate point with reference to
  21767. // entire path distance at time t,
  21768. // following has to be done:
  21769. // 1. Length of each sub path have to be known
  21770. // 2. Locate and identify type of curve
  21771. // 3. Get t for the curve
  21772. // 4. Return curve.getPointAt(t')
  21773. getPoint( t, optionalTarget ) {
  21774. const d = t * this.getLength();
  21775. const curveLengths = this.getCurveLengths();
  21776. let i = 0;
  21777. // To think about boundaries points.
  21778. while ( i < curveLengths.length ) {
  21779. if ( curveLengths[ i ] >= d ) {
  21780. const diff = curveLengths[ i ] - d;
  21781. const curve = this.curves[ i ];
  21782. const segmentLength = curve.getLength();
  21783. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21784. return curve.getPointAt( u, optionalTarget );
  21785. }
  21786. i ++;
  21787. }
  21788. return null;
  21789. // loop where sum != 0, sum > d , sum+1 <d
  21790. }
  21791. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21792. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21793. // getPoint() depends on getLength
  21794. getLength() {
  21795. const lens = this.getCurveLengths();
  21796. return lens[ lens.length - 1 ];
  21797. }
  21798. // cacheLengths must be recalculated.
  21799. updateArcLengths() {
  21800. this.needsUpdate = true;
  21801. this.cacheLengths = null;
  21802. this.getCurveLengths();
  21803. }
  21804. // Compute lengths and cache them
  21805. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21806. getCurveLengths() {
  21807. // We use cache values if curves and cache array are same length
  21808. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21809. return this.cacheLengths;
  21810. }
  21811. // Get length of sub-curve
  21812. // Push sums into cached array
  21813. const lengths = [];
  21814. let sums = 0;
  21815. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21816. sums += this.curves[ i ].getLength();
  21817. lengths.push( sums );
  21818. }
  21819. this.cacheLengths = lengths;
  21820. return lengths;
  21821. }
  21822. getSpacedPoints( divisions = 40 ) {
  21823. const points = [];
  21824. for ( let i = 0; i <= divisions; i ++ ) {
  21825. points.push( this.getPoint( i / divisions ) );
  21826. }
  21827. if ( this.autoClose ) {
  21828. points.push( points[ 0 ] );
  21829. }
  21830. return points;
  21831. }
  21832. getPoints( divisions = 12 ) {
  21833. const points = [];
  21834. let last;
  21835. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21836. const curve = curves[ i ];
  21837. const resolution = curve.isEllipseCurve ? divisions * 2
  21838. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21839. : curve.isSplineCurve ? divisions * curve.points.length
  21840. : divisions;
  21841. const pts = curve.getPoints( resolution );
  21842. for ( let j = 0; j < pts.length; j ++ ) {
  21843. const point = pts[ j ];
  21844. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21845. points.push( point );
  21846. last = point;
  21847. }
  21848. }
  21849. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21850. points.push( points[ 0 ] );
  21851. }
  21852. return points;
  21853. }
  21854. copy( source ) {
  21855. super.copy( source );
  21856. this.curves = [];
  21857. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21858. const curve = source.curves[ i ];
  21859. this.curves.push( curve.clone() );
  21860. }
  21861. this.autoClose = source.autoClose;
  21862. return this;
  21863. }
  21864. toJSON() {
  21865. const data = super.toJSON();
  21866. data.autoClose = this.autoClose;
  21867. data.curves = [];
  21868. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21869. const curve = this.curves[ i ];
  21870. data.curves.push( curve.toJSON() );
  21871. }
  21872. return data;
  21873. }
  21874. fromJSON( json ) {
  21875. super.fromJSON( json );
  21876. this.autoClose = json.autoClose;
  21877. this.curves = [];
  21878. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21879. const curve = json.curves[ i ];
  21880. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21881. }
  21882. return this;
  21883. }
  21884. }
  21885. class Path extends CurvePath {
  21886. constructor( points ) {
  21887. super();
  21888. this.type = 'Path';
  21889. this.currentPoint = new Vector2();
  21890. if ( points ) {
  21891. this.setFromPoints( points );
  21892. }
  21893. }
  21894. setFromPoints( points ) {
  21895. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21896. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21897. this.lineTo( points[ i ].x, points[ i ].y );
  21898. }
  21899. return this;
  21900. }
  21901. moveTo( x, y ) {
  21902. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21903. return this;
  21904. }
  21905. lineTo( x, y ) {
  21906. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21907. this.curves.push( curve );
  21908. this.currentPoint.set( x, y );
  21909. return this;
  21910. }
  21911. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21912. const curve = new QuadraticBezierCurve(
  21913. this.currentPoint.clone(),
  21914. new Vector2( aCPx, aCPy ),
  21915. new Vector2( aX, aY )
  21916. );
  21917. this.curves.push( curve );
  21918. this.currentPoint.set( aX, aY );
  21919. return this;
  21920. }
  21921. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21922. const curve = new CubicBezierCurve(
  21923. this.currentPoint.clone(),
  21924. new Vector2( aCP1x, aCP1y ),
  21925. new Vector2( aCP2x, aCP2y ),
  21926. new Vector2( aX, aY )
  21927. );
  21928. this.curves.push( curve );
  21929. this.currentPoint.set( aX, aY );
  21930. return this;
  21931. }
  21932. splineThru( pts /*Array of Vector*/ ) {
  21933. const npts = [ this.currentPoint.clone() ].concat( pts );
  21934. const curve = new SplineCurve( npts );
  21935. this.curves.push( curve );
  21936. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21937. return this;
  21938. }
  21939. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21940. const x0 = this.currentPoint.x;
  21941. const y0 = this.currentPoint.y;
  21942. this.absarc( aX + x0, aY + y0, aRadius,
  21943. aStartAngle, aEndAngle, aClockwise );
  21944. return this;
  21945. }
  21946. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21947. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21948. return this;
  21949. }
  21950. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21951. const x0 = this.currentPoint.x;
  21952. const y0 = this.currentPoint.y;
  21953. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21954. return this;
  21955. }
  21956. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21957. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21958. if ( this.curves.length > 0 ) {
  21959. // if a previous curve is present, attempt to join
  21960. const firstPoint = curve.getPoint( 0 );
  21961. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21962. this.lineTo( firstPoint.x, firstPoint.y );
  21963. }
  21964. }
  21965. this.curves.push( curve );
  21966. const lastPoint = curve.getPoint( 1 );
  21967. this.currentPoint.copy( lastPoint );
  21968. return this;
  21969. }
  21970. copy( source ) {
  21971. super.copy( source );
  21972. this.currentPoint.copy( source.currentPoint );
  21973. return this;
  21974. }
  21975. toJSON() {
  21976. const data = super.toJSON();
  21977. data.currentPoint = this.currentPoint.toArray();
  21978. return data;
  21979. }
  21980. fromJSON( json ) {
  21981. super.fromJSON( json );
  21982. this.currentPoint.fromArray( json.currentPoint );
  21983. return this;
  21984. }
  21985. }
  21986. class LatheGeometry extends BufferGeometry {
  21987. 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 ) {
  21988. super();
  21989. this.type = 'LatheGeometry';
  21990. this.parameters = {
  21991. points: points,
  21992. segments: segments,
  21993. phiStart: phiStart,
  21994. phiLength: phiLength
  21995. };
  21996. segments = Math.floor( segments );
  21997. // clamp phiLength so it's in range of [ 0, 2PI ]
  21998. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21999. // buffers
  22000. const indices = [];
  22001. const vertices = [];
  22002. const uvs = [];
  22003. const initNormals = [];
  22004. const normals = [];
  22005. // helper variables
  22006. const inverseSegments = 1.0 / segments;
  22007. const vertex = new Vector3();
  22008. const uv = new Vector2();
  22009. const normal = new Vector3();
  22010. const curNormal = new Vector3();
  22011. const prevNormal = new Vector3();
  22012. let dx = 0;
  22013. let dy = 0;
  22014. // pre-compute normals for initial "meridian"
  22015. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  22016. switch ( j ) {
  22017. case 0: // special handling for 1st vertex on path
  22018. dx = points[ j + 1 ].x - points[ j ].x;
  22019. dy = points[ j + 1 ].y - points[ j ].y;
  22020. normal.x = dy * 1.0;
  22021. normal.y = - dx;
  22022. normal.z = dy * 0.0;
  22023. prevNormal.copy( normal );
  22024. normal.normalize();
  22025. initNormals.push( normal.x, normal.y, normal.z );
  22026. break;
  22027. case ( points.length - 1 ): // special handling for last Vertex on path
  22028. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  22029. break;
  22030. default: // default handling for all vertices in between
  22031. dx = points[ j + 1 ].x - points[ j ].x;
  22032. dy = points[ j + 1 ].y - points[ j ].y;
  22033. normal.x = dy * 1.0;
  22034. normal.y = - dx;
  22035. normal.z = dy * 0.0;
  22036. curNormal.copy( normal );
  22037. normal.x += prevNormal.x;
  22038. normal.y += prevNormal.y;
  22039. normal.z += prevNormal.z;
  22040. normal.normalize();
  22041. initNormals.push( normal.x, normal.y, normal.z );
  22042. prevNormal.copy( curNormal );
  22043. }
  22044. }
  22045. // generate vertices, uvs and normals
  22046. for ( let i = 0; i <= segments; i ++ ) {
  22047. const phi = phiStart + i * inverseSegments * phiLength;
  22048. const sin = Math.sin( phi );
  22049. const cos = Math.cos( phi );
  22050. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  22051. // vertex
  22052. vertex.x = points[ j ].x * sin;
  22053. vertex.y = points[ j ].y;
  22054. vertex.z = points[ j ].x * cos;
  22055. vertices.push( vertex.x, vertex.y, vertex.z );
  22056. // uv
  22057. uv.x = i / segments;
  22058. uv.y = j / ( points.length - 1 );
  22059. uvs.push( uv.x, uv.y );
  22060. // normal
  22061. const x = initNormals[ 3 * j + 0 ] * sin;
  22062. const y = initNormals[ 3 * j + 1 ];
  22063. const z = initNormals[ 3 * j + 0 ] * cos;
  22064. normals.push( x, y, z );
  22065. }
  22066. }
  22067. // indices
  22068. for ( let i = 0; i < segments; i ++ ) {
  22069. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  22070. const base = j + i * points.length;
  22071. const a = base;
  22072. const b = base + points.length;
  22073. const c = base + points.length + 1;
  22074. const d = base + 1;
  22075. // faces
  22076. indices.push( a, b, d );
  22077. indices.push( c, d, b );
  22078. }
  22079. }
  22080. // build geometry
  22081. this.setIndex( indices );
  22082. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22083. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22084. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22085. }
  22086. copy( source ) {
  22087. super.copy( source );
  22088. this.parameters = Object.assign( {}, source.parameters );
  22089. return this;
  22090. }
  22091. static fromJSON( data ) {
  22092. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  22093. }
  22094. }
  22095. class CapsuleGeometry extends LatheGeometry {
  22096. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  22097. const path = new Path();
  22098. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  22099. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  22100. super( path.getPoints( capSegments ), radialSegments );
  22101. this.type = 'CapsuleGeometry';
  22102. this.parameters = {
  22103. radius: radius,
  22104. length: length,
  22105. capSegments: capSegments,
  22106. radialSegments: radialSegments,
  22107. };
  22108. }
  22109. static fromJSON( data ) {
  22110. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  22111. }
  22112. }
  22113. class CircleGeometry extends BufferGeometry {
  22114. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22115. super();
  22116. this.type = 'CircleGeometry';
  22117. this.parameters = {
  22118. radius: radius,
  22119. segments: segments,
  22120. thetaStart: thetaStart,
  22121. thetaLength: thetaLength
  22122. };
  22123. segments = Math.max( 3, segments );
  22124. // buffers
  22125. const indices = [];
  22126. const vertices = [];
  22127. const normals = [];
  22128. const uvs = [];
  22129. // helper variables
  22130. const vertex = new Vector3();
  22131. const uv = new Vector2();
  22132. // center point
  22133. vertices.push( 0, 0, 0 );
  22134. normals.push( 0, 0, 1 );
  22135. uvs.push( 0.5, 0.5 );
  22136. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22137. const segment = thetaStart + s / segments * thetaLength;
  22138. // vertex
  22139. vertex.x = radius * Math.cos( segment );
  22140. vertex.y = radius * Math.sin( segment );
  22141. vertices.push( vertex.x, vertex.y, vertex.z );
  22142. // normal
  22143. normals.push( 0, 0, 1 );
  22144. // uvs
  22145. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22146. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22147. uvs.push( uv.x, uv.y );
  22148. }
  22149. // indices
  22150. for ( let i = 1; i <= segments; i ++ ) {
  22151. indices.push( i, i + 1, 0 );
  22152. }
  22153. // build geometry
  22154. this.setIndex( indices );
  22155. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22156. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22157. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22158. }
  22159. copy( source ) {
  22160. super.copy( source );
  22161. this.parameters = Object.assign( {}, source.parameters );
  22162. return this;
  22163. }
  22164. static fromJSON( data ) {
  22165. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22166. }
  22167. }
  22168. class CylinderGeometry extends BufferGeometry {
  22169. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22170. super();
  22171. this.type = 'CylinderGeometry';
  22172. this.parameters = {
  22173. radiusTop: radiusTop,
  22174. radiusBottom: radiusBottom,
  22175. height: height,
  22176. radialSegments: radialSegments,
  22177. heightSegments: heightSegments,
  22178. openEnded: openEnded,
  22179. thetaStart: thetaStart,
  22180. thetaLength: thetaLength
  22181. };
  22182. const scope = this;
  22183. radialSegments = Math.floor( radialSegments );
  22184. heightSegments = Math.floor( heightSegments );
  22185. // buffers
  22186. const indices = [];
  22187. const vertices = [];
  22188. const normals = [];
  22189. const uvs = [];
  22190. // helper variables
  22191. let index = 0;
  22192. const indexArray = [];
  22193. const halfHeight = height / 2;
  22194. let groupStart = 0;
  22195. // generate geometry
  22196. generateTorso();
  22197. if ( openEnded === false ) {
  22198. if ( radiusTop > 0 ) generateCap( true );
  22199. if ( radiusBottom > 0 ) generateCap( false );
  22200. }
  22201. // build geometry
  22202. this.setIndex( indices );
  22203. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22204. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22205. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22206. function generateTorso() {
  22207. const normal = new Vector3();
  22208. const vertex = new Vector3();
  22209. let groupCount = 0;
  22210. // this will be used to calculate the normal
  22211. const slope = ( radiusBottom - radiusTop ) / height;
  22212. // generate vertices, normals and uvs
  22213. for ( let y = 0; y <= heightSegments; y ++ ) {
  22214. const indexRow = [];
  22215. const v = y / heightSegments;
  22216. // calculate the radius of the current row
  22217. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22218. for ( let x = 0; x <= radialSegments; x ++ ) {
  22219. const u = x / radialSegments;
  22220. const theta = u * thetaLength + thetaStart;
  22221. const sinTheta = Math.sin( theta );
  22222. const cosTheta = Math.cos( theta );
  22223. // vertex
  22224. vertex.x = radius * sinTheta;
  22225. vertex.y = - v * height + halfHeight;
  22226. vertex.z = radius * cosTheta;
  22227. vertices.push( vertex.x, vertex.y, vertex.z );
  22228. // normal
  22229. normal.set( sinTheta, slope, cosTheta ).normalize();
  22230. normals.push( normal.x, normal.y, normal.z );
  22231. // uv
  22232. uvs.push( u, 1 - v );
  22233. // save index of vertex in respective row
  22234. indexRow.push( index ++ );
  22235. }
  22236. // now save vertices of the row in our index array
  22237. indexArray.push( indexRow );
  22238. }
  22239. // generate indices
  22240. for ( let x = 0; x < radialSegments; x ++ ) {
  22241. for ( let y = 0; y < heightSegments; y ++ ) {
  22242. // we use the index array to access the correct indices
  22243. const a = indexArray[ y ][ x ];
  22244. const b = indexArray[ y + 1 ][ x ];
  22245. const c = indexArray[ y + 1 ][ x + 1 ];
  22246. const d = indexArray[ y ][ x + 1 ];
  22247. // faces
  22248. indices.push( a, b, d );
  22249. indices.push( b, c, d );
  22250. // update group counter
  22251. groupCount += 6;
  22252. }
  22253. }
  22254. // add a group to the geometry. this will ensure multi material support
  22255. scope.addGroup( groupStart, groupCount, 0 );
  22256. // calculate new start value for groups
  22257. groupStart += groupCount;
  22258. }
  22259. function generateCap( top ) {
  22260. // save the index of the first center vertex
  22261. const centerIndexStart = index;
  22262. const uv = new Vector2();
  22263. const vertex = new Vector3();
  22264. let groupCount = 0;
  22265. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22266. const sign = ( top === true ) ? 1 : - 1;
  22267. // first we generate the center vertex data of the cap.
  22268. // because the geometry needs one set of uvs per face,
  22269. // we must generate a center vertex per face/segment
  22270. for ( let x = 1; x <= radialSegments; x ++ ) {
  22271. // vertex
  22272. vertices.push( 0, halfHeight * sign, 0 );
  22273. // normal
  22274. normals.push( 0, sign, 0 );
  22275. // uv
  22276. uvs.push( 0.5, 0.5 );
  22277. // increase index
  22278. index ++;
  22279. }
  22280. // save the index of the last center vertex
  22281. const centerIndexEnd = index;
  22282. // now we generate the surrounding vertices, normals and uvs
  22283. for ( let x = 0; x <= radialSegments; x ++ ) {
  22284. const u = x / radialSegments;
  22285. const theta = u * thetaLength + thetaStart;
  22286. const cosTheta = Math.cos( theta );
  22287. const sinTheta = Math.sin( theta );
  22288. // vertex
  22289. vertex.x = radius * sinTheta;
  22290. vertex.y = halfHeight * sign;
  22291. vertex.z = radius * cosTheta;
  22292. vertices.push( vertex.x, vertex.y, vertex.z );
  22293. // normal
  22294. normals.push( 0, sign, 0 );
  22295. // uv
  22296. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22297. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22298. uvs.push( uv.x, uv.y );
  22299. // increase index
  22300. index ++;
  22301. }
  22302. // generate indices
  22303. for ( let x = 0; x < radialSegments; x ++ ) {
  22304. const c = centerIndexStart + x;
  22305. const i = centerIndexEnd + x;
  22306. if ( top === true ) {
  22307. // face top
  22308. indices.push( i, i + 1, c );
  22309. } else {
  22310. // face bottom
  22311. indices.push( i + 1, i, c );
  22312. }
  22313. groupCount += 3;
  22314. }
  22315. // add a group to the geometry. this will ensure multi material support
  22316. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22317. // calculate new start value for groups
  22318. groupStart += groupCount;
  22319. }
  22320. }
  22321. copy( source ) {
  22322. super.copy( source );
  22323. this.parameters = Object.assign( {}, source.parameters );
  22324. return this;
  22325. }
  22326. static fromJSON( data ) {
  22327. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22328. }
  22329. }
  22330. class ConeGeometry extends CylinderGeometry {
  22331. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22332. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22333. this.type = 'ConeGeometry';
  22334. this.parameters = {
  22335. radius: radius,
  22336. height: height,
  22337. radialSegments: radialSegments,
  22338. heightSegments: heightSegments,
  22339. openEnded: openEnded,
  22340. thetaStart: thetaStart,
  22341. thetaLength: thetaLength
  22342. };
  22343. }
  22344. static fromJSON( data ) {
  22345. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22346. }
  22347. }
  22348. class PolyhedronGeometry extends BufferGeometry {
  22349. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22350. super();
  22351. this.type = 'PolyhedronGeometry';
  22352. this.parameters = {
  22353. vertices: vertices,
  22354. indices: indices,
  22355. radius: radius,
  22356. detail: detail
  22357. };
  22358. // default buffer data
  22359. const vertexBuffer = [];
  22360. const uvBuffer = [];
  22361. // the subdivision creates the vertex buffer data
  22362. subdivide( detail );
  22363. // all vertices should lie on a conceptual sphere with a given radius
  22364. applyRadius( radius );
  22365. // finally, create the uv data
  22366. generateUVs();
  22367. // build non-indexed geometry
  22368. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22369. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22370. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22371. if ( detail === 0 ) {
  22372. this.computeVertexNormals(); // flat normals
  22373. } else {
  22374. this.normalizeNormals(); // smooth normals
  22375. }
  22376. // helper functions
  22377. function subdivide( detail ) {
  22378. const a = new Vector3();
  22379. const b = new Vector3();
  22380. const c = new Vector3();
  22381. // iterate over all faces and apply a subdivision with the given detail value
  22382. for ( let i = 0; i < indices.length; i += 3 ) {
  22383. // get the vertices of the face
  22384. getVertexByIndex( indices[ i + 0 ], a );
  22385. getVertexByIndex( indices[ i + 1 ], b );
  22386. getVertexByIndex( indices[ i + 2 ], c );
  22387. // perform subdivision
  22388. subdivideFace( a, b, c, detail );
  22389. }
  22390. }
  22391. function subdivideFace( a, b, c, detail ) {
  22392. const cols = detail + 1;
  22393. // we use this multidimensional array as a data structure for creating the subdivision
  22394. const v = [];
  22395. // construct all of the vertices for this subdivision
  22396. for ( let i = 0; i <= cols; i ++ ) {
  22397. v[ i ] = [];
  22398. const aj = a.clone().lerp( c, i / cols );
  22399. const bj = b.clone().lerp( c, i / cols );
  22400. const rows = cols - i;
  22401. for ( let j = 0; j <= rows; j ++ ) {
  22402. if ( j === 0 && i === cols ) {
  22403. v[ i ][ j ] = aj;
  22404. } else {
  22405. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22406. }
  22407. }
  22408. }
  22409. // construct all of the faces
  22410. for ( let i = 0; i < cols; i ++ ) {
  22411. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22412. const k = Math.floor( j / 2 );
  22413. if ( j % 2 === 0 ) {
  22414. pushVertex( v[ i ][ k + 1 ] );
  22415. pushVertex( v[ i + 1 ][ k ] );
  22416. pushVertex( v[ i ][ k ] );
  22417. } else {
  22418. pushVertex( v[ i ][ k + 1 ] );
  22419. pushVertex( v[ i + 1 ][ k + 1 ] );
  22420. pushVertex( v[ i + 1 ][ k ] );
  22421. }
  22422. }
  22423. }
  22424. }
  22425. function applyRadius( radius ) {
  22426. const vertex = new Vector3();
  22427. // iterate over the entire buffer and apply the radius to each vertex
  22428. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22429. vertex.x = vertexBuffer[ i + 0 ];
  22430. vertex.y = vertexBuffer[ i + 1 ];
  22431. vertex.z = vertexBuffer[ i + 2 ];
  22432. vertex.normalize().multiplyScalar( radius );
  22433. vertexBuffer[ i + 0 ] = vertex.x;
  22434. vertexBuffer[ i + 1 ] = vertex.y;
  22435. vertexBuffer[ i + 2 ] = vertex.z;
  22436. }
  22437. }
  22438. function generateUVs() {
  22439. const vertex = new Vector3();
  22440. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22441. vertex.x = vertexBuffer[ i + 0 ];
  22442. vertex.y = vertexBuffer[ i + 1 ];
  22443. vertex.z = vertexBuffer[ i + 2 ];
  22444. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22445. const v = inclination( vertex ) / Math.PI + 0.5;
  22446. uvBuffer.push( u, 1 - v );
  22447. }
  22448. correctUVs();
  22449. correctSeam();
  22450. }
  22451. function correctSeam() {
  22452. // handle case when face straddles the seam, see #3269
  22453. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22454. // uv data of a single face
  22455. const x0 = uvBuffer[ i + 0 ];
  22456. const x1 = uvBuffer[ i + 2 ];
  22457. const x2 = uvBuffer[ i + 4 ];
  22458. const max = Math.max( x0, x1, x2 );
  22459. const min = Math.min( x0, x1, x2 );
  22460. // 0.9 is somewhat arbitrary
  22461. if ( max > 0.9 && min < 0.1 ) {
  22462. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22463. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22464. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22465. }
  22466. }
  22467. }
  22468. function pushVertex( vertex ) {
  22469. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22470. }
  22471. function getVertexByIndex( index, vertex ) {
  22472. const stride = index * 3;
  22473. vertex.x = vertices[ stride + 0 ];
  22474. vertex.y = vertices[ stride + 1 ];
  22475. vertex.z = vertices[ stride + 2 ];
  22476. }
  22477. function correctUVs() {
  22478. const a = new Vector3();
  22479. const b = new Vector3();
  22480. const c = new Vector3();
  22481. const centroid = new Vector3();
  22482. const uvA = new Vector2();
  22483. const uvB = new Vector2();
  22484. const uvC = new Vector2();
  22485. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22486. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22487. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22488. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22489. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22490. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22491. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22492. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22493. const azi = azimuth( centroid );
  22494. correctUV( uvA, j + 0, a, azi );
  22495. correctUV( uvB, j + 2, b, azi );
  22496. correctUV( uvC, j + 4, c, azi );
  22497. }
  22498. }
  22499. function correctUV( uv, stride, vector, azimuth ) {
  22500. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22501. uvBuffer[ stride ] = uv.x - 1;
  22502. }
  22503. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22504. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22505. }
  22506. }
  22507. // Angle around the Y axis, counter-clockwise when looking from above.
  22508. function azimuth( vector ) {
  22509. return Math.atan2( vector.z, - vector.x );
  22510. }
  22511. // Angle above the XZ plane.
  22512. function inclination( vector ) {
  22513. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22514. }
  22515. }
  22516. copy( source ) {
  22517. super.copy( source );
  22518. this.parameters = Object.assign( {}, source.parameters );
  22519. return this;
  22520. }
  22521. static fromJSON( data ) {
  22522. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22523. }
  22524. }
  22525. class DodecahedronGeometry extends PolyhedronGeometry {
  22526. constructor( radius = 1, detail = 0 ) {
  22527. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22528. const r = 1 / t;
  22529. const vertices = [
  22530. // (±1, ±1, ±1)
  22531. - 1, - 1, - 1, - 1, - 1, 1,
  22532. - 1, 1, - 1, - 1, 1, 1,
  22533. 1, - 1, - 1, 1, - 1, 1,
  22534. 1, 1, - 1, 1, 1, 1,
  22535. // (0, ±1/φ, ±φ)
  22536. 0, - r, - t, 0, - r, t,
  22537. 0, r, - t, 0, r, t,
  22538. // (±1/φ, ±φ, 0)
  22539. - r, - t, 0, - r, t, 0,
  22540. r, - t, 0, r, t, 0,
  22541. // (±φ, 0, ±1/φ)
  22542. - t, 0, - r, t, 0, - r,
  22543. - t, 0, r, t, 0, r
  22544. ];
  22545. const indices = [
  22546. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22547. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22548. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22549. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22550. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22551. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22552. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22553. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22554. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22555. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22556. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22557. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22558. ];
  22559. super( vertices, indices, radius, detail );
  22560. this.type = 'DodecahedronGeometry';
  22561. this.parameters = {
  22562. radius: radius,
  22563. detail: detail
  22564. };
  22565. }
  22566. static fromJSON( data ) {
  22567. return new DodecahedronGeometry( data.radius, data.detail );
  22568. }
  22569. }
  22570. const _v0 = /*@__PURE__*/ new Vector3();
  22571. const _v1$1 = /*@__PURE__*/ new Vector3();
  22572. const _normal = /*@__PURE__*/ new Vector3();
  22573. const _triangle = /*@__PURE__*/ new Triangle();
  22574. class EdgesGeometry extends BufferGeometry {
  22575. constructor( geometry = null, thresholdAngle = 1 ) {
  22576. super();
  22577. this.type = 'EdgesGeometry';
  22578. this.parameters = {
  22579. geometry: geometry,
  22580. thresholdAngle: thresholdAngle
  22581. };
  22582. if ( geometry !== null ) {
  22583. const precisionPoints = 4;
  22584. const precision = Math.pow( 10, precisionPoints );
  22585. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22586. const indexAttr = geometry.getIndex();
  22587. const positionAttr = geometry.getAttribute( 'position' );
  22588. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22589. const indexArr = [ 0, 0, 0 ];
  22590. const vertKeys = [ 'a', 'b', 'c' ];
  22591. const hashes = new Array( 3 );
  22592. const edgeData = {};
  22593. const vertices = [];
  22594. for ( let i = 0; i < indexCount; i += 3 ) {
  22595. if ( indexAttr ) {
  22596. indexArr[ 0 ] = indexAttr.getX( i );
  22597. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22598. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22599. } else {
  22600. indexArr[ 0 ] = i;
  22601. indexArr[ 1 ] = i + 1;
  22602. indexArr[ 2 ] = i + 2;
  22603. }
  22604. const { a, b, c } = _triangle;
  22605. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22606. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22607. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22608. _triangle.getNormal( _normal );
  22609. // create hashes for the edge from the vertices
  22610. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22611. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22612. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22613. // skip degenerate triangles
  22614. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22615. continue;
  22616. }
  22617. // iterate over every edge
  22618. for ( let j = 0; j < 3; j ++ ) {
  22619. // get the first and next vertex making up the edge
  22620. const jNext = ( j + 1 ) % 3;
  22621. const vecHash0 = hashes[ j ];
  22622. const vecHash1 = hashes[ jNext ];
  22623. const v0 = _triangle[ vertKeys[ j ] ];
  22624. const v1 = _triangle[ vertKeys[ jNext ] ];
  22625. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22626. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22627. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22628. // if we found a sibling edge add it into the vertex array if
  22629. // it meets the angle threshold and delete the edge from the map.
  22630. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22631. vertices.push( v0.x, v0.y, v0.z );
  22632. vertices.push( v1.x, v1.y, v1.z );
  22633. }
  22634. edgeData[ reverseHash ] = null;
  22635. } else if ( ! ( hash in edgeData ) ) {
  22636. // if we've already got an edge here then skip adding a new one
  22637. edgeData[ hash ] = {
  22638. index0: indexArr[ j ],
  22639. index1: indexArr[ jNext ],
  22640. normal: _normal.clone(),
  22641. };
  22642. }
  22643. }
  22644. }
  22645. // iterate over all remaining, unmatched edges and add them to the vertex array
  22646. for ( const key in edgeData ) {
  22647. if ( edgeData[ key ] ) {
  22648. const { index0, index1 } = edgeData[ key ];
  22649. _v0.fromBufferAttribute( positionAttr, index0 );
  22650. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22651. vertices.push( _v0.x, _v0.y, _v0.z );
  22652. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22653. }
  22654. }
  22655. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22656. }
  22657. }
  22658. copy( source ) {
  22659. super.copy( source );
  22660. this.parameters = Object.assign( {}, source.parameters );
  22661. return this;
  22662. }
  22663. }
  22664. class Shape extends Path {
  22665. constructor( points ) {
  22666. super( points );
  22667. this.uuid = generateUUID();
  22668. this.type = 'Shape';
  22669. this.holes = [];
  22670. }
  22671. getPointsHoles( divisions ) {
  22672. const holesPts = [];
  22673. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22674. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22675. }
  22676. return holesPts;
  22677. }
  22678. // get points of shape and holes (keypoints based on segments parameter)
  22679. extractPoints( divisions ) {
  22680. return {
  22681. shape: this.getPoints( divisions ),
  22682. holes: this.getPointsHoles( divisions )
  22683. };
  22684. }
  22685. copy( source ) {
  22686. super.copy( source );
  22687. this.holes = [];
  22688. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22689. const hole = source.holes[ i ];
  22690. this.holes.push( hole.clone() );
  22691. }
  22692. return this;
  22693. }
  22694. toJSON() {
  22695. const data = super.toJSON();
  22696. data.uuid = this.uuid;
  22697. data.holes = [];
  22698. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22699. const hole = this.holes[ i ];
  22700. data.holes.push( hole.toJSON() );
  22701. }
  22702. return data;
  22703. }
  22704. fromJSON( json ) {
  22705. super.fromJSON( json );
  22706. this.uuid = json.uuid;
  22707. this.holes = [];
  22708. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22709. const hole = json.holes[ i ];
  22710. this.holes.push( new Path().fromJSON( hole ) );
  22711. }
  22712. return this;
  22713. }
  22714. }
  22715. /**
  22716. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22717. */
  22718. const Earcut = {
  22719. triangulate: function ( data, holeIndices, dim = 2 ) {
  22720. const hasHoles = holeIndices && holeIndices.length;
  22721. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22722. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22723. const triangles = [];
  22724. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22725. let minX, minY, maxX, maxY, x, y, invSize;
  22726. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22727. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22728. if ( data.length > 80 * dim ) {
  22729. minX = maxX = data[ 0 ];
  22730. minY = maxY = data[ 1 ];
  22731. for ( let i = dim; i < outerLen; i += dim ) {
  22732. x = data[ i ];
  22733. y = data[ i + 1 ];
  22734. if ( x < minX ) minX = x;
  22735. if ( y < minY ) minY = y;
  22736. if ( x > maxX ) maxX = x;
  22737. if ( y > maxY ) maxY = y;
  22738. }
  22739. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22740. invSize = Math.max( maxX - minX, maxY - minY );
  22741. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22742. }
  22743. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22744. return triangles;
  22745. }
  22746. };
  22747. // create a circular doubly linked list from polygon points in the specified winding order
  22748. function linkedList( data, start, end, dim, clockwise ) {
  22749. let i, last;
  22750. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22751. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22752. } else {
  22753. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22754. }
  22755. if ( last && equals( last, last.next ) ) {
  22756. removeNode( last );
  22757. last = last.next;
  22758. }
  22759. return last;
  22760. }
  22761. // eliminate colinear or duplicate points
  22762. function filterPoints( start, end ) {
  22763. if ( ! start ) return start;
  22764. if ( ! end ) end = start;
  22765. let p = start,
  22766. again;
  22767. do {
  22768. again = false;
  22769. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22770. removeNode( p );
  22771. p = end = p.prev;
  22772. if ( p === p.next ) break;
  22773. again = true;
  22774. } else {
  22775. p = p.next;
  22776. }
  22777. } while ( again || p !== end );
  22778. return end;
  22779. }
  22780. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22781. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22782. if ( ! ear ) return;
  22783. // interlink polygon nodes in z-order
  22784. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22785. let stop = ear,
  22786. prev, next;
  22787. // iterate through ears, slicing them one by one
  22788. while ( ear.prev !== ear.next ) {
  22789. prev = ear.prev;
  22790. next = ear.next;
  22791. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22792. // cut off the triangle
  22793. triangles.push( prev.i / dim | 0 );
  22794. triangles.push( ear.i / dim | 0 );
  22795. triangles.push( next.i / dim | 0 );
  22796. removeNode( ear );
  22797. // skipping the next vertex leads to less sliver triangles
  22798. ear = next.next;
  22799. stop = next.next;
  22800. continue;
  22801. }
  22802. ear = next;
  22803. // if we looped through the whole remaining polygon and can't find any more ears
  22804. if ( ear === stop ) {
  22805. // try filtering points and slicing again
  22806. if ( ! pass ) {
  22807. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22808. // if this didn't work, try curing all small self-intersections locally
  22809. } else if ( pass === 1 ) {
  22810. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22811. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22812. // as a last resort, try splitting the remaining polygon into two
  22813. } else if ( pass === 2 ) {
  22814. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22815. }
  22816. break;
  22817. }
  22818. }
  22819. }
  22820. // check whether a polygon node forms a valid ear with adjacent nodes
  22821. function isEar( ear ) {
  22822. const a = ear.prev,
  22823. b = ear,
  22824. c = ear.next;
  22825. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22826. // now make sure we don't have other points inside the potential ear
  22827. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22828. // triangle bbox; min & max are calculated like this for speed
  22829. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22830. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22831. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22832. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22833. let p = c.next;
  22834. while ( p !== a ) {
  22835. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22836. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22837. area( p.prev, p, p.next ) >= 0 ) return false;
  22838. p = p.next;
  22839. }
  22840. return true;
  22841. }
  22842. function isEarHashed( ear, minX, minY, invSize ) {
  22843. const a = ear.prev,
  22844. b = ear,
  22845. c = ear.next;
  22846. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22847. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22848. // triangle bbox; min & max are calculated like this for speed
  22849. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22850. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22851. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22852. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22853. // z-order range for the current triangle bbox;
  22854. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22855. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22856. let p = ear.prevZ,
  22857. n = ear.nextZ;
  22858. // look for points inside the triangle in both directions
  22859. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22860. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22861. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22862. p = p.prevZ;
  22863. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22864. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22865. n = n.nextZ;
  22866. }
  22867. // look for remaining points in decreasing z-order
  22868. while ( p && p.z >= minZ ) {
  22869. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22870. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22871. p = p.prevZ;
  22872. }
  22873. // look for remaining points in increasing z-order
  22874. while ( n && n.z <= maxZ ) {
  22875. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22876. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22877. n = n.nextZ;
  22878. }
  22879. return true;
  22880. }
  22881. // go through all polygon nodes and cure small local self-intersections
  22882. function cureLocalIntersections( start, triangles, dim ) {
  22883. let p = start;
  22884. do {
  22885. const a = p.prev,
  22886. b = p.next.next;
  22887. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22888. triangles.push( a.i / dim | 0 );
  22889. triangles.push( p.i / dim | 0 );
  22890. triangles.push( b.i / dim | 0 );
  22891. // remove two nodes involved
  22892. removeNode( p );
  22893. removeNode( p.next );
  22894. p = start = b;
  22895. }
  22896. p = p.next;
  22897. } while ( p !== start );
  22898. return filterPoints( p );
  22899. }
  22900. // try splitting polygon into two and triangulate them independently
  22901. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22902. // look for a valid diagonal that divides the polygon into two
  22903. let a = start;
  22904. do {
  22905. let b = a.next.next;
  22906. while ( b !== a.prev ) {
  22907. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22908. // split the polygon in two by the diagonal
  22909. let c = splitPolygon( a, b );
  22910. // filter colinear points around the cuts
  22911. a = filterPoints( a, a.next );
  22912. c = filterPoints( c, c.next );
  22913. // run earcut on each half
  22914. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22915. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22916. return;
  22917. }
  22918. b = b.next;
  22919. }
  22920. a = a.next;
  22921. } while ( a !== start );
  22922. }
  22923. // link every hole into the outer loop, producing a single-ring polygon without holes
  22924. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22925. const queue = [];
  22926. let i, len, start, end, list;
  22927. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22928. start = holeIndices[ i ] * dim;
  22929. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  22930. list = linkedList( data, start, end, dim, false );
  22931. if ( list === list.next ) list.steiner = true;
  22932. queue.push( getLeftmost( list ) );
  22933. }
  22934. queue.sort( compareX );
  22935. // process holes from left to right
  22936. for ( i = 0; i < queue.length; i ++ ) {
  22937. outerNode = eliminateHole( queue[ i ], outerNode );
  22938. }
  22939. return outerNode;
  22940. }
  22941. function compareX( a, b ) {
  22942. return a.x - b.x;
  22943. }
  22944. // find a bridge between vertices that connects hole with an outer ring and link it
  22945. function eliminateHole( hole, outerNode ) {
  22946. const bridge = findHoleBridge( hole, outerNode );
  22947. if ( ! bridge ) {
  22948. return outerNode;
  22949. }
  22950. const bridgeReverse = splitPolygon( bridge, hole );
  22951. // filter collinear points around the cuts
  22952. filterPoints( bridgeReverse, bridgeReverse.next );
  22953. return filterPoints( bridge, bridge.next );
  22954. }
  22955. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  22956. function findHoleBridge( hole, outerNode ) {
  22957. let p = outerNode,
  22958. qx = - Infinity,
  22959. m;
  22960. const hx = hole.x, hy = hole.y;
  22961. // find a segment intersected by a ray from the hole's leftmost point to the left;
  22962. // segment's endpoint with lesser x will be potential connection point
  22963. do {
  22964. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  22965. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  22966. if ( x <= hx && x > qx ) {
  22967. qx = x;
  22968. m = p.x < p.next.x ? p : p.next;
  22969. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  22970. }
  22971. }
  22972. p = p.next;
  22973. } while ( p !== outerNode );
  22974. if ( ! m ) return null;
  22975. // look for points inside the triangle of hole point, segment intersection and endpoint;
  22976. // if there are no points found, we have a valid connection;
  22977. // otherwise choose the point of the minimum angle with the ray as connection point
  22978. const stop = m,
  22979. mx = m.x,
  22980. my = m.y;
  22981. let tanMin = Infinity, tan;
  22982. p = m;
  22983. do {
  22984. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  22985. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  22986. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  22987. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  22988. m = p;
  22989. tanMin = tan;
  22990. }
  22991. }
  22992. p = p.next;
  22993. } while ( p !== stop );
  22994. return m;
  22995. }
  22996. // whether sector in vertex m contains sector in vertex p in the same coordinates
  22997. function sectorContainsSector( m, p ) {
  22998. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  22999. }
  23000. // interlink polygon nodes in z-order
  23001. function indexCurve( start, minX, minY, invSize ) {
  23002. let p = start;
  23003. do {
  23004. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  23005. p.prevZ = p.prev;
  23006. p.nextZ = p.next;
  23007. p = p.next;
  23008. } while ( p !== start );
  23009. p.prevZ.nextZ = null;
  23010. p.prevZ = null;
  23011. sortLinked( p );
  23012. }
  23013. // Simon Tatham's linked list merge sort algorithm
  23014. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23015. function sortLinked( list ) {
  23016. let i, p, q, e, tail, numMerges, pSize, qSize,
  23017. inSize = 1;
  23018. do {
  23019. p = list;
  23020. list = null;
  23021. tail = null;
  23022. numMerges = 0;
  23023. while ( p ) {
  23024. numMerges ++;
  23025. q = p;
  23026. pSize = 0;
  23027. for ( i = 0; i < inSize; i ++ ) {
  23028. pSize ++;
  23029. q = q.nextZ;
  23030. if ( ! q ) break;
  23031. }
  23032. qSize = inSize;
  23033. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  23034. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  23035. e = p;
  23036. p = p.nextZ;
  23037. pSize --;
  23038. } else {
  23039. e = q;
  23040. q = q.nextZ;
  23041. qSize --;
  23042. }
  23043. if ( tail ) tail.nextZ = e;
  23044. else list = e;
  23045. e.prevZ = tail;
  23046. tail = e;
  23047. }
  23048. p = q;
  23049. }
  23050. tail.nextZ = null;
  23051. inSize *= 2;
  23052. } while ( numMerges > 1 );
  23053. return list;
  23054. }
  23055. // z-order of a point given coords and inverse of the longer side of data bbox
  23056. function zOrder( x, y, minX, minY, invSize ) {
  23057. // coords are transformed into non-negative 15-bit integer range
  23058. x = ( x - minX ) * invSize | 0;
  23059. y = ( y - minY ) * invSize | 0;
  23060. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  23061. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  23062. x = ( x | ( x << 2 ) ) & 0x33333333;
  23063. x = ( x | ( x << 1 ) ) & 0x55555555;
  23064. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  23065. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  23066. y = ( y | ( y << 2 ) ) & 0x33333333;
  23067. y = ( y | ( y << 1 ) ) & 0x55555555;
  23068. return x | ( y << 1 );
  23069. }
  23070. // find the leftmost node of a polygon ring
  23071. function getLeftmost( start ) {
  23072. let p = start,
  23073. leftmost = start;
  23074. do {
  23075. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  23076. p = p.next;
  23077. } while ( p !== start );
  23078. return leftmost;
  23079. }
  23080. // check if a point lies within a convex triangle
  23081. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  23082. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  23083. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  23084. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  23085. }
  23086. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23087. function isValidDiagonal( a, b ) {
  23088. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  23089. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  23090. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  23091. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  23092. }
  23093. // signed area of a triangle
  23094. function area( p, q, r ) {
  23095. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  23096. }
  23097. // check if two points are equal
  23098. function equals( p1, p2 ) {
  23099. return p1.x === p2.x && p1.y === p2.y;
  23100. }
  23101. // check if two segments intersect
  23102. function intersects( p1, q1, p2, q2 ) {
  23103. const o1 = sign( area( p1, q1, p2 ) );
  23104. const o2 = sign( area( p1, q1, q2 ) );
  23105. const o3 = sign( area( p2, q2, p1 ) );
  23106. const o4 = sign( area( p2, q2, q1 ) );
  23107. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  23108. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  23109. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  23110. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  23111. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  23112. return false;
  23113. }
  23114. // for collinear points p, q, r, check if point q lies on segment pr
  23115. function onSegment( p, q, r ) {
  23116. 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 );
  23117. }
  23118. function sign( num ) {
  23119. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  23120. }
  23121. // check if a polygon diagonal intersects any polygon segments
  23122. function intersectsPolygon( a, b ) {
  23123. let p = a;
  23124. do {
  23125. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  23126. intersects( p, p.next, a, b ) ) return true;
  23127. p = p.next;
  23128. } while ( p !== a );
  23129. return false;
  23130. }
  23131. // check if a polygon diagonal is locally inside the polygon
  23132. function locallyInside( a, b ) {
  23133. return area( a.prev, a, a.next ) < 0 ?
  23134. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  23135. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  23136. }
  23137. // check if the middle point of a polygon diagonal is inside the polygon
  23138. function middleInside( a, b ) {
  23139. let p = a,
  23140. inside = false;
  23141. const px = ( a.x + b.x ) / 2,
  23142. py = ( a.y + b.y ) / 2;
  23143. do {
  23144. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  23145. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  23146. inside = ! inside;
  23147. p = p.next;
  23148. } while ( p !== a );
  23149. return inside;
  23150. }
  23151. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  23152. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  23153. function splitPolygon( a, b ) {
  23154. const a2 = new Node( a.i, a.x, a.y ),
  23155. b2 = new Node( b.i, b.x, b.y ),
  23156. an = a.next,
  23157. bp = b.prev;
  23158. a.next = b;
  23159. b.prev = a;
  23160. a2.next = an;
  23161. an.prev = a2;
  23162. b2.next = a2;
  23163. a2.prev = b2;
  23164. bp.next = b2;
  23165. b2.prev = bp;
  23166. return b2;
  23167. }
  23168. // create a node and optionally link it with previous one (in a circular doubly linked list)
  23169. function insertNode( i, x, y, last ) {
  23170. const p = new Node( i, x, y );
  23171. if ( ! last ) {
  23172. p.prev = p;
  23173. p.next = p;
  23174. } else {
  23175. p.next = last.next;
  23176. p.prev = last;
  23177. last.next.prev = p;
  23178. last.next = p;
  23179. }
  23180. return p;
  23181. }
  23182. function removeNode( p ) {
  23183. p.next.prev = p.prev;
  23184. p.prev.next = p.next;
  23185. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  23186. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  23187. }
  23188. function Node( i, x, y ) {
  23189. // vertex index in coordinates array
  23190. this.i = i;
  23191. // vertex coordinates
  23192. this.x = x;
  23193. this.y = y;
  23194. // previous and next vertex nodes in a polygon ring
  23195. this.prev = null;
  23196. this.next = null;
  23197. // z-order curve value
  23198. this.z = 0;
  23199. // previous and next nodes in z-order
  23200. this.prevZ = null;
  23201. this.nextZ = null;
  23202. // indicates whether this is a steiner point
  23203. this.steiner = false;
  23204. }
  23205. function signedArea( data, start, end, dim ) {
  23206. let sum = 0;
  23207. for ( let i = start, j = end - dim; i < end; i += dim ) {
  23208. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  23209. j = i;
  23210. }
  23211. return sum;
  23212. }
  23213. class ShapeUtils {
  23214. // calculate area of the contour polygon
  23215. static area( contour ) {
  23216. const n = contour.length;
  23217. let a = 0.0;
  23218. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  23219. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  23220. }
  23221. return a * 0.5;
  23222. }
  23223. static isClockWise( pts ) {
  23224. return ShapeUtils.area( pts ) < 0;
  23225. }
  23226. static triangulateShape( contour, holes ) {
  23227. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  23228. const holeIndices = []; // array of hole indices
  23229. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  23230. removeDupEndPts( contour );
  23231. addContour( vertices, contour );
  23232. //
  23233. let holeIndex = contour.length;
  23234. holes.forEach( removeDupEndPts );
  23235. for ( let i = 0; i < holes.length; i ++ ) {
  23236. holeIndices.push( holeIndex );
  23237. holeIndex += holes[ i ].length;
  23238. addContour( vertices, holes[ i ] );
  23239. }
  23240. //
  23241. const triangles = Earcut.triangulate( vertices, holeIndices );
  23242. //
  23243. for ( let i = 0; i < triangles.length; i += 3 ) {
  23244. faces.push( triangles.slice( i, i + 3 ) );
  23245. }
  23246. return faces;
  23247. }
  23248. }
  23249. function removeDupEndPts( points ) {
  23250. const l = points.length;
  23251. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  23252. points.pop();
  23253. }
  23254. }
  23255. function addContour( vertices, contour ) {
  23256. for ( let i = 0; i < contour.length; i ++ ) {
  23257. vertices.push( contour[ i ].x );
  23258. vertices.push( contour[ i ].y );
  23259. }
  23260. }
  23261. /**
  23262. * Creates extruded geometry from a path shape.
  23263. *
  23264. * parameters = {
  23265. *
  23266. * curveSegments: <int>, // number of points on the curves
  23267. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  23268. * depth: <float>, // Depth to extrude the shape
  23269. *
  23270. * bevelEnabled: <bool>, // turn on bevel
  23271. * bevelThickness: <float>, // how deep into the original shape bevel goes
  23272. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  23273. * bevelOffset: <float>, // how far from shape outline does bevel start
  23274. * bevelSegments: <int>, // number of bevel layers
  23275. *
  23276. * extrudePath: <THREE.Curve> // curve to extrude shape along
  23277. *
  23278. * UVGenerator: <Object> // object that provides UV generator functions
  23279. *
  23280. * }
  23281. */
  23282. class ExtrudeGeometry extends BufferGeometry {
  23283. 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 = {} ) {
  23284. super();
  23285. this.type = 'ExtrudeGeometry';
  23286. this.parameters = {
  23287. shapes: shapes,
  23288. options: options
  23289. };
  23290. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  23291. const scope = this;
  23292. const verticesArray = [];
  23293. const uvArray = [];
  23294. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23295. const shape = shapes[ i ];
  23296. addShape( shape );
  23297. }
  23298. // build geometry
  23299. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  23300. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  23301. this.computeVertexNormals();
  23302. // functions
  23303. function addShape( shape ) {
  23304. const placeholder = [];
  23305. // options
  23306. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  23307. const steps = options.steps !== undefined ? options.steps : 1;
  23308. const depth = options.depth !== undefined ? options.depth : 1;
  23309. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  23310. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  23311. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  23312. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  23313. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  23314. const extrudePath = options.extrudePath;
  23315. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  23316. //
  23317. let extrudePts, extrudeByPath = false;
  23318. let splineTube, binormal, normal, position2;
  23319. if ( extrudePath ) {
  23320. extrudePts = extrudePath.getSpacedPoints( steps );
  23321. extrudeByPath = true;
  23322. bevelEnabled = false; // bevels not supported for path extrusion
  23323. // SETUP TNB variables
  23324. // TODO1 - have a .isClosed in spline?
  23325. splineTube = extrudePath.computeFrenetFrames( steps, false );
  23326. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  23327. binormal = new Vector3();
  23328. normal = new Vector3();
  23329. position2 = new Vector3();
  23330. }
  23331. // Safeguards if bevels are not enabled
  23332. if ( ! bevelEnabled ) {
  23333. bevelSegments = 0;
  23334. bevelThickness = 0;
  23335. bevelSize = 0;
  23336. bevelOffset = 0;
  23337. }
  23338. // Variables initialization
  23339. const shapePoints = shape.extractPoints( curveSegments );
  23340. let vertices = shapePoints.shape;
  23341. const holes = shapePoints.holes;
  23342. const reverse = ! ShapeUtils.isClockWise( vertices );
  23343. if ( reverse ) {
  23344. vertices = vertices.reverse();
  23345. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  23346. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23347. const ahole = holes[ h ];
  23348. if ( ShapeUtils.isClockWise( ahole ) ) {
  23349. holes[ h ] = ahole.reverse();
  23350. }
  23351. }
  23352. }
  23353. const faces = ShapeUtils.triangulateShape( vertices, holes );
  23354. /* Vertices */
  23355. const contour = vertices; // vertices has all points but contour has only points of circumference
  23356. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23357. const ahole = holes[ h ];
  23358. vertices = vertices.concat( ahole );
  23359. }
  23360. function scalePt2( pt, vec, size ) {
  23361. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  23362. return pt.clone().addScaledVector( vec, size );
  23363. }
  23364. const vlen = vertices.length, flen = faces.length;
  23365. // Find directions for point movement
  23366. function getBevelVec( inPt, inPrev, inNext ) {
  23367. // computes for inPt the corresponding point inPt' on a new contour
  23368. // shifted by 1 unit (length of normalized vector) to the left
  23369. // if we walk along contour clockwise, this new contour is outside the old one
  23370. //
  23371. // inPt' is the intersection of the two lines parallel to the two
  23372. // adjacent edges of inPt at a distance of 1 unit on the left side.
  23373. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  23374. // good reading for geometry algorithms (here: line-line intersection)
  23375. // http://geomalgorithms.com/a05-_intersect-1.html
  23376. const v_prev_x = inPt.x - inPrev.x,
  23377. v_prev_y = inPt.y - inPrev.y;
  23378. const v_next_x = inNext.x - inPt.x,
  23379. v_next_y = inNext.y - inPt.y;
  23380. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  23381. // check for collinear edges
  23382. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23383. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  23384. // not collinear
  23385. // length of vectors for normalizing
  23386. const v_prev_len = Math.sqrt( v_prev_lensq );
  23387. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  23388. // shift adjacent points by unit vectors to the left
  23389. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  23390. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  23391. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  23392. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  23393. // scaling factor for v_prev to intersection point
  23394. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  23395. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  23396. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23397. // vector from inPt to intersection point
  23398. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  23399. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  23400. // Don't normalize!, otherwise sharp corners become ugly
  23401. // but prevent crazy spikes
  23402. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  23403. if ( v_trans_lensq <= 2 ) {
  23404. return new Vector2( v_trans_x, v_trans_y );
  23405. } else {
  23406. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  23407. }
  23408. } else {
  23409. // handle special case of collinear edges
  23410. let direction_eq = false; // assumes: opposite
  23411. if ( v_prev_x > Number.EPSILON ) {
  23412. if ( v_next_x > Number.EPSILON ) {
  23413. direction_eq = true;
  23414. }
  23415. } else {
  23416. if ( v_prev_x < - Number.EPSILON ) {
  23417. if ( v_next_x < - Number.EPSILON ) {
  23418. direction_eq = true;
  23419. }
  23420. } else {
  23421. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  23422. direction_eq = true;
  23423. }
  23424. }
  23425. }
  23426. if ( direction_eq ) {
  23427. // console.log("Warning: lines are a straight sequence");
  23428. v_trans_x = - v_prev_y;
  23429. v_trans_y = v_prev_x;
  23430. shrink_by = Math.sqrt( v_prev_lensq );
  23431. } else {
  23432. // console.log("Warning: lines are a straight spike");
  23433. v_trans_x = v_prev_x;
  23434. v_trans_y = v_prev_y;
  23435. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  23436. }
  23437. }
  23438. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  23439. }
  23440. const contourMovements = [];
  23441. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23442. if ( j === il ) j = 0;
  23443. if ( k === il ) k = 0;
  23444. // (j)---(i)---(k)
  23445. // console.log('i,j,k', i, j , k)
  23446. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  23447. }
  23448. const holesMovements = [];
  23449. let oneHoleMovements, verticesMovements = contourMovements.concat();
  23450. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23451. const ahole = holes[ h ];
  23452. oneHoleMovements = [];
  23453. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23454. if ( j === il ) j = 0;
  23455. if ( k === il ) k = 0;
  23456. // (j)---(i)---(k)
  23457. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  23458. }
  23459. holesMovements.push( oneHoleMovements );
  23460. verticesMovements = verticesMovements.concat( oneHoleMovements );
  23461. }
  23462. // Loop bevelSegments, 1 for the front, 1 for the back
  23463. for ( let b = 0; b < bevelSegments; b ++ ) {
  23464. //for ( b = bevelSegments; b > 0; b -- ) {
  23465. const t = b / bevelSegments;
  23466. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23467. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23468. // contract shape
  23469. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23470. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23471. v( vert.x, vert.y, - z );
  23472. }
  23473. // expand holes
  23474. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23475. const ahole = holes[ h ];
  23476. oneHoleMovements = holesMovements[ h ];
  23477. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23478. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23479. v( vert.x, vert.y, - z );
  23480. }
  23481. }
  23482. }
  23483. const bs = bevelSize + bevelOffset;
  23484. // Back facing vertices
  23485. for ( let i = 0; i < vlen; i ++ ) {
  23486. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23487. if ( ! extrudeByPath ) {
  23488. v( vert.x, vert.y, 0 );
  23489. } else {
  23490. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  23491. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  23492. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  23493. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  23494. v( position2.x, position2.y, position2.z );
  23495. }
  23496. }
  23497. // Add stepped vertices...
  23498. // Including front facing vertices
  23499. for ( let s = 1; s <= steps; s ++ ) {
  23500. for ( let i = 0; i < vlen; i ++ ) {
  23501. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23502. if ( ! extrudeByPath ) {
  23503. v( vert.x, vert.y, depth / steps * s );
  23504. } else {
  23505. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  23506. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  23507. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  23508. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  23509. v( position2.x, position2.y, position2.z );
  23510. }
  23511. }
  23512. }
  23513. // Add bevel segments planes
  23514. //for ( b = 1; b <= bevelSegments; b ++ ) {
  23515. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  23516. const t = b / bevelSegments;
  23517. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23518. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23519. // contract shape
  23520. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23521. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23522. v( vert.x, vert.y, depth + z );
  23523. }
  23524. // expand holes
  23525. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23526. const ahole = holes[ h ];
  23527. oneHoleMovements = holesMovements[ h ];
  23528. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23529. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23530. if ( ! extrudeByPath ) {
  23531. v( vert.x, vert.y, depth + z );
  23532. } else {
  23533. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  23534. }
  23535. }
  23536. }
  23537. }
  23538. /* Faces */
  23539. // Top and bottom faces
  23540. buildLidFaces();
  23541. // Sides faces
  23542. buildSideFaces();
  23543. ///// Internal functions
  23544. function buildLidFaces() {
  23545. const start = verticesArray.length / 3;
  23546. if ( bevelEnabled ) {
  23547. let layer = 0; // steps + 1
  23548. let offset = vlen * layer;
  23549. // Bottom faces
  23550. for ( let i = 0; i < flen; i ++ ) {
  23551. const face = faces[ i ];
  23552. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23553. }
  23554. layer = steps + bevelSegments * 2;
  23555. offset = vlen * layer;
  23556. // Top faces
  23557. for ( let i = 0; i < flen; i ++ ) {
  23558. const face = faces[ i ];
  23559. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23560. }
  23561. } else {
  23562. // Bottom faces
  23563. for ( let i = 0; i < flen; i ++ ) {
  23564. const face = faces[ i ];
  23565. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23566. }
  23567. // Top faces
  23568. for ( let i = 0; i < flen; i ++ ) {
  23569. const face = faces[ i ];
  23570. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23571. }
  23572. }
  23573. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23574. }
  23575. // Create faces for the z-sides of the shape
  23576. function buildSideFaces() {
  23577. const start = verticesArray.length / 3;
  23578. let layeroffset = 0;
  23579. sidewalls( contour, layeroffset );
  23580. layeroffset += contour.length;
  23581. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23582. const ahole = holes[ h ];
  23583. sidewalls( ahole, layeroffset );
  23584. //, true
  23585. layeroffset += ahole.length;
  23586. }
  23587. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23588. }
  23589. function sidewalls( contour, layeroffset ) {
  23590. let i = contour.length;
  23591. while ( -- i >= 0 ) {
  23592. const j = i;
  23593. let k = i - 1;
  23594. if ( k < 0 ) k = contour.length - 1;
  23595. //console.log('b', i,j, i-1, k,vertices.length);
  23596. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23597. const slen1 = vlen * s;
  23598. const slen2 = vlen * ( s + 1 );
  23599. const a = layeroffset + j + slen1,
  23600. b = layeroffset + k + slen1,
  23601. c = layeroffset + k + slen2,
  23602. d = layeroffset + j + slen2;
  23603. f4( a, b, c, d );
  23604. }
  23605. }
  23606. }
  23607. function v( x, y, z ) {
  23608. placeholder.push( x );
  23609. placeholder.push( y );
  23610. placeholder.push( z );
  23611. }
  23612. function f3( a, b, c ) {
  23613. addVertex( a );
  23614. addVertex( b );
  23615. addVertex( c );
  23616. const nextIndex = verticesArray.length / 3;
  23617. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23618. addUV( uvs[ 0 ] );
  23619. addUV( uvs[ 1 ] );
  23620. addUV( uvs[ 2 ] );
  23621. }
  23622. function f4( a, b, c, d ) {
  23623. addVertex( a );
  23624. addVertex( b );
  23625. addVertex( d );
  23626. addVertex( b );
  23627. addVertex( c );
  23628. addVertex( d );
  23629. const nextIndex = verticesArray.length / 3;
  23630. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23631. addUV( uvs[ 0 ] );
  23632. addUV( uvs[ 1 ] );
  23633. addUV( uvs[ 3 ] );
  23634. addUV( uvs[ 1 ] );
  23635. addUV( uvs[ 2 ] );
  23636. addUV( uvs[ 3 ] );
  23637. }
  23638. function addVertex( index ) {
  23639. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23640. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23641. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23642. }
  23643. function addUV( vector2 ) {
  23644. uvArray.push( vector2.x );
  23645. uvArray.push( vector2.y );
  23646. }
  23647. }
  23648. }
  23649. copy( source ) {
  23650. super.copy( source );
  23651. this.parameters = Object.assign( {}, source.parameters );
  23652. return this;
  23653. }
  23654. toJSON() {
  23655. const data = super.toJSON();
  23656. const shapes = this.parameters.shapes;
  23657. const options = this.parameters.options;
  23658. return toJSON$1( shapes, options, data );
  23659. }
  23660. static fromJSON( data, shapes ) {
  23661. const geometryShapes = [];
  23662. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23663. const shape = shapes[ data.shapes[ j ] ];
  23664. geometryShapes.push( shape );
  23665. }
  23666. const extrudePath = data.options.extrudePath;
  23667. if ( extrudePath !== undefined ) {
  23668. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23669. }
  23670. return new ExtrudeGeometry( geometryShapes, data.options );
  23671. }
  23672. }
  23673. const WorldUVGenerator = {
  23674. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23675. const a_x = vertices[ indexA * 3 ];
  23676. const a_y = vertices[ indexA * 3 + 1 ];
  23677. const b_x = vertices[ indexB * 3 ];
  23678. const b_y = vertices[ indexB * 3 + 1 ];
  23679. const c_x = vertices[ indexC * 3 ];
  23680. const c_y = vertices[ indexC * 3 + 1 ];
  23681. return [
  23682. new Vector2( a_x, a_y ),
  23683. new Vector2( b_x, b_y ),
  23684. new Vector2( c_x, c_y )
  23685. ];
  23686. },
  23687. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23688. const a_x = vertices[ indexA * 3 ];
  23689. const a_y = vertices[ indexA * 3 + 1 ];
  23690. const a_z = vertices[ indexA * 3 + 2 ];
  23691. const b_x = vertices[ indexB * 3 ];
  23692. const b_y = vertices[ indexB * 3 + 1 ];
  23693. const b_z = vertices[ indexB * 3 + 2 ];
  23694. const c_x = vertices[ indexC * 3 ];
  23695. const c_y = vertices[ indexC * 3 + 1 ];
  23696. const c_z = vertices[ indexC * 3 + 2 ];
  23697. const d_x = vertices[ indexD * 3 ];
  23698. const d_y = vertices[ indexD * 3 + 1 ];
  23699. const d_z = vertices[ indexD * 3 + 2 ];
  23700. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23701. return [
  23702. new Vector2( a_x, 1 - a_z ),
  23703. new Vector2( b_x, 1 - b_z ),
  23704. new Vector2( c_x, 1 - c_z ),
  23705. new Vector2( d_x, 1 - d_z )
  23706. ];
  23707. } else {
  23708. return [
  23709. new Vector2( a_y, 1 - a_z ),
  23710. new Vector2( b_y, 1 - b_z ),
  23711. new Vector2( c_y, 1 - c_z ),
  23712. new Vector2( d_y, 1 - d_z )
  23713. ];
  23714. }
  23715. }
  23716. };
  23717. function toJSON$1( shapes, options, data ) {
  23718. data.shapes = [];
  23719. if ( Array.isArray( shapes ) ) {
  23720. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23721. const shape = shapes[ i ];
  23722. data.shapes.push( shape.uuid );
  23723. }
  23724. } else {
  23725. data.shapes.push( shapes.uuid );
  23726. }
  23727. data.options = Object.assign( {}, options );
  23728. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23729. return data;
  23730. }
  23731. class IcosahedronGeometry extends PolyhedronGeometry {
  23732. constructor( radius = 1, detail = 0 ) {
  23733. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23734. const vertices = [
  23735. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23736. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23737. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23738. ];
  23739. const indices = [
  23740. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23741. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23742. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23743. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23744. ];
  23745. super( vertices, indices, radius, detail );
  23746. this.type = 'IcosahedronGeometry';
  23747. this.parameters = {
  23748. radius: radius,
  23749. detail: detail
  23750. };
  23751. }
  23752. static fromJSON( data ) {
  23753. return new IcosahedronGeometry( data.radius, data.detail );
  23754. }
  23755. }
  23756. class OctahedronGeometry extends PolyhedronGeometry {
  23757. constructor( radius = 1, detail = 0 ) {
  23758. const vertices = [
  23759. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23760. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23761. ];
  23762. const indices = [
  23763. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23764. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23765. 1, 3, 4, 1, 4, 2
  23766. ];
  23767. super( vertices, indices, radius, detail );
  23768. this.type = 'OctahedronGeometry';
  23769. this.parameters = {
  23770. radius: radius,
  23771. detail: detail
  23772. };
  23773. }
  23774. static fromJSON( data ) {
  23775. return new OctahedronGeometry( data.radius, data.detail );
  23776. }
  23777. }
  23778. class RingGeometry extends BufferGeometry {
  23779. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23780. super();
  23781. this.type = 'RingGeometry';
  23782. this.parameters = {
  23783. innerRadius: innerRadius,
  23784. outerRadius: outerRadius,
  23785. thetaSegments: thetaSegments,
  23786. phiSegments: phiSegments,
  23787. thetaStart: thetaStart,
  23788. thetaLength: thetaLength
  23789. };
  23790. thetaSegments = Math.max( 3, thetaSegments );
  23791. phiSegments = Math.max( 1, phiSegments );
  23792. // buffers
  23793. const indices = [];
  23794. const vertices = [];
  23795. const normals = [];
  23796. const uvs = [];
  23797. // some helper variables
  23798. let radius = innerRadius;
  23799. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23800. const vertex = new Vector3();
  23801. const uv = new Vector2();
  23802. // generate vertices, normals and uvs
  23803. for ( let j = 0; j <= phiSegments; j ++ ) {
  23804. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23805. // values are generate from the inside of the ring to the outside
  23806. const segment = thetaStart + i / thetaSegments * thetaLength;
  23807. // vertex
  23808. vertex.x = radius * Math.cos( segment );
  23809. vertex.y = radius * Math.sin( segment );
  23810. vertices.push( vertex.x, vertex.y, vertex.z );
  23811. // normal
  23812. normals.push( 0, 0, 1 );
  23813. // uv
  23814. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23815. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23816. uvs.push( uv.x, uv.y );
  23817. }
  23818. // increase the radius for next row of vertices
  23819. radius += radiusStep;
  23820. }
  23821. // indices
  23822. for ( let j = 0; j < phiSegments; j ++ ) {
  23823. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23824. for ( let i = 0; i < thetaSegments; i ++ ) {
  23825. const segment = i + thetaSegmentLevel;
  23826. const a = segment;
  23827. const b = segment + thetaSegments + 1;
  23828. const c = segment + thetaSegments + 2;
  23829. const d = segment + 1;
  23830. // faces
  23831. indices.push( a, b, d );
  23832. indices.push( b, c, d );
  23833. }
  23834. }
  23835. // build geometry
  23836. this.setIndex( indices );
  23837. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23838. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23839. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23840. }
  23841. copy( source ) {
  23842. super.copy( source );
  23843. this.parameters = Object.assign( {}, source.parameters );
  23844. return this;
  23845. }
  23846. static fromJSON( data ) {
  23847. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23848. }
  23849. }
  23850. class ShapeGeometry extends BufferGeometry {
  23851. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23852. super();
  23853. this.type = 'ShapeGeometry';
  23854. this.parameters = {
  23855. shapes: shapes,
  23856. curveSegments: curveSegments
  23857. };
  23858. // buffers
  23859. const indices = [];
  23860. const vertices = [];
  23861. const normals = [];
  23862. const uvs = [];
  23863. // helper variables
  23864. let groupStart = 0;
  23865. let groupCount = 0;
  23866. // allow single and array values for "shapes" parameter
  23867. if ( Array.isArray( shapes ) === false ) {
  23868. addShape( shapes );
  23869. } else {
  23870. for ( let i = 0; i < shapes.length; i ++ ) {
  23871. addShape( shapes[ i ] );
  23872. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23873. groupStart += groupCount;
  23874. groupCount = 0;
  23875. }
  23876. }
  23877. // build geometry
  23878. this.setIndex( indices );
  23879. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23880. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23881. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23882. // helper functions
  23883. function addShape( shape ) {
  23884. const indexOffset = vertices.length / 3;
  23885. const points = shape.extractPoints( curveSegments );
  23886. let shapeVertices = points.shape;
  23887. const shapeHoles = points.holes;
  23888. // check direction of vertices
  23889. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23890. shapeVertices = shapeVertices.reverse();
  23891. }
  23892. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23893. const shapeHole = shapeHoles[ i ];
  23894. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23895. shapeHoles[ i ] = shapeHole.reverse();
  23896. }
  23897. }
  23898. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23899. // join vertices of inner and outer paths to a single array
  23900. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23901. const shapeHole = shapeHoles[ i ];
  23902. shapeVertices = shapeVertices.concat( shapeHole );
  23903. }
  23904. // vertices, normals, uvs
  23905. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23906. const vertex = shapeVertices[ i ];
  23907. vertices.push( vertex.x, vertex.y, 0 );
  23908. normals.push( 0, 0, 1 );
  23909. uvs.push( vertex.x, vertex.y ); // world uvs
  23910. }
  23911. // indices
  23912. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23913. const face = faces[ i ];
  23914. const a = face[ 0 ] + indexOffset;
  23915. const b = face[ 1 ] + indexOffset;
  23916. const c = face[ 2 ] + indexOffset;
  23917. indices.push( a, b, c );
  23918. groupCount += 3;
  23919. }
  23920. }
  23921. }
  23922. copy( source ) {
  23923. super.copy( source );
  23924. this.parameters = Object.assign( {}, source.parameters );
  23925. return this;
  23926. }
  23927. toJSON() {
  23928. const data = super.toJSON();
  23929. const shapes = this.parameters.shapes;
  23930. return toJSON( shapes, data );
  23931. }
  23932. static fromJSON( data, shapes ) {
  23933. const geometryShapes = [];
  23934. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23935. const shape = shapes[ data.shapes[ j ] ];
  23936. geometryShapes.push( shape );
  23937. }
  23938. return new ShapeGeometry( geometryShapes, data.curveSegments );
  23939. }
  23940. }
  23941. function toJSON( shapes, data ) {
  23942. data.shapes = [];
  23943. if ( Array.isArray( shapes ) ) {
  23944. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23945. const shape = shapes[ i ];
  23946. data.shapes.push( shape.uuid );
  23947. }
  23948. } else {
  23949. data.shapes.push( shapes.uuid );
  23950. }
  23951. return data;
  23952. }
  23953. class SphereGeometry extends BufferGeometry {
  23954. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  23955. super();
  23956. this.type = 'SphereGeometry';
  23957. this.parameters = {
  23958. radius: radius,
  23959. widthSegments: widthSegments,
  23960. heightSegments: heightSegments,
  23961. phiStart: phiStart,
  23962. phiLength: phiLength,
  23963. thetaStart: thetaStart,
  23964. thetaLength: thetaLength
  23965. };
  23966. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  23967. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  23968. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  23969. let index = 0;
  23970. const grid = [];
  23971. const vertex = new Vector3();
  23972. const normal = new Vector3();
  23973. // buffers
  23974. const indices = [];
  23975. const vertices = [];
  23976. const normals = [];
  23977. const uvs = [];
  23978. // generate vertices, normals and uvs
  23979. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  23980. const verticesRow = [];
  23981. const v = iy / heightSegments;
  23982. // special case for the poles
  23983. let uOffset = 0;
  23984. if ( iy === 0 && thetaStart === 0 ) {
  23985. uOffset = 0.5 / widthSegments;
  23986. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  23987. uOffset = - 0.5 / widthSegments;
  23988. }
  23989. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  23990. const u = ix / widthSegments;
  23991. // vertex
  23992. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23993. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  23994. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23995. vertices.push( vertex.x, vertex.y, vertex.z );
  23996. // normal
  23997. normal.copy( vertex ).normalize();
  23998. normals.push( normal.x, normal.y, normal.z );
  23999. // uv
  24000. uvs.push( u + uOffset, 1 - v );
  24001. verticesRow.push( index ++ );
  24002. }
  24003. grid.push( verticesRow );
  24004. }
  24005. // indices
  24006. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  24007. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  24008. const a = grid[ iy ][ ix + 1 ];
  24009. const b = grid[ iy ][ ix ];
  24010. const c = grid[ iy + 1 ][ ix ];
  24011. const d = grid[ iy + 1 ][ ix + 1 ];
  24012. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  24013. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  24014. }
  24015. }
  24016. // build geometry
  24017. this.setIndex( indices );
  24018. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24019. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24020. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24021. }
  24022. copy( source ) {
  24023. super.copy( source );
  24024. this.parameters = Object.assign( {}, source.parameters );
  24025. return this;
  24026. }
  24027. static fromJSON( data ) {
  24028. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  24029. }
  24030. }
  24031. class TetrahedronGeometry extends PolyhedronGeometry {
  24032. constructor( radius = 1, detail = 0 ) {
  24033. const vertices = [
  24034. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  24035. ];
  24036. const indices = [
  24037. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  24038. ];
  24039. super( vertices, indices, radius, detail );
  24040. this.type = 'TetrahedronGeometry';
  24041. this.parameters = {
  24042. radius: radius,
  24043. detail: detail
  24044. };
  24045. }
  24046. static fromJSON( data ) {
  24047. return new TetrahedronGeometry( data.radius, data.detail );
  24048. }
  24049. }
  24050. class TorusGeometry extends BufferGeometry {
  24051. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  24052. super();
  24053. this.type = 'TorusGeometry';
  24054. this.parameters = {
  24055. radius: radius,
  24056. tube: tube,
  24057. radialSegments: radialSegments,
  24058. tubularSegments: tubularSegments,
  24059. arc: arc
  24060. };
  24061. radialSegments = Math.floor( radialSegments );
  24062. tubularSegments = Math.floor( tubularSegments );
  24063. // buffers
  24064. const indices = [];
  24065. const vertices = [];
  24066. const normals = [];
  24067. const uvs = [];
  24068. // helper variables
  24069. const center = new Vector3();
  24070. const vertex = new Vector3();
  24071. const normal = new Vector3();
  24072. // generate vertices, normals and uvs
  24073. for ( let j = 0; j <= radialSegments; j ++ ) {
  24074. for ( let i = 0; i <= tubularSegments; i ++ ) {
  24075. const u = i / tubularSegments * arc;
  24076. const v = j / radialSegments * Math.PI * 2;
  24077. // vertex
  24078. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  24079. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  24080. vertex.z = tube * Math.sin( v );
  24081. vertices.push( vertex.x, vertex.y, vertex.z );
  24082. // normal
  24083. center.x = radius * Math.cos( u );
  24084. center.y = radius * Math.sin( u );
  24085. normal.subVectors( vertex, center ).normalize();
  24086. normals.push( normal.x, normal.y, normal.z );
  24087. // uv
  24088. uvs.push( i / tubularSegments );
  24089. uvs.push( j / radialSegments );
  24090. }
  24091. }
  24092. // generate indices
  24093. for ( let j = 1; j <= radialSegments; j ++ ) {
  24094. for ( let i = 1; i <= tubularSegments; i ++ ) {
  24095. // indices
  24096. const a = ( tubularSegments + 1 ) * j + i - 1;
  24097. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  24098. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  24099. const d = ( tubularSegments + 1 ) * j + i;
  24100. // faces
  24101. indices.push( a, b, d );
  24102. indices.push( b, c, d );
  24103. }
  24104. }
  24105. // build geometry
  24106. this.setIndex( indices );
  24107. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24108. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24109. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24110. }
  24111. copy( source ) {
  24112. super.copy( source );
  24113. this.parameters = Object.assign( {}, source.parameters );
  24114. return this;
  24115. }
  24116. static fromJSON( data ) {
  24117. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  24118. }
  24119. }
  24120. class TorusKnotGeometry extends BufferGeometry {
  24121. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  24122. super();
  24123. this.type = 'TorusKnotGeometry';
  24124. this.parameters = {
  24125. radius: radius,
  24126. tube: tube,
  24127. tubularSegments: tubularSegments,
  24128. radialSegments: radialSegments,
  24129. p: p,
  24130. q: q
  24131. };
  24132. tubularSegments = Math.floor( tubularSegments );
  24133. radialSegments = Math.floor( radialSegments );
  24134. // buffers
  24135. const indices = [];
  24136. const vertices = [];
  24137. const normals = [];
  24138. const uvs = [];
  24139. // helper variables
  24140. const vertex = new Vector3();
  24141. const normal = new Vector3();
  24142. const P1 = new Vector3();
  24143. const P2 = new Vector3();
  24144. const B = new Vector3();
  24145. const T = new Vector3();
  24146. const N = new Vector3();
  24147. // generate vertices, normals and uvs
  24148. for ( let i = 0; i <= tubularSegments; ++ i ) {
  24149. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  24150. const u = i / tubularSegments * p * Math.PI * 2;
  24151. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  24152. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  24153. calculatePositionOnCurve( u, p, q, radius, P1 );
  24154. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  24155. // calculate orthonormal basis
  24156. T.subVectors( P2, P1 );
  24157. N.addVectors( P2, P1 );
  24158. B.crossVectors( T, N );
  24159. N.crossVectors( B, T );
  24160. // normalize B, N. T can be ignored, we don't use it
  24161. B.normalize();
  24162. N.normalize();
  24163. for ( let j = 0; j <= radialSegments; ++ j ) {
  24164. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  24165. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  24166. const v = j / radialSegments * Math.PI * 2;
  24167. const cx = - tube * Math.cos( v );
  24168. const cy = tube * Math.sin( v );
  24169. // now calculate the final vertex position.
  24170. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  24171. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  24172. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  24173. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  24174. vertices.push( vertex.x, vertex.y, vertex.z );
  24175. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  24176. normal.subVectors( vertex, P1 ).normalize();
  24177. normals.push( normal.x, normal.y, normal.z );
  24178. // uv
  24179. uvs.push( i / tubularSegments );
  24180. uvs.push( j / radialSegments );
  24181. }
  24182. }
  24183. // generate indices
  24184. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24185. for ( let i = 1; i <= radialSegments; i ++ ) {
  24186. // indices
  24187. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24188. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24189. const c = ( radialSegments + 1 ) * j + i;
  24190. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24191. // faces
  24192. indices.push( a, b, d );
  24193. indices.push( b, c, d );
  24194. }
  24195. }
  24196. // build geometry
  24197. this.setIndex( indices );
  24198. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24199. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24200. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24201. // this function calculates the current position on the torus curve
  24202. function calculatePositionOnCurve( u, p, q, radius, position ) {
  24203. const cu = Math.cos( u );
  24204. const su = Math.sin( u );
  24205. const quOverP = q / p * u;
  24206. const cs = Math.cos( quOverP );
  24207. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  24208. position.y = radius * ( 2 + cs ) * su * 0.5;
  24209. position.z = radius * Math.sin( quOverP ) * 0.5;
  24210. }
  24211. }
  24212. copy( source ) {
  24213. super.copy( source );
  24214. this.parameters = Object.assign( {}, source.parameters );
  24215. return this;
  24216. }
  24217. static fromJSON( data ) {
  24218. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  24219. }
  24220. }
  24221. class TubeGeometry extends BufferGeometry {
  24222. 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 ) {
  24223. super();
  24224. this.type = 'TubeGeometry';
  24225. this.parameters = {
  24226. path: path,
  24227. tubularSegments: tubularSegments,
  24228. radius: radius,
  24229. radialSegments: radialSegments,
  24230. closed: closed
  24231. };
  24232. const frames = path.computeFrenetFrames( tubularSegments, closed );
  24233. // expose internals
  24234. this.tangents = frames.tangents;
  24235. this.normals = frames.normals;
  24236. this.binormals = frames.binormals;
  24237. // helper variables
  24238. const vertex = new Vector3();
  24239. const normal = new Vector3();
  24240. const uv = new Vector2();
  24241. let P = new Vector3();
  24242. // buffer
  24243. const vertices = [];
  24244. const normals = [];
  24245. const uvs = [];
  24246. const indices = [];
  24247. // create buffer data
  24248. generateBufferData();
  24249. // build geometry
  24250. this.setIndex( indices );
  24251. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24252. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24253. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24254. // functions
  24255. function generateBufferData() {
  24256. for ( let i = 0; i < tubularSegments; i ++ ) {
  24257. generateSegment( i );
  24258. }
  24259. // if the geometry is not closed, generate the last row of vertices and normals
  24260. // at the regular position on the given path
  24261. //
  24262. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  24263. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  24264. // uvs are generated in a separate function.
  24265. // this makes it easy compute correct values for closed geometries
  24266. generateUVs();
  24267. // finally create faces
  24268. generateIndices();
  24269. }
  24270. function generateSegment( i ) {
  24271. // we use getPointAt to sample evenly distributed points from the given path
  24272. P = path.getPointAt( i / tubularSegments, P );
  24273. // retrieve corresponding normal and binormal
  24274. const N = frames.normals[ i ];
  24275. const B = frames.binormals[ i ];
  24276. // generate normals and vertices for the current segment
  24277. for ( let j = 0; j <= radialSegments; j ++ ) {
  24278. const v = j / radialSegments * Math.PI * 2;
  24279. const sin = Math.sin( v );
  24280. const cos = - Math.cos( v );
  24281. // normal
  24282. normal.x = ( cos * N.x + sin * B.x );
  24283. normal.y = ( cos * N.y + sin * B.y );
  24284. normal.z = ( cos * N.z + sin * B.z );
  24285. normal.normalize();
  24286. normals.push( normal.x, normal.y, normal.z );
  24287. // vertex
  24288. vertex.x = P.x + radius * normal.x;
  24289. vertex.y = P.y + radius * normal.y;
  24290. vertex.z = P.z + radius * normal.z;
  24291. vertices.push( vertex.x, vertex.y, vertex.z );
  24292. }
  24293. }
  24294. function generateIndices() {
  24295. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24296. for ( let i = 1; i <= radialSegments; i ++ ) {
  24297. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24298. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24299. const c = ( radialSegments + 1 ) * j + i;
  24300. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24301. // faces
  24302. indices.push( a, b, d );
  24303. indices.push( b, c, d );
  24304. }
  24305. }
  24306. }
  24307. function generateUVs() {
  24308. for ( let i = 0; i <= tubularSegments; i ++ ) {
  24309. for ( let j = 0; j <= radialSegments; j ++ ) {
  24310. uv.x = i / tubularSegments;
  24311. uv.y = j / radialSegments;
  24312. uvs.push( uv.x, uv.y );
  24313. }
  24314. }
  24315. }
  24316. }
  24317. copy( source ) {
  24318. super.copy( source );
  24319. this.parameters = Object.assign( {}, source.parameters );
  24320. return this;
  24321. }
  24322. toJSON() {
  24323. const data = super.toJSON();
  24324. data.path = this.parameters.path.toJSON();
  24325. return data;
  24326. }
  24327. static fromJSON( data ) {
  24328. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24329. // User defined curves or instances of CurvePath will not be deserialized.
  24330. return new TubeGeometry(
  24331. new Curves[ data.path.type ]().fromJSON( data.path ),
  24332. data.tubularSegments,
  24333. data.radius,
  24334. data.radialSegments,
  24335. data.closed
  24336. );
  24337. }
  24338. }
  24339. class WireframeGeometry extends BufferGeometry {
  24340. constructor( geometry = null ) {
  24341. super();
  24342. this.type = 'WireframeGeometry';
  24343. this.parameters = {
  24344. geometry: geometry
  24345. };
  24346. if ( geometry !== null ) {
  24347. // buffer
  24348. const vertices = [];
  24349. const edges = new Set();
  24350. // helper variables
  24351. const start = new Vector3();
  24352. const end = new Vector3();
  24353. if ( geometry.index !== null ) {
  24354. // indexed BufferGeometry
  24355. const position = geometry.attributes.position;
  24356. const indices = geometry.index;
  24357. let groups = geometry.groups;
  24358. if ( groups.length === 0 ) {
  24359. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  24360. }
  24361. // create a data structure that contains all edges without duplicates
  24362. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  24363. const group = groups[ o ];
  24364. const groupStart = group.start;
  24365. const groupCount = group.count;
  24366. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  24367. for ( let j = 0; j < 3; j ++ ) {
  24368. const index1 = indices.getX( i + j );
  24369. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  24370. start.fromBufferAttribute( position, index1 );
  24371. end.fromBufferAttribute( position, index2 );
  24372. if ( isUniqueEdge( start, end, edges ) === true ) {
  24373. vertices.push( start.x, start.y, start.z );
  24374. vertices.push( end.x, end.y, end.z );
  24375. }
  24376. }
  24377. }
  24378. }
  24379. } else {
  24380. // non-indexed BufferGeometry
  24381. const position = geometry.attributes.position;
  24382. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  24383. for ( let j = 0; j < 3; j ++ ) {
  24384. // three edges per triangle, an edge is represented as (index1, index2)
  24385. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  24386. const index1 = 3 * i + j;
  24387. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  24388. start.fromBufferAttribute( position, index1 );
  24389. end.fromBufferAttribute( position, index2 );
  24390. if ( isUniqueEdge( start, end, edges ) === true ) {
  24391. vertices.push( start.x, start.y, start.z );
  24392. vertices.push( end.x, end.y, end.z );
  24393. }
  24394. }
  24395. }
  24396. }
  24397. // build geometry
  24398. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24399. }
  24400. }
  24401. copy( source ) {
  24402. super.copy( source );
  24403. this.parameters = Object.assign( {}, source.parameters );
  24404. return this;
  24405. }
  24406. }
  24407. function isUniqueEdge( start, end, edges ) {
  24408. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  24409. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  24410. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  24411. return false;
  24412. } else {
  24413. edges.add( hash1 );
  24414. edges.add( hash2 );
  24415. return true;
  24416. }
  24417. }
  24418. var Geometries = /*#__PURE__*/Object.freeze({
  24419. __proto__: null,
  24420. BoxGeometry: BoxGeometry,
  24421. CapsuleGeometry: CapsuleGeometry,
  24422. CircleGeometry: CircleGeometry,
  24423. ConeGeometry: ConeGeometry,
  24424. CylinderGeometry: CylinderGeometry,
  24425. DodecahedronGeometry: DodecahedronGeometry,
  24426. EdgesGeometry: EdgesGeometry,
  24427. ExtrudeGeometry: ExtrudeGeometry,
  24428. IcosahedronGeometry: IcosahedronGeometry,
  24429. LatheGeometry: LatheGeometry,
  24430. OctahedronGeometry: OctahedronGeometry,
  24431. PlaneGeometry: PlaneGeometry,
  24432. PolyhedronGeometry: PolyhedronGeometry,
  24433. RingGeometry: RingGeometry,
  24434. ShapeGeometry: ShapeGeometry,
  24435. SphereGeometry: SphereGeometry,
  24436. TetrahedronGeometry: TetrahedronGeometry,
  24437. TorusGeometry: TorusGeometry,
  24438. TorusKnotGeometry: TorusKnotGeometry,
  24439. TubeGeometry: TubeGeometry,
  24440. WireframeGeometry: WireframeGeometry
  24441. });
  24442. class ShadowMaterial extends Material {
  24443. constructor( parameters ) {
  24444. super();
  24445. this.isShadowMaterial = true;
  24446. this.type = 'ShadowMaterial';
  24447. this.color = new Color( 0x000000 );
  24448. this.transparent = true;
  24449. this.fog = true;
  24450. this.setValues( parameters );
  24451. }
  24452. copy( source ) {
  24453. super.copy( source );
  24454. this.color.copy( source.color );
  24455. this.fog = source.fog;
  24456. return this;
  24457. }
  24458. }
  24459. class RawShaderMaterial extends ShaderMaterial {
  24460. constructor( parameters ) {
  24461. super( parameters );
  24462. this.isRawShaderMaterial = true;
  24463. this.type = 'RawShaderMaterial';
  24464. }
  24465. }
  24466. class MeshStandardMaterial extends Material {
  24467. constructor( parameters ) {
  24468. super();
  24469. this.isMeshStandardMaterial = true;
  24470. this.defines = { 'STANDARD': '' };
  24471. this.type = 'MeshStandardMaterial';
  24472. this.color = new Color( 0xffffff ); // diffuse
  24473. this.roughness = 1.0;
  24474. this.metalness = 0.0;
  24475. this.map = null;
  24476. this.lightMap = null;
  24477. this.lightMapIntensity = 1.0;
  24478. this.aoMap = null;
  24479. this.aoMapIntensity = 1.0;
  24480. this.emissive = new Color( 0x000000 );
  24481. this.emissiveIntensity = 1.0;
  24482. this.emissiveMap = null;
  24483. this.bumpMap = null;
  24484. this.bumpScale = 1;
  24485. this.normalMap = null;
  24486. this.normalMapType = TangentSpaceNormalMap;
  24487. this.normalScale = new Vector2( 1, 1 );
  24488. this.displacementMap = null;
  24489. this.displacementScale = 1;
  24490. this.displacementBias = 0;
  24491. this.roughnessMap = null;
  24492. this.metalnessMap = null;
  24493. this.alphaMap = null;
  24494. this.envMap = null;
  24495. this.envMapRotation = new Euler();
  24496. this.envMapIntensity = 1.0;
  24497. this.wireframe = false;
  24498. this.wireframeLinewidth = 1;
  24499. this.wireframeLinecap = 'round';
  24500. this.wireframeLinejoin = 'round';
  24501. this.flatShading = false;
  24502. this.fog = true;
  24503. this.setValues( parameters );
  24504. }
  24505. copy( source ) {
  24506. super.copy( source );
  24507. this.defines = { 'STANDARD': '' };
  24508. this.color.copy( source.color );
  24509. this.roughness = source.roughness;
  24510. this.metalness = source.metalness;
  24511. this.map = source.map;
  24512. this.lightMap = source.lightMap;
  24513. this.lightMapIntensity = source.lightMapIntensity;
  24514. this.aoMap = source.aoMap;
  24515. this.aoMapIntensity = source.aoMapIntensity;
  24516. this.emissive.copy( source.emissive );
  24517. this.emissiveMap = source.emissiveMap;
  24518. this.emissiveIntensity = source.emissiveIntensity;
  24519. this.bumpMap = source.bumpMap;
  24520. this.bumpScale = source.bumpScale;
  24521. this.normalMap = source.normalMap;
  24522. this.normalMapType = source.normalMapType;
  24523. this.normalScale.copy( source.normalScale );
  24524. this.displacementMap = source.displacementMap;
  24525. this.displacementScale = source.displacementScale;
  24526. this.displacementBias = source.displacementBias;
  24527. this.roughnessMap = source.roughnessMap;
  24528. this.metalnessMap = source.metalnessMap;
  24529. this.alphaMap = source.alphaMap;
  24530. this.envMap = source.envMap;
  24531. this.envMapRotation.copy( source.envMapRotation );
  24532. this.envMapIntensity = source.envMapIntensity;
  24533. this.wireframe = source.wireframe;
  24534. this.wireframeLinewidth = source.wireframeLinewidth;
  24535. this.wireframeLinecap = source.wireframeLinecap;
  24536. this.wireframeLinejoin = source.wireframeLinejoin;
  24537. this.flatShading = source.flatShading;
  24538. this.fog = source.fog;
  24539. return this;
  24540. }
  24541. }
  24542. class MeshPhysicalMaterial extends MeshStandardMaterial {
  24543. constructor( parameters ) {
  24544. super();
  24545. this.isMeshPhysicalMaterial = true;
  24546. this.defines = {
  24547. 'STANDARD': '',
  24548. 'PHYSICAL': ''
  24549. };
  24550. this.type = 'MeshPhysicalMaterial';
  24551. this.anisotropyRotation = 0;
  24552. this.anisotropyMap = null;
  24553. this.clearcoatMap = null;
  24554. this.clearcoatRoughness = 0.0;
  24555. this.clearcoatRoughnessMap = null;
  24556. this.clearcoatNormalScale = new Vector2( 1, 1 );
  24557. this.clearcoatNormalMap = null;
  24558. this.ior = 1.5;
  24559. Object.defineProperty( this, 'reflectivity', {
  24560. get: function () {
  24561. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24562. },
  24563. set: function ( reflectivity ) {
  24564. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24565. }
  24566. } );
  24567. this.iridescenceMap = null;
  24568. this.iridescenceIOR = 1.3;
  24569. this.iridescenceThicknessRange = [ 100, 400 ];
  24570. this.iridescenceThicknessMap = null;
  24571. this.sheenColor = new Color( 0x000000 );
  24572. this.sheenColorMap = null;
  24573. this.sheenRoughness = 1.0;
  24574. this.sheenRoughnessMap = null;
  24575. this.transmissionMap = null;
  24576. this.thickness = 0;
  24577. this.thicknessMap = null;
  24578. this.attenuationDistance = Infinity;
  24579. this.attenuationColor = new Color( 1, 1, 1 );
  24580. this.specularIntensity = 1.0;
  24581. this.specularIntensityMap = null;
  24582. this.specularColor = new Color( 1, 1, 1 );
  24583. this.specularColorMap = null;
  24584. this._anisotropy = 0;
  24585. this._clearcoat = 0;
  24586. this._dispersion = 0;
  24587. this._iridescence = 0;
  24588. this._sheen = 0.0;
  24589. this._transmission = 0;
  24590. this.setValues( parameters );
  24591. }
  24592. get anisotropy() {
  24593. return this._anisotropy;
  24594. }
  24595. set anisotropy( value ) {
  24596. if ( this._anisotropy > 0 !== value > 0 ) {
  24597. this.version ++;
  24598. }
  24599. this._anisotropy = value;
  24600. }
  24601. get clearcoat() {
  24602. return this._clearcoat;
  24603. }
  24604. set clearcoat( value ) {
  24605. if ( this._clearcoat > 0 !== value > 0 ) {
  24606. this.version ++;
  24607. }
  24608. this._clearcoat = value;
  24609. }
  24610. get iridescence() {
  24611. return this._iridescence;
  24612. }
  24613. set iridescence( value ) {
  24614. if ( this._iridescence > 0 !== value > 0 ) {
  24615. this.version ++;
  24616. }
  24617. this._iridescence = value;
  24618. }
  24619. get dispersion() {
  24620. return this._dispersion;
  24621. }
  24622. set dispersion( value ) {
  24623. if ( this._dispersion > 0 !== value > 0 ) {
  24624. this.version ++;
  24625. }
  24626. this._dispersion = value;
  24627. }
  24628. get sheen() {
  24629. return this._sheen;
  24630. }
  24631. set sheen( value ) {
  24632. if ( this._sheen > 0 !== value > 0 ) {
  24633. this.version ++;
  24634. }
  24635. this._sheen = value;
  24636. }
  24637. get transmission() {
  24638. return this._transmission;
  24639. }
  24640. set transmission( value ) {
  24641. if ( this._transmission > 0 !== value > 0 ) {
  24642. this.version ++;
  24643. }
  24644. this._transmission = value;
  24645. }
  24646. copy( source ) {
  24647. super.copy( source );
  24648. this.defines = {
  24649. 'STANDARD': '',
  24650. 'PHYSICAL': ''
  24651. };
  24652. this.anisotropy = source.anisotropy;
  24653. this.anisotropyRotation = source.anisotropyRotation;
  24654. this.anisotropyMap = source.anisotropyMap;
  24655. this.clearcoat = source.clearcoat;
  24656. this.clearcoatMap = source.clearcoatMap;
  24657. this.clearcoatRoughness = source.clearcoatRoughness;
  24658. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24659. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24660. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24661. this.dispersion = source.dispersion;
  24662. this.ior = source.ior;
  24663. this.iridescence = source.iridescence;
  24664. this.iridescenceMap = source.iridescenceMap;
  24665. this.iridescenceIOR = source.iridescenceIOR;
  24666. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24667. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24668. this.sheen = source.sheen;
  24669. this.sheenColor.copy( source.sheenColor );
  24670. this.sheenColorMap = source.sheenColorMap;
  24671. this.sheenRoughness = source.sheenRoughness;
  24672. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24673. this.transmission = source.transmission;
  24674. this.transmissionMap = source.transmissionMap;
  24675. this.thickness = source.thickness;
  24676. this.thicknessMap = source.thicknessMap;
  24677. this.attenuationDistance = source.attenuationDistance;
  24678. this.attenuationColor.copy( source.attenuationColor );
  24679. this.specularIntensity = source.specularIntensity;
  24680. this.specularIntensityMap = source.specularIntensityMap;
  24681. this.specularColor.copy( source.specularColor );
  24682. this.specularColorMap = source.specularColorMap;
  24683. return this;
  24684. }
  24685. }
  24686. class MeshPhongMaterial extends Material {
  24687. constructor( parameters ) {
  24688. super();
  24689. this.isMeshPhongMaterial = true;
  24690. this.type = 'MeshPhongMaterial';
  24691. this.color = new Color( 0xffffff ); // diffuse
  24692. this.specular = new Color( 0x111111 );
  24693. this.shininess = 30;
  24694. this.map = null;
  24695. this.lightMap = null;
  24696. this.lightMapIntensity = 1.0;
  24697. this.aoMap = null;
  24698. this.aoMapIntensity = 1.0;
  24699. this.emissive = new Color( 0x000000 );
  24700. this.emissiveIntensity = 1.0;
  24701. this.emissiveMap = null;
  24702. this.bumpMap = null;
  24703. this.bumpScale = 1;
  24704. this.normalMap = null;
  24705. this.normalMapType = TangentSpaceNormalMap;
  24706. this.normalScale = new Vector2( 1, 1 );
  24707. this.displacementMap = null;
  24708. this.displacementScale = 1;
  24709. this.displacementBias = 0;
  24710. this.specularMap = null;
  24711. this.alphaMap = null;
  24712. this.envMap = null;
  24713. this.envMapRotation = new Euler();
  24714. this.combine = MultiplyOperation;
  24715. this.reflectivity = 1;
  24716. this.refractionRatio = 0.98;
  24717. this.wireframe = false;
  24718. this.wireframeLinewidth = 1;
  24719. this.wireframeLinecap = 'round';
  24720. this.wireframeLinejoin = 'round';
  24721. this.flatShading = false;
  24722. this.fog = true;
  24723. this.setValues( parameters );
  24724. }
  24725. copy( source ) {
  24726. super.copy( source );
  24727. this.color.copy( source.color );
  24728. this.specular.copy( source.specular );
  24729. this.shininess = source.shininess;
  24730. this.map = source.map;
  24731. this.lightMap = source.lightMap;
  24732. this.lightMapIntensity = source.lightMapIntensity;
  24733. this.aoMap = source.aoMap;
  24734. this.aoMapIntensity = source.aoMapIntensity;
  24735. this.emissive.copy( source.emissive );
  24736. this.emissiveMap = source.emissiveMap;
  24737. this.emissiveIntensity = source.emissiveIntensity;
  24738. this.bumpMap = source.bumpMap;
  24739. this.bumpScale = source.bumpScale;
  24740. this.normalMap = source.normalMap;
  24741. this.normalMapType = source.normalMapType;
  24742. this.normalScale.copy( source.normalScale );
  24743. this.displacementMap = source.displacementMap;
  24744. this.displacementScale = source.displacementScale;
  24745. this.displacementBias = source.displacementBias;
  24746. this.specularMap = source.specularMap;
  24747. this.alphaMap = source.alphaMap;
  24748. this.envMap = source.envMap;
  24749. this.envMapRotation.copy( source.envMapRotation );
  24750. this.combine = source.combine;
  24751. this.reflectivity = source.reflectivity;
  24752. this.refractionRatio = source.refractionRatio;
  24753. this.wireframe = source.wireframe;
  24754. this.wireframeLinewidth = source.wireframeLinewidth;
  24755. this.wireframeLinecap = source.wireframeLinecap;
  24756. this.wireframeLinejoin = source.wireframeLinejoin;
  24757. this.flatShading = source.flatShading;
  24758. this.fog = source.fog;
  24759. return this;
  24760. }
  24761. }
  24762. class MeshToonMaterial extends Material {
  24763. constructor( parameters ) {
  24764. super();
  24765. this.isMeshToonMaterial = true;
  24766. this.defines = { 'TOON': '' };
  24767. this.type = 'MeshToonMaterial';
  24768. this.color = new Color( 0xffffff );
  24769. this.map = null;
  24770. this.gradientMap = null;
  24771. this.lightMap = null;
  24772. this.lightMapIntensity = 1.0;
  24773. this.aoMap = null;
  24774. this.aoMapIntensity = 1.0;
  24775. this.emissive = new Color( 0x000000 );
  24776. this.emissiveIntensity = 1.0;
  24777. this.emissiveMap = null;
  24778. this.bumpMap = null;
  24779. this.bumpScale = 1;
  24780. this.normalMap = null;
  24781. this.normalMapType = TangentSpaceNormalMap;
  24782. this.normalScale = new Vector2( 1, 1 );
  24783. this.displacementMap = null;
  24784. this.displacementScale = 1;
  24785. this.displacementBias = 0;
  24786. this.alphaMap = null;
  24787. this.wireframe = false;
  24788. this.wireframeLinewidth = 1;
  24789. this.wireframeLinecap = 'round';
  24790. this.wireframeLinejoin = 'round';
  24791. this.fog = true;
  24792. this.setValues( parameters );
  24793. }
  24794. copy( source ) {
  24795. super.copy( source );
  24796. this.color.copy( source.color );
  24797. this.map = source.map;
  24798. this.gradientMap = source.gradientMap;
  24799. this.lightMap = source.lightMap;
  24800. this.lightMapIntensity = source.lightMapIntensity;
  24801. this.aoMap = source.aoMap;
  24802. this.aoMapIntensity = source.aoMapIntensity;
  24803. this.emissive.copy( source.emissive );
  24804. this.emissiveMap = source.emissiveMap;
  24805. this.emissiveIntensity = source.emissiveIntensity;
  24806. this.bumpMap = source.bumpMap;
  24807. this.bumpScale = source.bumpScale;
  24808. this.normalMap = source.normalMap;
  24809. this.normalMapType = source.normalMapType;
  24810. this.normalScale.copy( source.normalScale );
  24811. this.displacementMap = source.displacementMap;
  24812. this.displacementScale = source.displacementScale;
  24813. this.displacementBias = source.displacementBias;
  24814. this.alphaMap = source.alphaMap;
  24815. this.wireframe = source.wireframe;
  24816. this.wireframeLinewidth = source.wireframeLinewidth;
  24817. this.wireframeLinecap = source.wireframeLinecap;
  24818. this.wireframeLinejoin = source.wireframeLinejoin;
  24819. this.fog = source.fog;
  24820. return this;
  24821. }
  24822. }
  24823. class MeshNormalMaterial extends Material {
  24824. constructor( parameters ) {
  24825. super();
  24826. this.isMeshNormalMaterial = true;
  24827. this.type = 'MeshNormalMaterial';
  24828. this.bumpMap = null;
  24829. this.bumpScale = 1;
  24830. this.normalMap = null;
  24831. this.normalMapType = TangentSpaceNormalMap;
  24832. this.normalScale = new Vector2( 1, 1 );
  24833. this.displacementMap = null;
  24834. this.displacementScale = 1;
  24835. this.displacementBias = 0;
  24836. this.wireframe = false;
  24837. this.wireframeLinewidth = 1;
  24838. this.flatShading = false;
  24839. this.setValues( parameters );
  24840. }
  24841. copy( source ) {
  24842. super.copy( source );
  24843. this.bumpMap = source.bumpMap;
  24844. this.bumpScale = source.bumpScale;
  24845. this.normalMap = source.normalMap;
  24846. this.normalMapType = source.normalMapType;
  24847. this.normalScale.copy( source.normalScale );
  24848. this.displacementMap = source.displacementMap;
  24849. this.displacementScale = source.displacementScale;
  24850. this.displacementBias = source.displacementBias;
  24851. this.wireframe = source.wireframe;
  24852. this.wireframeLinewidth = source.wireframeLinewidth;
  24853. this.flatShading = source.flatShading;
  24854. return this;
  24855. }
  24856. }
  24857. class MeshLambertMaterial extends Material {
  24858. constructor( parameters ) {
  24859. super();
  24860. this.isMeshLambertMaterial = true;
  24861. this.type = 'MeshLambertMaterial';
  24862. this.color = new Color( 0xffffff ); // diffuse
  24863. this.map = null;
  24864. this.lightMap = null;
  24865. this.lightMapIntensity = 1.0;
  24866. this.aoMap = null;
  24867. this.aoMapIntensity = 1.0;
  24868. this.emissive = new Color( 0x000000 );
  24869. this.emissiveIntensity = 1.0;
  24870. this.emissiveMap = null;
  24871. this.bumpMap = null;
  24872. this.bumpScale = 1;
  24873. this.normalMap = null;
  24874. this.normalMapType = TangentSpaceNormalMap;
  24875. this.normalScale = new Vector2( 1, 1 );
  24876. this.displacementMap = null;
  24877. this.displacementScale = 1;
  24878. this.displacementBias = 0;
  24879. this.specularMap = null;
  24880. this.alphaMap = null;
  24881. this.envMap = null;
  24882. this.envMapRotation = new Euler();
  24883. this.combine = MultiplyOperation;
  24884. this.reflectivity = 1;
  24885. this.refractionRatio = 0.98;
  24886. this.wireframe = false;
  24887. this.wireframeLinewidth = 1;
  24888. this.wireframeLinecap = 'round';
  24889. this.wireframeLinejoin = 'round';
  24890. this.flatShading = false;
  24891. this.fog = true;
  24892. this.setValues( parameters );
  24893. }
  24894. copy( source ) {
  24895. super.copy( source );
  24896. this.color.copy( source.color );
  24897. this.map = source.map;
  24898. this.lightMap = source.lightMap;
  24899. this.lightMapIntensity = source.lightMapIntensity;
  24900. this.aoMap = source.aoMap;
  24901. this.aoMapIntensity = source.aoMapIntensity;
  24902. this.emissive.copy( source.emissive );
  24903. this.emissiveMap = source.emissiveMap;
  24904. this.emissiveIntensity = source.emissiveIntensity;
  24905. this.bumpMap = source.bumpMap;
  24906. this.bumpScale = source.bumpScale;
  24907. this.normalMap = source.normalMap;
  24908. this.normalMapType = source.normalMapType;
  24909. this.normalScale.copy( source.normalScale );
  24910. this.displacementMap = source.displacementMap;
  24911. this.displacementScale = source.displacementScale;
  24912. this.displacementBias = source.displacementBias;
  24913. this.specularMap = source.specularMap;
  24914. this.alphaMap = source.alphaMap;
  24915. this.envMap = source.envMap;
  24916. this.envMapRotation.copy( source.envMapRotation );
  24917. this.combine = source.combine;
  24918. this.reflectivity = source.reflectivity;
  24919. this.refractionRatio = source.refractionRatio;
  24920. this.wireframe = source.wireframe;
  24921. this.wireframeLinewidth = source.wireframeLinewidth;
  24922. this.wireframeLinecap = source.wireframeLinecap;
  24923. this.wireframeLinejoin = source.wireframeLinejoin;
  24924. this.flatShading = source.flatShading;
  24925. this.fog = source.fog;
  24926. return this;
  24927. }
  24928. }
  24929. class MeshMatcapMaterial extends Material {
  24930. constructor( parameters ) {
  24931. super();
  24932. this.isMeshMatcapMaterial = true;
  24933. this.defines = { 'MATCAP': '' };
  24934. this.type = 'MeshMatcapMaterial';
  24935. this.color = new Color( 0xffffff ); // diffuse
  24936. this.matcap = null;
  24937. this.map = null;
  24938. this.bumpMap = null;
  24939. this.bumpScale = 1;
  24940. this.normalMap = null;
  24941. this.normalMapType = TangentSpaceNormalMap;
  24942. this.normalScale = new Vector2( 1, 1 );
  24943. this.displacementMap = null;
  24944. this.displacementScale = 1;
  24945. this.displacementBias = 0;
  24946. this.alphaMap = null;
  24947. this.flatShading = false;
  24948. this.fog = true;
  24949. this.setValues( parameters );
  24950. }
  24951. copy( source ) {
  24952. super.copy( source );
  24953. this.defines = { 'MATCAP': '' };
  24954. this.color.copy( source.color );
  24955. this.matcap = source.matcap;
  24956. this.map = source.map;
  24957. this.bumpMap = source.bumpMap;
  24958. this.bumpScale = source.bumpScale;
  24959. this.normalMap = source.normalMap;
  24960. this.normalMapType = source.normalMapType;
  24961. this.normalScale.copy( source.normalScale );
  24962. this.displacementMap = source.displacementMap;
  24963. this.displacementScale = source.displacementScale;
  24964. this.displacementBias = source.displacementBias;
  24965. this.alphaMap = source.alphaMap;
  24966. this.flatShading = source.flatShading;
  24967. this.fog = source.fog;
  24968. return this;
  24969. }
  24970. }
  24971. class LineDashedMaterial extends LineBasicMaterial {
  24972. constructor( parameters ) {
  24973. super();
  24974. this.isLineDashedMaterial = true;
  24975. this.type = 'LineDashedMaterial';
  24976. this.scale = 1;
  24977. this.dashSize = 3;
  24978. this.gapSize = 1;
  24979. this.setValues( parameters );
  24980. }
  24981. copy( source ) {
  24982. super.copy( source );
  24983. this.scale = source.scale;
  24984. this.dashSize = source.dashSize;
  24985. this.gapSize = source.gapSize;
  24986. return this;
  24987. }
  24988. }
  24989. // converts an array to a specific type
  24990. function convertArray( array, type, forceClone ) {
  24991. if ( ! array || // let 'undefined' and 'null' pass
  24992. ! forceClone && array.constructor === type ) return array;
  24993. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24994. return new type( array ); // create typed array
  24995. }
  24996. return Array.prototype.slice.call( array ); // create Array
  24997. }
  24998. function isTypedArray( object ) {
  24999. return ArrayBuffer.isView( object ) &&
  25000. ! ( object instanceof DataView );
  25001. }
  25002. // returns an array by which times and values can be sorted
  25003. function getKeyframeOrder( times ) {
  25004. function compareTime( i, j ) {
  25005. return times[ i ] - times[ j ];
  25006. }
  25007. const n = times.length;
  25008. const result = new Array( n );
  25009. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  25010. result.sort( compareTime );
  25011. return result;
  25012. }
  25013. // uses the array previously returned by 'getKeyframeOrder' to sort data
  25014. function sortedArray( values, stride, order ) {
  25015. const nValues = values.length;
  25016. const result = new values.constructor( nValues );
  25017. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  25018. const srcOffset = order[ i ] * stride;
  25019. for ( let j = 0; j !== stride; ++ j ) {
  25020. result[ dstOffset ++ ] = values[ srcOffset + j ];
  25021. }
  25022. }
  25023. return result;
  25024. }
  25025. // function for parsing AOS keyframe formats
  25026. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  25027. let i = 1, key = jsonKeys[ 0 ];
  25028. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  25029. key = jsonKeys[ i ++ ];
  25030. }
  25031. if ( key === undefined ) return; // no data
  25032. let value = key[ valuePropertyName ];
  25033. if ( value === undefined ) return; // no data
  25034. if ( Array.isArray( value ) ) {
  25035. do {
  25036. value = key[ valuePropertyName ];
  25037. if ( value !== undefined ) {
  25038. times.push( key.time );
  25039. values.push.apply( values, value ); // push all elements
  25040. }
  25041. key = jsonKeys[ i ++ ];
  25042. } while ( key !== undefined );
  25043. } else if ( value.toArray !== undefined ) {
  25044. // ...assume THREE.Math-ish
  25045. do {
  25046. value = key[ valuePropertyName ];
  25047. if ( value !== undefined ) {
  25048. times.push( key.time );
  25049. value.toArray( values, values.length );
  25050. }
  25051. key = jsonKeys[ i ++ ];
  25052. } while ( key !== undefined );
  25053. } else {
  25054. // otherwise push as-is
  25055. do {
  25056. value = key[ valuePropertyName ];
  25057. if ( value !== undefined ) {
  25058. times.push( key.time );
  25059. values.push( value );
  25060. }
  25061. key = jsonKeys[ i ++ ];
  25062. } while ( key !== undefined );
  25063. }
  25064. }
  25065. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  25066. const clip = sourceClip.clone();
  25067. clip.name = name;
  25068. const tracks = [];
  25069. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  25070. const track = clip.tracks[ i ];
  25071. const valueSize = track.getValueSize();
  25072. const times = [];
  25073. const values = [];
  25074. for ( let j = 0; j < track.times.length; ++ j ) {
  25075. const frame = track.times[ j ] * fps;
  25076. if ( frame < startFrame || frame >= endFrame ) continue;
  25077. times.push( track.times[ j ] );
  25078. for ( let k = 0; k < valueSize; ++ k ) {
  25079. values.push( track.values[ j * valueSize + k ] );
  25080. }
  25081. }
  25082. if ( times.length === 0 ) continue;
  25083. track.times = convertArray( times, track.times.constructor );
  25084. track.values = convertArray( values, track.values.constructor );
  25085. tracks.push( track );
  25086. }
  25087. clip.tracks = tracks;
  25088. // find minimum .times value across all tracks in the trimmed clip
  25089. let minStartTime = Infinity;
  25090. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  25091. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  25092. minStartTime = clip.tracks[ i ].times[ 0 ];
  25093. }
  25094. }
  25095. // shift all tracks such that clip begins at t=0
  25096. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  25097. clip.tracks[ i ].shift( - 1 * minStartTime );
  25098. }
  25099. clip.resetDuration();
  25100. return clip;
  25101. }
  25102. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  25103. if ( fps <= 0 ) fps = 30;
  25104. const numTracks = referenceClip.tracks.length;
  25105. const referenceTime = referenceFrame / fps;
  25106. // Make each track's values relative to the values at the reference frame
  25107. for ( let i = 0; i < numTracks; ++ i ) {
  25108. const referenceTrack = referenceClip.tracks[ i ];
  25109. const referenceTrackType = referenceTrack.ValueTypeName;
  25110. // Skip this track if it's non-numeric
  25111. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  25112. // Find the track in the target clip whose name and type matches the reference track
  25113. const targetTrack = targetClip.tracks.find( function ( track ) {
  25114. return track.name === referenceTrack.name
  25115. && track.ValueTypeName === referenceTrackType;
  25116. } );
  25117. if ( targetTrack === undefined ) continue;
  25118. let referenceOffset = 0;
  25119. const referenceValueSize = referenceTrack.getValueSize();
  25120. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  25121. referenceOffset = referenceValueSize / 3;
  25122. }
  25123. let targetOffset = 0;
  25124. const targetValueSize = targetTrack.getValueSize();
  25125. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  25126. targetOffset = targetValueSize / 3;
  25127. }
  25128. const lastIndex = referenceTrack.times.length - 1;
  25129. let referenceValue;
  25130. // Find the value to subtract out of the track
  25131. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  25132. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  25133. const startIndex = referenceOffset;
  25134. const endIndex = referenceValueSize - referenceOffset;
  25135. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  25136. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  25137. // Reference frame is after the last keyframe, so just use the last keyframe
  25138. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  25139. const endIndex = startIndex + referenceValueSize - referenceOffset;
  25140. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  25141. } else {
  25142. // Interpolate to the reference value
  25143. const interpolant = referenceTrack.createInterpolant();
  25144. const startIndex = referenceOffset;
  25145. const endIndex = referenceValueSize - referenceOffset;
  25146. interpolant.evaluate( referenceTime );
  25147. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  25148. }
  25149. // Conjugate the quaternion
  25150. if ( referenceTrackType === 'quaternion' ) {
  25151. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  25152. referenceQuat.toArray( referenceValue );
  25153. }
  25154. // Subtract the reference value from all of the track values
  25155. const numTimes = targetTrack.times.length;
  25156. for ( let j = 0; j < numTimes; ++ j ) {
  25157. const valueStart = j * targetValueSize + targetOffset;
  25158. if ( referenceTrackType === 'quaternion' ) {
  25159. // Multiply the conjugate for quaternion track types
  25160. Quaternion.multiplyQuaternionsFlat(
  25161. targetTrack.values,
  25162. valueStart,
  25163. referenceValue,
  25164. 0,
  25165. targetTrack.values,
  25166. valueStart
  25167. );
  25168. } else {
  25169. const valueEnd = targetValueSize - targetOffset * 2;
  25170. // Subtract each value for all other numeric track types
  25171. for ( let k = 0; k < valueEnd; ++ k ) {
  25172. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  25173. }
  25174. }
  25175. }
  25176. }
  25177. targetClip.blendMode = AdditiveAnimationBlendMode;
  25178. return targetClip;
  25179. }
  25180. const AnimationUtils = {
  25181. convertArray: convertArray,
  25182. isTypedArray: isTypedArray,
  25183. getKeyframeOrder: getKeyframeOrder,
  25184. sortedArray: sortedArray,
  25185. flattenJSON: flattenJSON,
  25186. subclip: subclip,
  25187. makeClipAdditive: makeClipAdditive
  25188. };
  25189. /**
  25190. * Abstract base class of interpolants over parametric samples.
  25191. *
  25192. * The parameter domain is one dimensional, typically the time or a path
  25193. * along a curve defined by the data.
  25194. *
  25195. * The sample values can have any dimensionality and derived classes may
  25196. * apply special interpretations to the data.
  25197. *
  25198. * This class provides the interval seek in a Template Method, deferring
  25199. * the actual interpolation to derived classes.
  25200. *
  25201. * Time complexity is O(1) for linear access crossing at most two points
  25202. * and O(log N) for random access, where N is the number of positions.
  25203. *
  25204. * References:
  25205. *
  25206. * http://www.oodesign.com/template-method-pattern.html
  25207. *
  25208. */
  25209. class Interpolant {
  25210. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25211. this.parameterPositions = parameterPositions;
  25212. this._cachedIndex = 0;
  25213. this.resultBuffer = resultBuffer !== undefined ?
  25214. resultBuffer : new sampleValues.constructor( sampleSize );
  25215. this.sampleValues = sampleValues;
  25216. this.valueSize = sampleSize;
  25217. this.settings = null;
  25218. this.DefaultSettings_ = {};
  25219. }
  25220. evaluate( t ) {
  25221. const pp = this.parameterPositions;
  25222. let i1 = this._cachedIndex,
  25223. t1 = pp[ i1 ],
  25224. t0 = pp[ i1 - 1 ];
  25225. validate_interval: {
  25226. seek: {
  25227. let right;
  25228. linear_scan: {
  25229. //- See http://jsperf.com/comparison-to-undefined/3
  25230. //- slower code:
  25231. //-
  25232. //- if ( t >= t1 || t1 === undefined ) {
  25233. forward_scan: if ( ! ( t < t1 ) ) {
  25234. for ( let giveUpAt = i1 + 2; ; ) {
  25235. if ( t1 === undefined ) {
  25236. if ( t < t0 ) break forward_scan;
  25237. // after end
  25238. i1 = pp.length;
  25239. this._cachedIndex = i1;
  25240. return this.copySampleValue_( i1 - 1 );
  25241. }
  25242. if ( i1 === giveUpAt ) break; // this loop
  25243. t0 = t1;
  25244. t1 = pp[ ++ i1 ];
  25245. if ( t < t1 ) {
  25246. // we have arrived at the sought interval
  25247. break seek;
  25248. }
  25249. }
  25250. // prepare binary search on the right side of the index
  25251. right = pp.length;
  25252. break linear_scan;
  25253. }
  25254. //- slower code:
  25255. //- if ( t < t0 || t0 === undefined ) {
  25256. if ( ! ( t >= t0 ) ) {
  25257. // looping?
  25258. const t1global = pp[ 1 ];
  25259. if ( t < t1global ) {
  25260. i1 = 2; // + 1, using the scan for the details
  25261. t0 = t1global;
  25262. }
  25263. // linear reverse scan
  25264. for ( let giveUpAt = i1 - 2; ; ) {
  25265. if ( t0 === undefined ) {
  25266. // before start
  25267. this._cachedIndex = 0;
  25268. return this.copySampleValue_( 0 );
  25269. }
  25270. if ( i1 === giveUpAt ) break; // this loop
  25271. t1 = t0;
  25272. t0 = pp[ -- i1 - 1 ];
  25273. if ( t >= t0 ) {
  25274. // we have arrived at the sought interval
  25275. break seek;
  25276. }
  25277. }
  25278. // prepare binary search on the left side of the index
  25279. right = i1;
  25280. i1 = 0;
  25281. break linear_scan;
  25282. }
  25283. // the interval is valid
  25284. break validate_interval;
  25285. } // linear scan
  25286. // binary search
  25287. while ( i1 < right ) {
  25288. const mid = ( i1 + right ) >>> 1;
  25289. if ( t < pp[ mid ] ) {
  25290. right = mid;
  25291. } else {
  25292. i1 = mid + 1;
  25293. }
  25294. }
  25295. t1 = pp[ i1 ];
  25296. t0 = pp[ i1 - 1 ];
  25297. // check boundary cases, again
  25298. if ( t0 === undefined ) {
  25299. this._cachedIndex = 0;
  25300. return this.copySampleValue_( 0 );
  25301. }
  25302. if ( t1 === undefined ) {
  25303. i1 = pp.length;
  25304. this._cachedIndex = i1;
  25305. return this.copySampleValue_( i1 - 1 );
  25306. }
  25307. } // seek
  25308. this._cachedIndex = i1;
  25309. this.intervalChanged_( i1, t0, t1 );
  25310. } // validate_interval
  25311. return this.interpolate_( i1, t0, t, t1 );
  25312. }
  25313. getSettings_() {
  25314. return this.settings || this.DefaultSettings_;
  25315. }
  25316. copySampleValue_( index ) {
  25317. // copies a sample value to the result buffer
  25318. const result = this.resultBuffer,
  25319. values = this.sampleValues,
  25320. stride = this.valueSize,
  25321. offset = index * stride;
  25322. for ( let i = 0; i !== stride; ++ i ) {
  25323. result[ i ] = values[ offset + i ];
  25324. }
  25325. return result;
  25326. }
  25327. // Template methods for derived classes:
  25328. interpolate_( /* i1, t0, t, t1 */ ) {
  25329. throw new Error( 'call to abstract method' );
  25330. // implementations shall return this.resultBuffer
  25331. }
  25332. intervalChanged_( /* i1, t0, t1 */ ) {
  25333. // empty
  25334. }
  25335. }
  25336. /**
  25337. * Fast and simple cubic spline interpolant.
  25338. *
  25339. * It was derived from a Hermitian construction setting the first derivative
  25340. * at each sample position to the linear slope between neighboring positions
  25341. * over their parameter interval.
  25342. */
  25343. class CubicInterpolant extends Interpolant {
  25344. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25345. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25346. this._weightPrev = - 0;
  25347. this._offsetPrev = - 0;
  25348. this._weightNext = - 0;
  25349. this._offsetNext = - 0;
  25350. this.DefaultSettings_ = {
  25351. endingStart: ZeroCurvatureEnding,
  25352. endingEnd: ZeroCurvatureEnding
  25353. };
  25354. }
  25355. intervalChanged_( i1, t0, t1 ) {
  25356. const pp = this.parameterPositions;
  25357. let iPrev = i1 - 2,
  25358. iNext = i1 + 1,
  25359. tPrev = pp[ iPrev ],
  25360. tNext = pp[ iNext ];
  25361. if ( tPrev === undefined ) {
  25362. switch ( this.getSettings_().endingStart ) {
  25363. case ZeroSlopeEnding:
  25364. // f'(t0) = 0
  25365. iPrev = i1;
  25366. tPrev = 2 * t0 - t1;
  25367. break;
  25368. case WrapAroundEnding:
  25369. // use the other end of the curve
  25370. iPrev = pp.length - 2;
  25371. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  25372. break;
  25373. default: // ZeroCurvatureEnding
  25374. // f''(t0) = 0 a.k.a. Natural Spline
  25375. iPrev = i1;
  25376. tPrev = t1;
  25377. }
  25378. }
  25379. if ( tNext === undefined ) {
  25380. switch ( this.getSettings_().endingEnd ) {
  25381. case ZeroSlopeEnding:
  25382. // f'(tN) = 0
  25383. iNext = i1;
  25384. tNext = 2 * t1 - t0;
  25385. break;
  25386. case WrapAroundEnding:
  25387. // use the other end of the curve
  25388. iNext = 1;
  25389. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  25390. break;
  25391. default: // ZeroCurvatureEnding
  25392. // f''(tN) = 0, a.k.a. Natural Spline
  25393. iNext = i1 - 1;
  25394. tNext = t0;
  25395. }
  25396. }
  25397. const halfDt = ( t1 - t0 ) * 0.5,
  25398. stride = this.valueSize;
  25399. this._weightPrev = halfDt / ( t0 - tPrev );
  25400. this._weightNext = halfDt / ( tNext - t1 );
  25401. this._offsetPrev = iPrev * stride;
  25402. this._offsetNext = iNext * stride;
  25403. }
  25404. interpolate_( i1, t0, t, t1 ) {
  25405. const result = this.resultBuffer,
  25406. values = this.sampleValues,
  25407. stride = this.valueSize,
  25408. o1 = i1 * stride, o0 = o1 - stride,
  25409. oP = this._offsetPrev, oN = this._offsetNext,
  25410. wP = this._weightPrev, wN = this._weightNext,
  25411. p = ( t - t0 ) / ( t1 - t0 ),
  25412. pp = p * p,
  25413. ppp = pp * p;
  25414. // evaluate polynomials
  25415. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  25416. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  25417. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  25418. const sN = wN * ppp - wN * pp;
  25419. // combine data linearly
  25420. for ( let i = 0; i !== stride; ++ i ) {
  25421. result[ i ] =
  25422. sP * values[ oP + i ] +
  25423. s0 * values[ o0 + i ] +
  25424. s1 * values[ o1 + i ] +
  25425. sN * values[ oN + i ];
  25426. }
  25427. return result;
  25428. }
  25429. }
  25430. class LinearInterpolant extends Interpolant {
  25431. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25432. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25433. }
  25434. interpolate_( i1, t0, t, t1 ) {
  25435. const result = this.resultBuffer,
  25436. values = this.sampleValues,
  25437. stride = this.valueSize,
  25438. offset1 = i1 * stride,
  25439. offset0 = offset1 - stride,
  25440. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25441. weight0 = 1 - weight1;
  25442. for ( let i = 0; i !== stride; ++ i ) {
  25443. result[ i ] =
  25444. values[ offset0 + i ] * weight0 +
  25445. values[ offset1 + i ] * weight1;
  25446. }
  25447. return result;
  25448. }
  25449. }
  25450. /**
  25451. *
  25452. * Interpolant that evaluates to the sample value at the position preceding
  25453. * the parameter.
  25454. */
  25455. class DiscreteInterpolant extends Interpolant {
  25456. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25457. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25458. }
  25459. interpolate_( i1 /*, t0, t, t1 */ ) {
  25460. return this.copySampleValue_( i1 - 1 );
  25461. }
  25462. }
  25463. class KeyframeTrack {
  25464. constructor( name, times, values, interpolation ) {
  25465. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25466. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25467. this.name = name;
  25468. this.times = convertArray( times, this.TimeBufferType );
  25469. this.values = convertArray( values, this.ValueBufferType );
  25470. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25471. }
  25472. // Serialization (in static context, because of constructor invocation
  25473. // and automatic invocation of .toJSON):
  25474. static toJSON( track ) {
  25475. const trackType = track.constructor;
  25476. let json;
  25477. // derived classes can define a static toJSON method
  25478. if ( trackType.toJSON !== this.toJSON ) {
  25479. json = trackType.toJSON( track );
  25480. } else {
  25481. // by default, we assume the data can be serialized as-is
  25482. json = {
  25483. 'name': track.name,
  25484. 'times': convertArray( track.times, Array ),
  25485. 'values': convertArray( track.values, Array )
  25486. };
  25487. const interpolation = track.getInterpolation();
  25488. if ( interpolation !== track.DefaultInterpolation ) {
  25489. json.interpolation = interpolation;
  25490. }
  25491. }
  25492. json.type = track.ValueTypeName; // mandatory
  25493. return json;
  25494. }
  25495. InterpolantFactoryMethodDiscrete( result ) {
  25496. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25497. }
  25498. InterpolantFactoryMethodLinear( result ) {
  25499. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25500. }
  25501. InterpolantFactoryMethodSmooth( result ) {
  25502. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25503. }
  25504. setInterpolation( interpolation ) {
  25505. let factoryMethod;
  25506. switch ( interpolation ) {
  25507. case InterpolateDiscrete:
  25508. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25509. break;
  25510. case InterpolateLinear:
  25511. factoryMethod = this.InterpolantFactoryMethodLinear;
  25512. break;
  25513. case InterpolateSmooth:
  25514. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25515. break;
  25516. }
  25517. if ( factoryMethod === undefined ) {
  25518. const message = 'unsupported interpolation for ' +
  25519. this.ValueTypeName + ' keyframe track named ' + this.name;
  25520. if ( this.createInterpolant === undefined ) {
  25521. // fall back to default, unless the default itself is messed up
  25522. if ( interpolation !== this.DefaultInterpolation ) {
  25523. this.setInterpolation( this.DefaultInterpolation );
  25524. } else {
  25525. throw new Error( message ); // fatal, in this case
  25526. }
  25527. }
  25528. console.warn( 'THREE.KeyframeTrack:', message );
  25529. return this;
  25530. }
  25531. this.createInterpolant = factoryMethod;
  25532. return this;
  25533. }
  25534. getInterpolation() {
  25535. switch ( this.createInterpolant ) {
  25536. case this.InterpolantFactoryMethodDiscrete:
  25537. return InterpolateDiscrete;
  25538. case this.InterpolantFactoryMethodLinear:
  25539. return InterpolateLinear;
  25540. case this.InterpolantFactoryMethodSmooth:
  25541. return InterpolateSmooth;
  25542. }
  25543. }
  25544. getValueSize() {
  25545. return this.values.length / this.times.length;
  25546. }
  25547. // move all keyframes either forwards or backwards in time
  25548. shift( timeOffset ) {
  25549. if ( timeOffset !== 0.0 ) {
  25550. const times = this.times;
  25551. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25552. times[ i ] += timeOffset;
  25553. }
  25554. }
  25555. return this;
  25556. }
  25557. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25558. scale( timeScale ) {
  25559. if ( timeScale !== 1.0 ) {
  25560. const times = this.times;
  25561. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25562. times[ i ] *= timeScale;
  25563. }
  25564. }
  25565. return this;
  25566. }
  25567. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25568. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25569. trim( startTime, endTime ) {
  25570. const times = this.times,
  25571. nKeys = times.length;
  25572. let from = 0,
  25573. to = nKeys - 1;
  25574. while ( from !== nKeys && times[ from ] < startTime ) {
  25575. ++ from;
  25576. }
  25577. while ( to !== - 1 && times[ to ] > endTime ) {
  25578. -- to;
  25579. }
  25580. ++ to; // inclusive -> exclusive bound
  25581. if ( from !== 0 || to !== nKeys ) {
  25582. // empty tracks are forbidden, so keep at least one keyframe
  25583. if ( from >= to ) {
  25584. to = Math.max( to, 1 );
  25585. from = to - 1;
  25586. }
  25587. const stride = this.getValueSize();
  25588. this.times = times.slice( from, to );
  25589. this.values = this.values.slice( from * stride, to * stride );
  25590. }
  25591. return this;
  25592. }
  25593. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25594. validate() {
  25595. let valid = true;
  25596. const valueSize = this.getValueSize();
  25597. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25598. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25599. valid = false;
  25600. }
  25601. const times = this.times,
  25602. values = this.values,
  25603. nKeys = times.length;
  25604. if ( nKeys === 0 ) {
  25605. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25606. valid = false;
  25607. }
  25608. let prevTime = null;
  25609. for ( let i = 0; i !== nKeys; i ++ ) {
  25610. const currTime = times[ i ];
  25611. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25612. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25613. valid = false;
  25614. break;
  25615. }
  25616. if ( prevTime !== null && prevTime > currTime ) {
  25617. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25618. valid = false;
  25619. break;
  25620. }
  25621. prevTime = currTime;
  25622. }
  25623. if ( values !== undefined ) {
  25624. if ( isTypedArray( values ) ) {
  25625. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25626. const value = values[ i ];
  25627. if ( isNaN( value ) ) {
  25628. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25629. valid = false;
  25630. break;
  25631. }
  25632. }
  25633. }
  25634. }
  25635. return valid;
  25636. }
  25637. // removes equivalent sequential keys as common in morph target sequences
  25638. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25639. optimize() {
  25640. // times or values may be shared with other tracks, so overwriting is unsafe
  25641. const times = this.times.slice(),
  25642. values = this.values.slice(),
  25643. stride = this.getValueSize(),
  25644. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25645. lastIndex = times.length - 1;
  25646. let writeIndex = 1;
  25647. for ( let i = 1; i < lastIndex; ++ i ) {
  25648. let keep = false;
  25649. const time = times[ i ];
  25650. const timeNext = times[ i + 1 ];
  25651. // remove adjacent keyframes scheduled at the same time
  25652. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25653. if ( ! smoothInterpolation ) {
  25654. // remove unnecessary keyframes same as their neighbors
  25655. const offset = i * stride,
  25656. offsetP = offset - stride,
  25657. offsetN = offset + stride;
  25658. for ( let j = 0; j !== stride; ++ j ) {
  25659. const value = values[ offset + j ];
  25660. if ( value !== values[ offsetP + j ] ||
  25661. value !== values[ offsetN + j ] ) {
  25662. keep = true;
  25663. break;
  25664. }
  25665. }
  25666. } else {
  25667. keep = true;
  25668. }
  25669. }
  25670. // in-place compaction
  25671. if ( keep ) {
  25672. if ( i !== writeIndex ) {
  25673. times[ writeIndex ] = times[ i ];
  25674. const readOffset = i * stride,
  25675. writeOffset = writeIndex * stride;
  25676. for ( let j = 0; j !== stride; ++ j ) {
  25677. values[ writeOffset + j ] = values[ readOffset + j ];
  25678. }
  25679. }
  25680. ++ writeIndex;
  25681. }
  25682. }
  25683. // flush last keyframe (compaction looks ahead)
  25684. if ( lastIndex > 0 ) {
  25685. times[ writeIndex ] = times[ lastIndex ];
  25686. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25687. values[ writeOffset + j ] = values[ readOffset + j ];
  25688. }
  25689. ++ writeIndex;
  25690. }
  25691. if ( writeIndex !== times.length ) {
  25692. this.times = times.slice( 0, writeIndex );
  25693. this.values = values.slice( 0, writeIndex * stride );
  25694. } else {
  25695. this.times = times;
  25696. this.values = values;
  25697. }
  25698. return this;
  25699. }
  25700. clone() {
  25701. const times = this.times.slice();
  25702. const values = this.values.slice();
  25703. const TypedKeyframeTrack = this.constructor;
  25704. const track = new TypedKeyframeTrack( this.name, times, values );
  25705. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25706. track.createInterpolant = this.createInterpolant;
  25707. return track;
  25708. }
  25709. }
  25710. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25711. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25712. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25713. /**
  25714. * A Track of Boolean keyframe values.
  25715. */
  25716. class BooleanKeyframeTrack extends KeyframeTrack {
  25717. // No interpolation parameter because only InterpolateDiscrete is valid.
  25718. constructor( name, times, values ) {
  25719. super( name, times, values );
  25720. }
  25721. }
  25722. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25723. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25724. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25725. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25726. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25727. /**
  25728. * A Track of keyframe values that represent color.
  25729. */
  25730. class ColorKeyframeTrack extends KeyframeTrack {}
  25731. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25732. /**
  25733. * A Track of numeric keyframe values.
  25734. */
  25735. class NumberKeyframeTrack extends KeyframeTrack {}
  25736. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25737. /**
  25738. * Spherical linear unit quaternion interpolant.
  25739. */
  25740. class QuaternionLinearInterpolant extends Interpolant {
  25741. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25742. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25743. }
  25744. interpolate_( i1, t0, t, t1 ) {
  25745. const result = this.resultBuffer,
  25746. values = this.sampleValues,
  25747. stride = this.valueSize,
  25748. alpha = ( t - t0 ) / ( t1 - t0 );
  25749. let offset = i1 * stride;
  25750. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25751. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25752. }
  25753. return result;
  25754. }
  25755. }
  25756. /**
  25757. * A Track of quaternion keyframe values.
  25758. */
  25759. class QuaternionKeyframeTrack extends KeyframeTrack {
  25760. InterpolantFactoryMethodLinear( result ) {
  25761. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25762. }
  25763. }
  25764. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25765. // ValueBufferType is inherited
  25766. // DefaultInterpolation is inherited;
  25767. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25768. /**
  25769. * A Track that interpolates Strings
  25770. */
  25771. class StringKeyframeTrack extends KeyframeTrack {
  25772. // No interpolation parameter because only InterpolateDiscrete is valid.
  25773. constructor( name, times, values ) {
  25774. super( name, times, values );
  25775. }
  25776. }
  25777. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25778. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25779. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25780. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25781. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25782. /**
  25783. * A Track of vectored keyframe values.
  25784. */
  25785. class VectorKeyframeTrack extends KeyframeTrack {}
  25786. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25787. class AnimationClip {
  25788. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  25789. this.name = name;
  25790. this.tracks = tracks;
  25791. this.duration = duration;
  25792. this.blendMode = blendMode;
  25793. this.uuid = generateUUID();
  25794. // this means it should figure out its duration by scanning the tracks
  25795. if ( this.duration < 0 ) {
  25796. this.resetDuration();
  25797. }
  25798. }
  25799. static parse( json ) {
  25800. const tracks = [],
  25801. jsonTracks = json.tracks,
  25802. frameTime = 1.0 / ( json.fps || 1.0 );
  25803. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25804. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25805. }
  25806. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25807. clip.uuid = json.uuid;
  25808. return clip;
  25809. }
  25810. static toJSON( clip ) {
  25811. const tracks = [],
  25812. clipTracks = clip.tracks;
  25813. const json = {
  25814. 'name': clip.name,
  25815. 'duration': clip.duration,
  25816. 'tracks': tracks,
  25817. 'uuid': clip.uuid,
  25818. 'blendMode': clip.blendMode
  25819. };
  25820. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25821. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25822. }
  25823. return json;
  25824. }
  25825. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25826. const numMorphTargets = morphTargetSequence.length;
  25827. const tracks = [];
  25828. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25829. let times = [];
  25830. let values = [];
  25831. times.push(
  25832. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25833. i,
  25834. ( i + 1 ) % numMorphTargets );
  25835. values.push( 0, 1, 0 );
  25836. const order = getKeyframeOrder( times );
  25837. times = sortedArray( times, 1, order );
  25838. values = sortedArray( values, 1, order );
  25839. // if there is a key at the first frame, duplicate it as the
  25840. // last frame as well for perfect loop.
  25841. if ( ! noLoop && times[ 0 ] === 0 ) {
  25842. times.push( numMorphTargets );
  25843. values.push( values[ 0 ] );
  25844. }
  25845. tracks.push(
  25846. new NumberKeyframeTrack(
  25847. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25848. times, values
  25849. ).scale( 1.0 / fps ) );
  25850. }
  25851. return new this( name, - 1, tracks );
  25852. }
  25853. static findByName( objectOrClipArray, name ) {
  25854. let clipArray = objectOrClipArray;
  25855. if ( ! Array.isArray( objectOrClipArray ) ) {
  25856. const o = objectOrClipArray;
  25857. clipArray = o.geometry && o.geometry.animations || o.animations;
  25858. }
  25859. for ( let i = 0; i < clipArray.length; i ++ ) {
  25860. if ( clipArray[ i ].name === name ) {
  25861. return clipArray[ i ];
  25862. }
  25863. }
  25864. return null;
  25865. }
  25866. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25867. const animationToMorphTargets = {};
  25868. // tested with https://regex101.com/ on trick sequences
  25869. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25870. const pattern = /^([\w-]*?)([\d]+)$/;
  25871. // sort morph target names into animation groups based
  25872. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25873. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25874. const morphTarget = morphTargets[ i ];
  25875. const parts = morphTarget.name.match( pattern );
  25876. if ( parts && parts.length > 1 ) {
  25877. const name = parts[ 1 ];
  25878. let animationMorphTargets = animationToMorphTargets[ name ];
  25879. if ( ! animationMorphTargets ) {
  25880. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25881. }
  25882. animationMorphTargets.push( morphTarget );
  25883. }
  25884. }
  25885. const clips = [];
  25886. for ( const name in animationToMorphTargets ) {
  25887. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25888. }
  25889. return clips;
  25890. }
  25891. // parse the animation.hierarchy format
  25892. static parseAnimation( animation, bones ) {
  25893. if ( ! animation ) {
  25894. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25895. return null;
  25896. }
  25897. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25898. // only return track if there are actually keys.
  25899. if ( animationKeys.length !== 0 ) {
  25900. const times = [];
  25901. const values = [];
  25902. flattenJSON( animationKeys, times, values, propertyName );
  25903. // empty keys are filtered out, so check again
  25904. if ( times.length !== 0 ) {
  25905. destTracks.push( new trackType( trackName, times, values ) );
  25906. }
  25907. }
  25908. };
  25909. const tracks = [];
  25910. const clipName = animation.name || 'default';
  25911. const fps = animation.fps || 30;
  25912. const blendMode = animation.blendMode;
  25913. // automatic length determination in AnimationClip.
  25914. let duration = animation.length || - 1;
  25915. const hierarchyTracks = animation.hierarchy || [];
  25916. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25917. const animationKeys = hierarchyTracks[ h ].keys;
  25918. // skip empty tracks
  25919. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25920. // process morph targets
  25921. if ( animationKeys[ 0 ].morphTargets ) {
  25922. // figure out all morph targets used in this track
  25923. const morphTargetNames = {};
  25924. let k;
  25925. for ( k = 0; k < animationKeys.length; k ++ ) {
  25926. if ( animationKeys[ k ].morphTargets ) {
  25927. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25928. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25929. }
  25930. }
  25931. }
  25932. // create a track for each morph target with all zero
  25933. // morphTargetInfluences except for the keys in which
  25934. // the morphTarget is named.
  25935. for ( const morphTargetName in morphTargetNames ) {
  25936. const times = [];
  25937. const values = [];
  25938. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25939. const animationKey = animationKeys[ k ];
  25940. times.push( animationKey.time );
  25941. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25942. }
  25943. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25944. }
  25945. duration = morphTargetNames.length * fps;
  25946. } else {
  25947. // ...assume skeletal animation
  25948. const boneName = '.bones[' + bones[ h ].name + ']';
  25949. addNonemptyTrack(
  25950. VectorKeyframeTrack, boneName + '.position',
  25951. animationKeys, 'pos', tracks );
  25952. addNonemptyTrack(
  25953. QuaternionKeyframeTrack, boneName + '.quaternion',
  25954. animationKeys, 'rot', tracks );
  25955. addNonemptyTrack(
  25956. VectorKeyframeTrack, boneName + '.scale',
  25957. animationKeys, 'scl', tracks );
  25958. }
  25959. }
  25960. if ( tracks.length === 0 ) {
  25961. return null;
  25962. }
  25963. const clip = new this( clipName, duration, tracks, blendMode );
  25964. return clip;
  25965. }
  25966. resetDuration() {
  25967. const tracks = this.tracks;
  25968. let duration = 0;
  25969. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  25970. const track = this.tracks[ i ];
  25971. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25972. }
  25973. this.duration = duration;
  25974. return this;
  25975. }
  25976. trim() {
  25977. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25978. this.tracks[ i ].trim( 0, this.duration );
  25979. }
  25980. return this;
  25981. }
  25982. validate() {
  25983. let valid = true;
  25984. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25985. valid = valid && this.tracks[ i ].validate();
  25986. }
  25987. return valid;
  25988. }
  25989. optimize() {
  25990. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25991. this.tracks[ i ].optimize();
  25992. }
  25993. return this;
  25994. }
  25995. clone() {
  25996. const tracks = [];
  25997. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25998. tracks.push( this.tracks[ i ].clone() );
  25999. }
  26000. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  26001. }
  26002. toJSON() {
  26003. return this.constructor.toJSON( this );
  26004. }
  26005. }
  26006. function getTrackTypeForValueTypeName( typeName ) {
  26007. switch ( typeName.toLowerCase() ) {
  26008. case 'scalar':
  26009. case 'double':
  26010. case 'float':
  26011. case 'number':
  26012. case 'integer':
  26013. return NumberKeyframeTrack;
  26014. case 'vector':
  26015. case 'vector2':
  26016. case 'vector3':
  26017. case 'vector4':
  26018. return VectorKeyframeTrack;
  26019. case 'color':
  26020. return ColorKeyframeTrack;
  26021. case 'quaternion':
  26022. return QuaternionKeyframeTrack;
  26023. case 'bool':
  26024. case 'boolean':
  26025. return BooleanKeyframeTrack;
  26026. case 'string':
  26027. return StringKeyframeTrack;
  26028. }
  26029. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  26030. }
  26031. function parseKeyframeTrack( json ) {
  26032. if ( json.type === undefined ) {
  26033. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  26034. }
  26035. const trackType = getTrackTypeForValueTypeName( json.type );
  26036. if ( json.times === undefined ) {
  26037. const times = [], values = [];
  26038. flattenJSON( json.keys, times, values, 'value' );
  26039. json.times = times;
  26040. json.values = values;
  26041. }
  26042. // derived classes can define a static parse method
  26043. if ( trackType.parse !== undefined ) {
  26044. return trackType.parse( json );
  26045. } else {
  26046. // by default, we assume a constructor compatible with the base
  26047. return new trackType( json.name, json.times, json.values, json.interpolation );
  26048. }
  26049. }
  26050. const Cache = {
  26051. enabled: false,
  26052. files: {},
  26053. add: function ( key, file ) {
  26054. if ( this.enabled === false ) return;
  26055. // console.log( 'THREE.Cache', 'Adding key:', key );
  26056. this.files[ key ] = file;
  26057. },
  26058. get: function ( key ) {
  26059. if ( this.enabled === false ) return;
  26060. // console.log( 'THREE.Cache', 'Checking key:', key );
  26061. return this.files[ key ];
  26062. },
  26063. remove: function ( key ) {
  26064. delete this.files[ key ];
  26065. },
  26066. clear: function () {
  26067. this.files = {};
  26068. }
  26069. };
  26070. class LoadingManager {
  26071. constructor( onLoad, onProgress, onError ) {
  26072. const scope = this;
  26073. let isLoading = false;
  26074. let itemsLoaded = 0;
  26075. let itemsTotal = 0;
  26076. let urlModifier = undefined;
  26077. const handlers = [];
  26078. // Refer to #5689 for the reason why we don't set .onStart
  26079. // in the constructor
  26080. this.onStart = undefined;
  26081. this.onLoad = onLoad;
  26082. this.onProgress = onProgress;
  26083. this.onError = onError;
  26084. this.itemStart = function ( url ) {
  26085. itemsTotal ++;
  26086. if ( isLoading === false ) {
  26087. if ( scope.onStart !== undefined ) {
  26088. scope.onStart( url, itemsLoaded, itemsTotal );
  26089. }
  26090. }
  26091. isLoading = true;
  26092. };
  26093. this.itemEnd = function ( url ) {
  26094. itemsLoaded ++;
  26095. if ( scope.onProgress !== undefined ) {
  26096. scope.onProgress( url, itemsLoaded, itemsTotal );
  26097. }
  26098. if ( itemsLoaded === itemsTotal ) {
  26099. isLoading = false;
  26100. if ( scope.onLoad !== undefined ) {
  26101. scope.onLoad();
  26102. }
  26103. }
  26104. };
  26105. this.itemError = function ( url ) {
  26106. if ( scope.onError !== undefined ) {
  26107. scope.onError( url );
  26108. }
  26109. };
  26110. this.resolveURL = function ( url ) {
  26111. if ( urlModifier ) {
  26112. return urlModifier( url );
  26113. }
  26114. return url;
  26115. };
  26116. this.setURLModifier = function ( transform ) {
  26117. urlModifier = transform;
  26118. return this;
  26119. };
  26120. this.addHandler = function ( regex, loader ) {
  26121. handlers.push( regex, loader );
  26122. return this;
  26123. };
  26124. this.removeHandler = function ( regex ) {
  26125. const index = handlers.indexOf( regex );
  26126. if ( index !== - 1 ) {
  26127. handlers.splice( index, 2 );
  26128. }
  26129. return this;
  26130. };
  26131. this.getHandler = function ( file ) {
  26132. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  26133. const regex = handlers[ i ];
  26134. const loader = handlers[ i + 1 ];
  26135. if ( regex.global ) regex.lastIndex = 0; // see #17920
  26136. if ( regex.test( file ) ) {
  26137. return loader;
  26138. }
  26139. }
  26140. return null;
  26141. };
  26142. }
  26143. }
  26144. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  26145. class Loader {
  26146. constructor( manager ) {
  26147. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26148. this.crossOrigin = 'anonymous';
  26149. this.withCredentials = false;
  26150. this.path = '';
  26151. this.resourcePath = '';
  26152. this.requestHeader = {};
  26153. }
  26154. load( /* url, onLoad, onProgress, onError */ ) {}
  26155. loadAsync( url, onProgress ) {
  26156. const scope = this;
  26157. return new Promise( function ( resolve, reject ) {
  26158. scope.load( url, resolve, onProgress, reject );
  26159. } );
  26160. }
  26161. parse( /* data */ ) {}
  26162. setCrossOrigin( crossOrigin ) {
  26163. this.crossOrigin = crossOrigin;
  26164. return this;
  26165. }
  26166. setWithCredentials( value ) {
  26167. this.withCredentials = value;
  26168. return this;
  26169. }
  26170. setPath( path ) {
  26171. this.path = path;
  26172. return this;
  26173. }
  26174. setResourcePath( resourcePath ) {
  26175. this.resourcePath = resourcePath;
  26176. return this;
  26177. }
  26178. setRequestHeader( requestHeader ) {
  26179. this.requestHeader = requestHeader;
  26180. return this;
  26181. }
  26182. }
  26183. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  26184. const loading = {};
  26185. class HttpError extends Error {
  26186. constructor( message, response ) {
  26187. super( message );
  26188. this.response = response;
  26189. }
  26190. }
  26191. class FileLoader extends Loader {
  26192. constructor( manager ) {
  26193. super( manager );
  26194. }
  26195. load( url, onLoad, onProgress, onError ) {
  26196. if ( url === undefined ) url = '';
  26197. if ( this.path !== undefined ) url = this.path + url;
  26198. url = this.manager.resolveURL( url );
  26199. const cached = Cache.get( url );
  26200. if ( cached !== undefined ) {
  26201. this.manager.itemStart( url );
  26202. setTimeout( () => {
  26203. if ( onLoad ) onLoad( cached );
  26204. this.manager.itemEnd( url );
  26205. }, 0 );
  26206. return cached;
  26207. }
  26208. // Check if request is duplicate
  26209. if ( loading[ url ] !== undefined ) {
  26210. loading[ url ].push( {
  26211. onLoad: onLoad,
  26212. onProgress: onProgress,
  26213. onError: onError
  26214. } );
  26215. return;
  26216. }
  26217. // Initialise array for duplicate requests
  26218. loading[ url ] = [];
  26219. loading[ url ].push( {
  26220. onLoad: onLoad,
  26221. onProgress: onProgress,
  26222. onError: onError,
  26223. } );
  26224. // create request
  26225. const req = new Request( url, {
  26226. headers: new Headers( this.requestHeader ),
  26227. credentials: this.withCredentials ? 'include' : 'same-origin',
  26228. // An abort controller could be added within a future PR
  26229. } );
  26230. // record states ( avoid data race )
  26231. const mimeType = this.mimeType;
  26232. const responseType = this.responseType;
  26233. // start the fetch
  26234. fetch( req )
  26235. .then( response => {
  26236. if ( response.status === 200 || response.status === 0 ) {
  26237. // Some browsers return HTTP Status 0 when using non-http protocol
  26238. // e.g. 'file://' or 'data://'. Handle as success.
  26239. if ( response.status === 0 ) {
  26240. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  26241. }
  26242. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  26243. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  26244. return response;
  26245. }
  26246. const callbacks = loading[ url ];
  26247. const reader = response.body.getReader();
  26248. // Nginx needs X-File-Size check
  26249. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  26250. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  26251. const total = contentLength ? parseInt( contentLength ) : 0;
  26252. const lengthComputable = total !== 0;
  26253. let loaded = 0;
  26254. // periodically read data into the new stream tracking while download progress
  26255. const stream = new ReadableStream( {
  26256. start( controller ) {
  26257. readData();
  26258. function readData() {
  26259. reader.read().then( ( { done, value } ) => {
  26260. if ( done ) {
  26261. controller.close();
  26262. } else {
  26263. loaded += value.byteLength;
  26264. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  26265. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26266. const callback = callbacks[ i ];
  26267. if ( callback.onProgress ) callback.onProgress( event );
  26268. }
  26269. controller.enqueue( value );
  26270. readData();
  26271. }
  26272. }, ( e ) => {
  26273. controller.error( e );
  26274. } );
  26275. }
  26276. }
  26277. } );
  26278. return new Response( stream );
  26279. } else {
  26280. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  26281. }
  26282. } )
  26283. .then( response => {
  26284. switch ( responseType ) {
  26285. case 'arraybuffer':
  26286. return response.arrayBuffer();
  26287. case 'blob':
  26288. return response.blob();
  26289. case 'document':
  26290. return response.text()
  26291. .then( text => {
  26292. const parser = new DOMParser();
  26293. return parser.parseFromString( text, mimeType );
  26294. } );
  26295. case 'json':
  26296. return response.json();
  26297. default:
  26298. if ( mimeType === undefined ) {
  26299. return response.text();
  26300. } else {
  26301. // sniff encoding
  26302. const re = /charset="?([^;"\s]*)"?/i;
  26303. const exec = re.exec( mimeType );
  26304. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  26305. const decoder = new TextDecoder( label );
  26306. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  26307. }
  26308. }
  26309. } )
  26310. .then( data => {
  26311. // Add to cache only on HTTP success, so that we do not cache
  26312. // error response bodies as proper responses to requests.
  26313. Cache.add( url, data );
  26314. const callbacks = loading[ url ];
  26315. delete loading[ url ];
  26316. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26317. const callback = callbacks[ i ];
  26318. if ( callback.onLoad ) callback.onLoad( data );
  26319. }
  26320. } )
  26321. .catch( err => {
  26322. // Abort errors and other errors are handled the same
  26323. const callbacks = loading[ url ];
  26324. if ( callbacks === undefined ) {
  26325. // When onLoad was called and url was deleted in `loading`
  26326. this.manager.itemError( url );
  26327. throw err;
  26328. }
  26329. delete loading[ url ];
  26330. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26331. const callback = callbacks[ i ];
  26332. if ( callback.onError ) callback.onError( err );
  26333. }
  26334. this.manager.itemError( url );
  26335. } )
  26336. .finally( () => {
  26337. this.manager.itemEnd( url );
  26338. } );
  26339. this.manager.itemStart( url );
  26340. }
  26341. setResponseType( value ) {
  26342. this.responseType = value;
  26343. return this;
  26344. }
  26345. setMimeType( value ) {
  26346. this.mimeType = value;
  26347. return this;
  26348. }
  26349. }
  26350. class AnimationLoader extends Loader {
  26351. constructor( manager ) {
  26352. super( manager );
  26353. }
  26354. load( url, onLoad, onProgress, onError ) {
  26355. const scope = this;
  26356. const loader = new FileLoader( this.manager );
  26357. loader.setPath( this.path );
  26358. loader.setRequestHeader( this.requestHeader );
  26359. loader.setWithCredentials( this.withCredentials );
  26360. loader.load( url, function ( text ) {
  26361. try {
  26362. onLoad( scope.parse( JSON.parse( text ) ) );
  26363. } catch ( e ) {
  26364. if ( onError ) {
  26365. onError( e );
  26366. } else {
  26367. console.error( e );
  26368. }
  26369. scope.manager.itemError( url );
  26370. }
  26371. }, onProgress, onError );
  26372. }
  26373. parse( json ) {
  26374. const animations = [];
  26375. for ( let i = 0; i < json.length; i ++ ) {
  26376. const clip = AnimationClip.parse( json[ i ] );
  26377. animations.push( clip );
  26378. }
  26379. return animations;
  26380. }
  26381. }
  26382. /**
  26383. * Abstract Base class to block based textures loader (dds, pvr, ...)
  26384. *
  26385. * Sub classes have to implement the parse() method which will be used in load().
  26386. */
  26387. class CompressedTextureLoader extends Loader {
  26388. constructor( manager ) {
  26389. super( manager );
  26390. }
  26391. load( url, onLoad, onProgress, onError ) {
  26392. const scope = this;
  26393. const images = [];
  26394. const texture = new CompressedTexture();
  26395. const loader = new FileLoader( this.manager );
  26396. loader.setPath( this.path );
  26397. loader.setResponseType( 'arraybuffer' );
  26398. loader.setRequestHeader( this.requestHeader );
  26399. loader.setWithCredentials( scope.withCredentials );
  26400. let loaded = 0;
  26401. function loadTexture( i ) {
  26402. loader.load( url[ i ], function ( buffer ) {
  26403. const texDatas = scope.parse( buffer, true );
  26404. images[ i ] = {
  26405. width: texDatas.width,
  26406. height: texDatas.height,
  26407. format: texDatas.format,
  26408. mipmaps: texDatas.mipmaps
  26409. };
  26410. loaded += 1;
  26411. if ( loaded === 6 ) {
  26412. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  26413. texture.image = images;
  26414. texture.format = texDatas.format;
  26415. texture.needsUpdate = true;
  26416. if ( onLoad ) onLoad( texture );
  26417. }
  26418. }, onProgress, onError );
  26419. }
  26420. if ( Array.isArray( url ) ) {
  26421. for ( let i = 0, il = url.length; i < il; ++ i ) {
  26422. loadTexture( i );
  26423. }
  26424. } else {
  26425. // compressed cubemap texture stored in a single DDS file
  26426. loader.load( url, function ( buffer ) {
  26427. const texDatas = scope.parse( buffer, true );
  26428. if ( texDatas.isCubemap ) {
  26429. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  26430. for ( let f = 0; f < faces; f ++ ) {
  26431. images[ f ] = { mipmaps: [] };
  26432. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  26433. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  26434. images[ f ].format = texDatas.format;
  26435. images[ f ].width = texDatas.width;
  26436. images[ f ].height = texDatas.height;
  26437. }
  26438. }
  26439. texture.image = images;
  26440. } else {
  26441. texture.image.width = texDatas.width;
  26442. texture.image.height = texDatas.height;
  26443. texture.mipmaps = texDatas.mipmaps;
  26444. }
  26445. if ( texDatas.mipmapCount === 1 ) {
  26446. texture.minFilter = LinearFilter;
  26447. }
  26448. texture.format = texDatas.format;
  26449. texture.needsUpdate = true;
  26450. if ( onLoad ) onLoad( texture );
  26451. }, onProgress, onError );
  26452. }
  26453. return texture;
  26454. }
  26455. }
  26456. class ImageLoader extends Loader {
  26457. constructor( manager ) {
  26458. super( manager );
  26459. }
  26460. load( url, onLoad, onProgress, onError ) {
  26461. if ( this.path !== undefined ) url = this.path + url;
  26462. url = this.manager.resolveURL( url );
  26463. const scope = this;
  26464. const cached = Cache.get( url );
  26465. if ( cached !== undefined ) {
  26466. scope.manager.itemStart( url );
  26467. setTimeout( function () {
  26468. if ( onLoad ) onLoad( cached );
  26469. scope.manager.itemEnd( url );
  26470. }, 0 );
  26471. return cached;
  26472. }
  26473. const image = createElementNS( 'img' );
  26474. function onImageLoad() {
  26475. removeEventListeners();
  26476. Cache.add( url, this );
  26477. if ( onLoad ) onLoad( this );
  26478. scope.manager.itemEnd( url );
  26479. }
  26480. function onImageError( event ) {
  26481. removeEventListeners();
  26482. if ( onError ) onError( event );
  26483. scope.manager.itemError( url );
  26484. scope.manager.itemEnd( url );
  26485. }
  26486. function removeEventListeners() {
  26487. image.removeEventListener( 'load', onImageLoad, false );
  26488. image.removeEventListener( 'error', onImageError, false );
  26489. }
  26490. image.addEventListener( 'load', onImageLoad, false );
  26491. image.addEventListener( 'error', onImageError, false );
  26492. if ( url.slice( 0, 5 ) !== 'data:' ) {
  26493. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  26494. }
  26495. scope.manager.itemStart( url );
  26496. image.src = url;
  26497. return image;
  26498. }
  26499. }
  26500. class CubeTextureLoader extends Loader {
  26501. constructor( manager ) {
  26502. super( manager );
  26503. }
  26504. load( urls, onLoad, onProgress, onError ) {
  26505. const texture = new CubeTexture();
  26506. texture.colorSpace = SRGBColorSpace;
  26507. const loader = new ImageLoader( this.manager );
  26508. loader.setCrossOrigin( this.crossOrigin );
  26509. loader.setPath( this.path );
  26510. let loaded = 0;
  26511. function loadTexture( i ) {
  26512. loader.load( urls[ i ], function ( image ) {
  26513. texture.images[ i ] = image;
  26514. loaded ++;
  26515. if ( loaded === 6 ) {
  26516. texture.needsUpdate = true;
  26517. if ( onLoad ) onLoad( texture );
  26518. }
  26519. }, undefined, onError );
  26520. }
  26521. for ( let i = 0; i < urls.length; ++ i ) {
  26522. loadTexture( i );
  26523. }
  26524. return texture;
  26525. }
  26526. }
  26527. /**
  26528. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  26529. *
  26530. * Sub classes have to implement the parse() method which will be used in load().
  26531. */
  26532. class DataTextureLoader extends Loader {
  26533. constructor( manager ) {
  26534. super( manager );
  26535. }
  26536. load( url, onLoad, onProgress, onError ) {
  26537. const scope = this;
  26538. const texture = new DataTexture();
  26539. const loader = new FileLoader( this.manager );
  26540. loader.setResponseType( 'arraybuffer' );
  26541. loader.setRequestHeader( this.requestHeader );
  26542. loader.setPath( this.path );
  26543. loader.setWithCredentials( scope.withCredentials );
  26544. loader.load( url, function ( buffer ) {
  26545. let texData;
  26546. try {
  26547. texData = scope.parse( buffer );
  26548. } catch ( error ) {
  26549. if ( onError !== undefined ) {
  26550. onError( error );
  26551. } else {
  26552. console.error( error );
  26553. return;
  26554. }
  26555. }
  26556. if ( texData.image !== undefined ) {
  26557. texture.image = texData.image;
  26558. } else if ( texData.data !== undefined ) {
  26559. texture.image.width = texData.width;
  26560. texture.image.height = texData.height;
  26561. texture.image.data = texData.data;
  26562. }
  26563. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26564. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26565. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26566. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  26567. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26568. if ( texData.colorSpace !== undefined ) {
  26569. texture.colorSpace = texData.colorSpace;
  26570. }
  26571. if ( texData.flipY !== undefined ) {
  26572. texture.flipY = texData.flipY;
  26573. }
  26574. if ( texData.format !== undefined ) {
  26575. texture.format = texData.format;
  26576. }
  26577. if ( texData.type !== undefined ) {
  26578. texture.type = texData.type;
  26579. }
  26580. if ( texData.mipmaps !== undefined ) {
  26581. texture.mipmaps = texData.mipmaps;
  26582. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26583. }
  26584. if ( texData.mipmapCount === 1 ) {
  26585. texture.minFilter = LinearFilter;
  26586. }
  26587. if ( texData.generateMipmaps !== undefined ) {
  26588. texture.generateMipmaps = texData.generateMipmaps;
  26589. }
  26590. texture.needsUpdate = true;
  26591. if ( onLoad ) onLoad( texture, texData );
  26592. }, onProgress, onError );
  26593. return texture;
  26594. }
  26595. }
  26596. class TextureLoader extends Loader {
  26597. constructor( manager ) {
  26598. super( manager );
  26599. }
  26600. load( url, onLoad, onProgress, onError ) {
  26601. const texture = new Texture();
  26602. const loader = new ImageLoader( this.manager );
  26603. loader.setCrossOrigin( this.crossOrigin );
  26604. loader.setPath( this.path );
  26605. loader.load( url, function ( image ) {
  26606. texture.image = image;
  26607. texture.needsUpdate = true;
  26608. if ( onLoad !== undefined ) {
  26609. onLoad( texture );
  26610. }
  26611. }, onProgress, onError );
  26612. return texture;
  26613. }
  26614. }
  26615. class Light extends Object3D {
  26616. constructor( color, intensity = 1 ) {
  26617. super();
  26618. this.isLight = true;
  26619. this.type = 'Light';
  26620. this.color = new Color( color );
  26621. this.intensity = intensity;
  26622. }
  26623. dispose() {
  26624. // Empty here in base class; some subclasses override.
  26625. }
  26626. copy( source, recursive ) {
  26627. super.copy( source, recursive );
  26628. this.color.copy( source.color );
  26629. this.intensity = source.intensity;
  26630. return this;
  26631. }
  26632. toJSON( meta ) {
  26633. const data = super.toJSON( meta );
  26634. data.object.color = this.color.getHex();
  26635. data.object.intensity = this.intensity;
  26636. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26637. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26638. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26639. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26640. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26641. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26642. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  26643. return data;
  26644. }
  26645. }
  26646. class HemisphereLight extends Light {
  26647. constructor( skyColor, groundColor, intensity ) {
  26648. super( skyColor, intensity );
  26649. this.isHemisphereLight = true;
  26650. this.type = 'HemisphereLight';
  26651. this.position.copy( Object3D.DEFAULT_UP );
  26652. this.updateMatrix();
  26653. this.groundColor = new Color( groundColor );
  26654. }
  26655. copy( source, recursive ) {
  26656. super.copy( source, recursive );
  26657. this.groundColor.copy( source.groundColor );
  26658. return this;
  26659. }
  26660. }
  26661. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26662. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26663. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26664. class LightShadow {
  26665. constructor( camera ) {
  26666. this.camera = camera;
  26667. this.intensity = 1;
  26668. this.bias = 0;
  26669. this.normalBias = 0;
  26670. this.radius = 1;
  26671. this.blurSamples = 8;
  26672. this.mapSize = new Vector2( 512, 512 );
  26673. this.map = null;
  26674. this.mapPass = null;
  26675. this.matrix = new Matrix4();
  26676. this.autoUpdate = true;
  26677. this.needsUpdate = false;
  26678. this._frustum = new Frustum();
  26679. this._frameExtents = new Vector2( 1, 1 );
  26680. this._viewportCount = 1;
  26681. this._viewports = [
  26682. new Vector4( 0, 0, 1, 1 )
  26683. ];
  26684. }
  26685. getViewportCount() {
  26686. return this._viewportCount;
  26687. }
  26688. getFrustum() {
  26689. return this._frustum;
  26690. }
  26691. updateMatrices( light ) {
  26692. const shadowCamera = this.camera;
  26693. const shadowMatrix = this.matrix;
  26694. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26695. shadowCamera.position.copy( _lightPositionWorld$1 );
  26696. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26697. shadowCamera.lookAt( _lookTarget$1 );
  26698. shadowCamera.updateMatrixWorld();
  26699. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26700. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26701. shadowMatrix.set(
  26702. 0.5, 0.0, 0.0, 0.5,
  26703. 0.0, 0.5, 0.0, 0.5,
  26704. 0.0, 0.0, 0.5, 0.5,
  26705. 0.0, 0.0, 0.0, 1.0
  26706. );
  26707. shadowMatrix.multiply( _projScreenMatrix$1 );
  26708. }
  26709. getViewport( viewportIndex ) {
  26710. return this._viewports[ viewportIndex ];
  26711. }
  26712. getFrameExtents() {
  26713. return this._frameExtents;
  26714. }
  26715. dispose() {
  26716. if ( this.map ) {
  26717. this.map.dispose();
  26718. }
  26719. if ( this.mapPass ) {
  26720. this.mapPass.dispose();
  26721. }
  26722. }
  26723. copy( source ) {
  26724. this.camera = source.camera.clone();
  26725. this.intensity = source.intensity;
  26726. this.bias = source.bias;
  26727. this.radius = source.radius;
  26728. this.mapSize.copy( source.mapSize );
  26729. return this;
  26730. }
  26731. clone() {
  26732. return new this.constructor().copy( this );
  26733. }
  26734. toJSON() {
  26735. const object = {};
  26736. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  26737. if ( this.bias !== 0 ) object.bias = this.bias;
  26738. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26739. if ( this.radius !== 1 ) object.radius = this.radius;
  26740. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26741. object.camera = this.camera.toJSON( false ).object;
  26742. delete object.camera.matrix;
  26743. return object;
  26744. }
  26745. }
  26746. class SpotLightShadow extends LightShadow {
  26747. constructor() {
  26748. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26749. this.isSpotLightShadow = true;
  26750. this.focus = 1;
  26751. }
  26752. updateMatrices( light ) {
  26753. const camera = this.camera;
  26754. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26755. const aspect = this.mapSize.width / this.mapSize.height;
  26756. const far = light.distance || camera.far;
  26757. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26758. camera.fov = fov;
  26759. camera.aspect = aspect;
  26760. camera.far = far;
  26761. camera.updateProjectionMatrix();
  26762. }
  26763. super.updateMatrices( light );
  26764. }
  26765. copy( source ) {
  26766. super.copy( source );
  26767. this.focus = source.focus;
  26768. return this;
  26769. }
  26770. }
  26771. class SpotLight extends Light {
  26772. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26773. super( color, intensity );
  26774. this.isSpotLight = true;
  26775. this.type = 'SpotLight';
  26776. this.position.copy( Object3D.DEFAULT_UP );
  26777. this.updateMatrix();
  26778. this.target = new Object3D();
  26779. this.distance = distance;
  26780. this.angle = angle;
  26781. this.penumbra = penumbra;
  26782. this.decay = decay;
  26783. this.map = null;
  26784. this.shadow = new SpotLightShadow();
  26785. }
  26786. get power() {
  26787. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26788. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26789. return this.intensity * Math.PI;
  26790. }
  26791. set power( power ) {
  26792. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26793. this.intensity = power / Math.PI;
  26794. }
  26795. dispose() {
  26796. this.shadow.dispose();
  26797. }
  26798. copy( source, recursive ) {
  26799. super.copy( source, recursive );
  26800. this.distance = source.distance;
  26801. this.angle = source.angle;
  26802. this.penumbra = source.penumbra;
  26803. this.decay = source.decay;
  26804. this.target = source.target.clone();
  26805. this.shadow = source.shadow.clone();
  26806. return this;
  26807. }
  26808. }
  26809. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26810. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26811. const _lookTarget = /*@__PURE__*/ new Vector3();
  26812. class PointLightShadow extends LightShadow {
  26813. constructor() {
  26814. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26815. this.isPointLightShadow = true;
  26816. this._frameExtents = new Vector2( 4, 2 );
  26817. this._viewportCount = 6;
  26818. this._viewports = [
  26819. // These viewports map a cube-map onto a 2D texture with the
  26820. // following orientation:
  26821. //
  26822. // xzXZ
  26823. // y Y
  26824. //
  26825. // X - Positive x direction
  26826. // x - Negative x direction
  26827. // Y - Positive y direction
  26828. // y - Negative y direction
  26829. // Z - Positive z direction
  26830. // z - Negative z direction
  26831. // positive X
  26832. new Vector4( 2, 1, 1, 1 ),
  26833. // negative X
  26834. new Vector4( 0, 1, 1, 1 ),
  26835. // positive Z
  26836. new Vector4( 3, 1, 1, 1 ),
  26837. // negative Z
  26838. new Vector4( 1, 1, 1, 1 ),
  26839. // positive Y
  26840. new Vector4( 3, 0, 1, 1 ),
  26841. // negative Y
  26842. new Vector4( 1, 0, 1, 1 )
  26843. ];
  26844. this._cubeDirections = [
  26845. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26846. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26847. ];
  26848. this._cubeUps = [
  26849. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26850. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26851. ];
  26852. }
  26853. updateMatrices( light, viewportIndex = 0 ) {
  26854. const camera = this.camera;
  26855. const shadowMatrix = this.matrix;
  26856. const far = light.distance || camera.far;
  26857. if ( far !== camera.far ) {
  26858. camera.far = far;
  26859. camera.updateProjectionMatrix();
  26860. }
  26861. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26862. camera.position.copy( _lightPositionWorld );
  26863. _lookTarget.copy( camera.position );
  26864. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26865. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26866. camera.lookAt( _lookTarget );
  26867. camera.updateMatrixWorld();
  26868. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26869. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26870. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26871. }
  26872. }
  26873. class PointLight extends Light {
  26874. constructor( color, intensity, distance = 0, decay = 2 ) {
  26875. super( color, intensity );
  26876. this.isPointLight = true;
  26877. this.type = 'PointLight';
  26878. this.distance = distance;
  26879. this.decay = decay;
  26880. this.shadow = new PointLightShadow();
  26881. }
  26882. get power() {
  26883. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26884. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26885. return this.intensity * 4 * Math.PI;
  26886. }
  26887. set power( power ) {
  26888. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26889. this.intensity = power / ( 4 * Math.PI );
  26890. }
  26891. dispose() {
  26892. this.shadow.dispose();
  26893. }
  26894. copy( source, recursive ) {
  26895. super.copy( source, recursive );
  26896. this.distance = source.distance;
  26897. this.decay = source.decay;
  26898. this.shadow = source.shadow.clone();
  26899. return this;
  26900. }
  26901. }
  26902. class DirectionalLightShadow extends LightShadow {
  26903. constructor() {
  26904. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26905. this.isDirectionalLightShadow = true;
  26906. }
  26907. }
  26908. class DirectionalLight extends Light {
  26909. constructor( color, intensity ) {
  26910. super( color, intensity );
  26911. this.isDirectionalLight = true;
  26912. this.type = 'DirectionalLight';
  26913. this.position.copy( Object3D.DEFAULT_UP );
  26914. this.updateMatrix();
  26915. this.target = new Object3D();
  26916. this.shadow = new DirectionalLightShadow();
  26917. }
  26918. dispose() {
  26919. this.shadow.dispose();
  26920. }
  26921. copy( source ) {
  26922. super.copy( source );
  26923. this.target = source.target.clone();
  26924. this.shadow = source.shadow.clone();
  26925. return this;
  26926. }
  26927. }
  26928. class AmbientLight extends Light {
  26929. constructor( color, intensity ) {
  26930. super( color, intensity );
  26931. this.isAmbientLight = true;
  26932. this.type = 'AmbientLight';
  26933. }
  26934. }
  26935. class RectAreaLight extends Light {
  26936. constructor( color, intensity, width = 10, height = 10 ) {
  26937. super( color, intensity );
  26938. this.isRectAreaLight = true;
  26939. this.type = 'RectAreaLight';
  26940. this.width = width;
  26941. this.height = height;
  26942. }
  26943. get power() {
  26944. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26945. return this.intensity * this.width * this.height * Math.PI;
  26946. }
  26947. set power( power ) {
  26948. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26949. this.intensity = power / ( this.width * this.height * Math.PI );
  26950. }
  26951. copy( source ) {
  26952. super.copy( source );
  26953. this.width = source.width;
  26954. this.height = source.height;
  26955. return this;
  26956. }
  26957. toJSON( meta ) {
  26958. const data = super.toJSON( meta );
  26959. data.object.width = this.width;
  26960. data.object.height = this.height;
  26961. return data;
  26962. }
  26963. }
  26964. /**
  26965. * Primary reference:
  26966. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26967. *
  26968. * Secondary reference:
  26969. * https://www.ppsloan.org/publications/StupidSH36.pdf
  26970. */
  26971. // 3-band SH defined by 9 coefficients
  26972. class SphericalHarmonics3 {
  26973. constructor() {
  26974. this.isSphericalHarmonics3 = true;
  26975. this.coefficients = [];
  26976. for ( let i = 0; i < 9; i ++ ) {
  26977. this.coefficients.push( new Vector3() );
  26978. }
  26979. }
  26980. set( coefficients ) {
  26981. for ( let i = 0; i < 9; i ++ ) {
  26982. this.coefficients[ i ].copy( coefficients[ i ] );
  26983. }
  26984. return this;
  26985. }
  26986. zero() {
  26987. for ( let i = 0; i < 9; i ++ ) {
  26988. this.coefficients[ i ].set( 0, 0, 0 );
  26989. }
  26990. return this;
  26991. }
  26992. // get the radiance in the direction of the normal
  26993. // target is a Vector3
  26994. getAt( normal, target ) {
  26995. // normal is assumed to be unit length
  26996. const x = normal.x, y = normal.y, z = normal.z;
  26997. const coeff = this.coefficients;
  26998. // band 0
  26999. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  27000. // band 1
  27001. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  27002. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  27003. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  27004. // band 2
  27005. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  27006. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  27007. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  27008. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  27009. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  27010. return target;
  27011. }
  27012. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  27013. // target is a Vector3
  27014. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  27015. getIrradianceAt( normal, target ) {
  27016. // normal is assumed to be unit length
  27017. const x = normal.x, y = normal.y, z = normal.z;
  27018. const coeff = this.coefficients;
  27019. // band 0
  27020. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  27021. // band 1
  27022. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  27023. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  27024. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  27025. // band 2
  27026. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  27027. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  27028. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  27029. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  27030. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  27031. return target;
  27032. }
  27033. add( sh ) {
  27034. for ( let i = 0; i < 9; i ++ ) {
  27035. this.coefficients[ i ].add( sh.coefficients[ i ] );
  27036. }
  27037. return this;
  27038. }
  27039. addScaledSH( sh, s ) {
  27040. for ( let i = 0; i < 9; i ++ ) {
  27041. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  27042. }
  27043. return this;
  27044. }
  27045. scale( s ) {
  27046. for ( let i = 0; i < 9; i ++ ) {
  27047. this.coefficients[ i ].multiplyScalar( s );
  27048. }
  27049. return this;
  27050. }
  27051. lerp( sh, alpha ) {
  27052. for ( let i = 0; i < 9; i ++ ) {
  27053. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  27054. }
  27055. return this;
  27056. }
  27057. equals( sh ) {
  27058. for ( let i = 0; i < 9; i ++ ) {
  27059. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  27060. return false;
  27061. }
  27062. }
  27063. return true;
  27064. }
  27065. copy( sh ) {
  27066. return this.set( sh.coefficients );
  27067. }
  27068. clone() {
  27069. return new this.constructor().copy( this );
  27070. }
  27071. fromArray( array, offset = 0 ) {
  27072. const coefficients = this.coefficients;
  27073. for ( let i = 0; i < 9; i ++ ) {
  27074. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  27075. }
  27076. return this;
  27077. }
  27078. toArray( array = [], offset = 0 ) {
  27079. const coefficients = this.coefficients;
  27080. for ( let i = 0; i < 9; i ++ ) {
  27081. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  27082. }
  27083. return array;
  27084. }
  27085. // evaluate the basis functions
  27086. // shBasis is an Array[ 9 ]
  27087. static getBasisAt( normal, shBasis ) {
  27088. // normal is assumed to be unit length
  27089. const x = normal.x, y = normal.y, z = normal.z;
  27090. // band 0
  27091. shBasis[ 0 ] = 0.282095;
  27092. // band 1
  27093. shBasis[ 1 ] = 0.488603 * y;
  27094. shBasis[ 2 ] = 0.488603 * z;
  27095. shBasis[ 3 ] = 0.488603 * x;
  27096. // band 2
  27097. shBasis[ 4 ] = 1.092548 * x * y;
  27098. shBasis[ 5 ] = 1.092548 * y * z;
  27099. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  27100. shBasis[ 7 ] = 1.092548 * x * z;
  27101. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  27102. }
  27103. }
  27104. class LightProbe extends Light {
  27105. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  27106. super( undefined, intensity );
  27107. this.isLightProbe = true;
  27108. this.sh = sh;
  27109. }
  27110. copy( source ) {
  27111. super.copy( source );
  27112. this.sh.copy( source.sh );
  27113. return this;
  27114. }
  27115. fromJSON( json ) {
  27116. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  27117. this.sh.fromArray( json.sh );
  27118. return this;
  27119. }
  27120. toJSON( meta ) {
  27121. const data = super.toJSON( meta );
  27122. data.object.sh = this.sh.toArray();
  27123. return data;
  27124. }
  27125. }
  27126. class MaterialLoader extends Loader {
  27127. constructor( manager ) {
  27128. super( manager );
  27129. this.textures = {};
  27130. }
  27131. load( url, onLoad, onProgress, onError ) {
  27132. const scope = this;
  27133. const loader = new FileLoader( scope.manager );
  27134. loader.setPath( scope.path );
  27135. loader.setRequestHeader( scope.requestHeader );
  27136. loader.setWithCredentials( scope.withCredentials );
  27137. loader.load( url, function ( text ) {
  27138. try {
  27139. onLoad( scope.parse( JSON.parse( text ) ) );
  27140. } catch ( e ) {
  27141. if ( onError ) {
  27142. onError( e );
  27143. } else {
  27144. console.error( e );
  27145. }
  27146. scope.manager.itemError( url );
  27147. }
  27148. }, onProgress, onError );
  27149. }
  27150. parse( json ) {
  27151. const textures = this.textures;
  27152. function getTexture( name ) {
  27153. if ( textures[ name ] === undefined ) {
  27154. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  27155. }
  27156. return textures[ name ];
  27157. }
  27158. const material = MaterialLoader.createMaterialFromType( json.type );
  27159. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  27160. if ( json.name !== undefined ) material.name = json.name;
  27161. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  27162. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  27163. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  27164. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  27165. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  27166. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  27167. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  27168. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  27169. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  27170. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  27171. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  27172. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  27173. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  27174. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  27175. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  27176. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  27177. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  27178. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  27179. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  27180. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  27181. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  27182. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  27183. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  27184. if ( json.fog !== undefined ) material.fog = json.fog;
  27185. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  27186. if ( json.blending !== undefined ) material.blending = json.blending;
  27187. if ( json.combine !== undefined ) material.combine = json.combine;
  27188. if ( json.side !== undefined ) material.side = json.side;
  27189. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  27190. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  27191. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  27192. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  27193. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  27194. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  27195. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  27196. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  27197. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  27198. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  27199. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  27200. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  27201. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  27202. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  27203. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  27204. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  27205. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  27206. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  27207. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  27208. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  27209. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  27210. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  27211. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  27212. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  27213. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  27214. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  27215. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  27216. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  27217. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  27218. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  27219. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  27220. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  27221. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  27222. if ( json.scale !== undefined ) material.scale = json.scale;
  27223. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  27224. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  27225. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  27226. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  27227. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  27228. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  27229. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  27230. if ( json.visible !== undefined ) material.visible = json.visible;
  27231. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  27232. if ( json.userData !== undefined ) material.userData = json.userData;
  27233. if ( json.vertexColors !== undefined ) {
  27234. if ( typeof json.vertexColors === 'number' ) {
  27235. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  27236. } else {
  27237. material.vertexColors = json.vertexColors;
  27238. }
  27239. }
  27240. // Shader Material
  27241. if ( json.uniforms !== undefined ) {
  27242. for ( const name in json.uniforms ) {
  27243. const uniform = json.uniforms[ name ];
  27244. material.uniforms[ name ] = {};
  27245. switch ( uniform.type ) {
  27246. case 't':
  27247. material.uniforms[ name ].value = getTexture( uniform.value );
  27248. break;
  27249. case 'c':
  27250. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  27251. break;
  27252. case 'v2':
  27253. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27254. break;
  27255. case 'v3':
  27256. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27257. break;
  27258. case 'v4':
  27259. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27260. break;
  27261. case 'm3':
  27262. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27263. break;
  27264. case 'm4':
  27265. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27266. break;
  27267. default:
  27268. material.uniforms[ name ].value = uniform.value;
  27269. }
  27270. }
  27271. }
  27272. if ( json.defines !== undefined ) material.defines = json.defines;
  27273. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  27274. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  27275. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  27276. if ( json.extensions !== undefined ) {
  27277. for ( const key in json.extensions ) {
  27278. material.extensions[ key ] = json.extensions[ key ];
  27279. }
  27280. }
  27281. if ( json.lights !== undefined ) material.lights = json.lights;
  27282. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  27283. // for PointsMaterial
  27284. if ( json.size !== undefined ) material.size = json.size;
  27285. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  27286. // maps
  27287. if ( json.map !== undefined ) material.map = getTexture( json.map );
  27288. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  27289. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  27290. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  27291. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  27292. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  27293. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  27294. if ( json.normalScale !== undefined ) {
  27295. let normalScale = json.normalScale;
  27296. if ( Array.isArray( normalScale ) === false ) {
  27297. // Blender exporter used to export a scalar. See #7459
  27298. normalScale = [ normalScale, normalScale ];
  27299. }
  27300. material.normalScale = new Vector2().fromArray( normalScale );
  27301. }
  27302. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  27303. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  27304. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  27305. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  27306. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  27307. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  27308. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  27309. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  27310. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  27311. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  27312. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  27313. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  27314. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  27315. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  27316. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  27317. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  27318. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  27319. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  27320. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  27321. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  27322. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  27323. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  27324. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  27325. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  27326. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  27327. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  27328. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  27329. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  27330. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  27331. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  27332. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  27333. return material;
  27334. }
  27335. setTextures( value ) {
  27336. this.textures = value;
  27337. return this;
  27338. }
  27339. static createMaterialFromType( type ) {
  27340. const materialLib = {
  27341. ShadowMaterial,
  27342. SpriteMaterial,
  27343. RawShaderMaterial,
  27344. ShaderMaterial,
  27345. PointsMaterial,
  27346. MeshPhysicalMaterial,
  27347. MeshStandardMaterial,
  27348. MeshPhongMaterial,
  27349. MeshToonMaterial,
  27350. MeshNormalMaterial,
  27351. MeshLambertMaterial,
  27352. MeshDepthMaterial,
  27353. MeshDistanceMaterial,
  27354. MeshBasicMaterial,
  27355. MeshMatcapMaterial,
  27356. LineDashedMaterial,
  27357. LineBasicMaterial,
  27358. Material
  27359. };
  27360. return new materialLib[ type ]();
  27361. }
  27362. }
  27363. class LoaderUtils {
  27364. static decodeText( array ) { // @deprecated, r165
  27365. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  27366. if ( typeof TextDecoder !== 'undefined' ) {
  27367. return new TextDecoder().decode( array );
  27368. }
  27369. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  27370. // throws a "maximum call stack size exceeded" error for large arrays.
  27371. let s = '';
  27372. for ( let i = 0, il = array.length; i < il; i ++ ) {
  27373. // Implicitly assumes little-endian.
  27374. s += String.fromCharCode( array[ i ] );
  27375. }
  27376. try {
  27377. // merges multi-byte utf-8 characters.
  27378. return decodeURIComponent( escape( s ) );
  27379. } catch ( e ) { // see #16358
  27380. return s;
  27381. }
  27382. }
  27383. static extractUrlBase( url ) {
  27384. const index = url.lastIndexOf( '/' );
  27385. if ( index === - 1 ) return './';
  27386. return url.slice( 0, index + 1 );
  27387. }
  27388. static resolveURL( url, path ) {
  27389. // Invalid URL
  27390. if ( typeof url !== 'string' || url === '' ) return '';
  27391. // Host Relative URL
  27392. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  27393. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  27394. }
  27395. // Absolute URL http://,https://,//
  27396. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  27397. // Data URI
  27398. if ( /^data:.*,.*$/i.test( url ) ) return url;
  27399. // Blob URL
  27400. if ( /^blob:.*$/i.test( url ) ) return url;
  27401. // Relative URL
  27402. return path + url;
  27403. }
  27404. }
  27405. class InstancedBufferGeometry extends BufferGeometry {
  27406. constructor() {
  27407. super();
  27408. this.isInstancedBufferGeometry = true;
  27409. this.type = 'InstancedBufferGeometry';
  27410. this.instanceCount = Infinity;
  27411. }
  27412. copy( source ) {
  27413. super.copy( source );
  27414. this.instanceCount = source.instanceCount;
  27415. return this;
  27416. }
  27417. toJSON() {
  27418. const data = super.toJSON();
  27419. data.instanceCount = this.instanceCount;
  27420. data.isInstancedBufferGeometry = true;
  27421. return data;
  27422. }
  27423. }
  27424. class BufferGeometryLoader extends Loader {
  27425. constructor( manager ) {
  27426. super( manager );
  27427. }
  27428. load( url, onLoad, onProgress, onError ) {
  27429. const scope = this;
  27430. const loader = new FileLoader( scope.manager );
  27431. loader.setPath( scope.path );
  27432. loader.setRequestHeader( scope.requestHeader );
  27433. loader.setWithCredentials( scope.withCredentials );
  27434. loader.load( url, function ( text ) {
  27435. try {
  27436. onLoad( scope.parse( JSON.parse( text ) ) );
  27437. } catch ( e ) {
  27438. if ( onError ) {
  27439. onError( e );
  27440. } else {
  27441. console.error( e );
  27442. }
  27443. scope.manager.itemError( url );
  27444. }
  27445. }, onProgress, onError );
  27446. }
  27447. parse( json ) {
  27448. const interleavedBufferMap = {};
  27449. const arrayBufferMap = {};
  27450. function getInterleavedBuffer( json, uuid ) {
  27451. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  27452. const interleavedBuffers = json.interleavedBuffers;
  27453. const interleavedBuffer = interleavedBuffers[ uuid ];
  27454. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  27455. const array = getTypedArray( interleavedBuffer.type, buffer );
  27456. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  27457. ib.uuid = interleavedBuffer.uuid;
  27458. interleavedBufferMap[ uuid ] = ib;
  27459. return ib;
  27460. }
  27461. function getArrayBuffer( json, uuid ) {
  27462. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  27463. const arrayBuffers = json.arrayBuffers;
  27464. const arrayBuffer = arrayBuffers[ uuid ];
  27465. const ab = new Uint32Array( arrayBuffer ).buffer;
  27466. arrayBufferMap[ uuid ] = ab;
  27467. return ab;
  27468. }
  27469. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  27470. const index = json.data.index;
  27471. if ( index !== undefined ) {
  27472. const typedArray = getTypedArray( index.type, index.array );
  27473. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27474. }
  27475. const attributes = json.data.attributes;
  27476. for ( const key in attributes ) {
  27477. const attribute = attributes[ key ];
  27478. let bufferAttribute;
  27479. if ( attribute.isInterleavedBufferAttribute ) {
  27480. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27481. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27482. } else {
  27483. const typedArray = getTypedArray( attribute.type, attribute.array );
  27484. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  27485. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  27486. }
  27487. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27488. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  27489. geometry.setAttribute( key, bufferAttribute );
  27490. }
  27491. const morphAttributes = json.data.morphAttributes;
  27492. if ( morphAttributes ) {
  27493. for ( const key in morphAttributes ) {
  27494. const attributeArray = morphAttributes[ key ];
  27495. const array = [];
  27496. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  27497. const attribute = attributeArray[ i ];
  27498. let bufferAttribute;
  27499. if ( attribute.isInterleavedBufferAttribute ) {
  27500. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27501. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27502. } else {
  27503. const typedArray = getTypedArray( attribute.type, attribute.array );
  27504. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27505. }
  27506. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27507. array.push( bufferAttribute );
  27508. }
  27509. geometry.morphAttributes[ key ] = array;
  27510. }
  27511. }
  27512. const morphTargetsRelative = json.data.morphTargetsRelative;
  27513. if ( morphTargetsRelative ) {
  27514. geometry.morphTargetsRelative = true;
  27515. }
  27516. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27517. if ( groups !== undefined ) {
  27518. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  27519. const group = groups[ i ];
  27520. geometry.addGroup( group.start, group.count, group.materialIndex );
  27521. }
  27522. }
  27523. const boundingSphere = json.data.boundingSphere;
  27524. if ( boundingSphere !== undefined ) {
  27525. const center = new Vector3();
  27526. if ( boundingSphere.center !== undefined ) {
  27527. center.fromArray( boundingSphere.center );
  27528. }
  27529. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27530. }
  27531. if ( json.name ) geometry.name = json.name;
  27532. if ( json.userData ) geometry.userData = json.userData;
  27533. return geometry;
  27534. }
  27535. }
  27536. class ObjectLoader extends Loader {
  27537. constructor( manager ) {
  27538. super( manager );
  27539. }
  27540. load( url, onLoad, onProgress, onError ) {
  27541. const scope = this;
  27542. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27543. this.resourcePath = this.resourcePath || path;
  27544. const loader = new FileLoader( this.manager );
  27545. loader.setPath( this.path );
  27546. loader.setRequestHeader( this.requestHeader );
  27547. loader.setWithCredentials( this.withCredentials );
  27548. loader.load( url, function ( text ) {
  27549. let json = null;
  27550. try {
  27551. json = JSON.parse( text );
  27552. } catch ( error ) {
  27553. if ( onError !== undefined ) onError( error );
  27554. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27555. return;
  27556. }
  27557. const metadata = json.metadata;
  27558. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27559. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  27560. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27561. return;
  27562. }
  27563. scope.parse( json, onLoad );
  27564. }, onProgress, onError );
  27565. }
  27566. async loadAsync( url, onProgress ) {
  27567. const scope = this;
  27568. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27569. this.resourcePath = this.resourcePath || path;
  27570. const loader = new FileLoader( this.manager );
  27571. loader.setPath( this.path );
  27572. loader.setRequestHeader( this.requestHeader );
  27573. loader.setWithCredentials( this.withCredentials );
  27574. const text = await loader.loadAsync( url, onProgress );
  27575. const json = JSON.parse( text );
  27576. const metadata = json.metadata;
  27577. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27578. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27579. }
  27580. return await scope.parseAsync( json );
  27581. }
  27582. parse( json, onLoad ) {
  27583. const animations = this.parseAnimations( json.animations );
  27584. const shapes = this.parseShapes( json.shapes );
  27585. const geometries = this.parseGeometries( json.geometries, shapes );
  27586. const images = this.parseImages( json.images, function () {
  27587. if ( onLoad !== undefined ) onLoad( object );
  27588. } );
  27589. const textures = this.parseTextures( json.textures, images );
  27590. const materials = this.parseMaterials( json.materials, textures );
  27591. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27592. const skeletons = this.parseSkeletons( json.skeletons, object );
  27593. this.bindSkeletons( object, skeletons );
  27594. this.bindLightTargets( object );
  27595. //
  27596. if ( onLoad !== undefined ) {
  27597. let hasImages = false;
  27598. for ( const uuid in images ) {
  27599. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27600. hasImages = true;
  27601. break;
  27602. }
  27603. }
  27604. if ( hasImages === false ) onLoad( object );
  27605. }
  27606. return object;
  27607. }
  27608. async parseAsync( json ) {
  27609. const animations = this.parseAnimations( json.animations );
  27610. const shapes = this.parseShapes( json.shapes );
  27611. const geometries = this.parseGeometries( json.geometries, shapes );
  27612. const images = await this.parseImagesAsync( json.images );
  27613. const textures = this.parseTextures( json.textures, images );
  27614. const materials = this.parseMaterials( json.materials, textures );
  27615. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27616. const skeletons = this.parseSkeletons( json.skeletons, object );
  27617. this.bindSkeletons( object, skeletons );
  27618. this.bindLightTargets( object );
  27619. return object;
  27620. }
  27621. parseShapes( json ) {
  27622. const shapes = {};
  27623. if ( json !== undefined ) {
  27624. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27625. const shape = new Shape().fromJSON( json[ i ] );
  27626. shapes[ shape.uuid ] = shape;
  27627. }
  27628. }
  27629. return shapes;
  27630. }
  27631. parseSkeletons( json, object ) {
  27632. const skeletons = {};
  27633. const bones = {};
  27634. // generate bone lookup table
  27635. object.traverse( function ( child ) {
  27636. if ( child.isBone ) bones[ child.uuid ] = child;
  27637. } );
  27638. // create skeletons
  27639. if ( json !== undefined ) {
  27640. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27641. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27642. skeletons[ skeleton.uuid ] = skeleton;
  27643. }
  27644. }
  27645. return skeletons;
  27646. }
  27647. parseGeometries( json, shapes ) {
  27648. const geometries = {};
  27649. if ( json !== undefined ) {
  27650. const bufferGeometryLoader = new BufferGeometryLoader();
  27651. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27652. let geometry;
  27653. const data = json[ i ];
  27654. switch ( data.type ) {
  27655. case 'BufferGeometry':
  27656. case 'InstancedBufferGeometry':
  27657. geometry = bufferGeometryLoader.parse( data );
  27658. break;
  27659. default:
  27660. if ( data.type in Geometries ) {
  27661. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27662. } else {
  27663. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27664. }
  27665. }
  27666. geometry.uuid = data.uuid;
  27667. if ( data.name !== undefined ) geometry.name = data.name;
  27668. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27669. geometries[ data.uuid ] = geometry;
  27670. }
  27671. }
  27672. return geometries;
  27673. }
  27674. parseMaterials( json, textures ) {
  27675. const cache = {}; // MultiMaterial
  27676. const materials = {};
  27677. if ( json !== undefined ) {
  27678. const loader = new MaterialLoader();
  27679. loader.setTextures( textures );
  27680. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27681. const data = json[ i ];
  27682. if ( cache[ data.uuid ] === undefined ) {
  27683. cache[ data.uuid ] = loader.parse( data );
  27684. }
  27685. materials[ data.uuid ] = cache[ data.uuid ];
  27686. }
  27687. }
  27688. return materials;
  27689. }
  27690. parseAnimations( json ) {
  27691. const animations = {};
  27692. if ( json !== undefined ) {
  27693. for ( let i = 0; i < json.length; i ++ ) {
  27694. const data = json[ i ];
  27695. const clip = AnimationClip.parse( data );
  27696. animations[ clip.uuid ] = clip;
  27697. }
  27698. }
  27699. return animations;
  27700. }
  27701. parseImages( json, onLoad ) {
  27702. const scope = this;
  27703. const images = {};
  27704. let loader;
  27705. function loadImage( url ) {
  27706. scope.manager.itemStart( url );
  27707. return loader.load( url, function () {
  27708. scope.manager.itemEnd( url );
  27709. }, undefined, function () {
  27710. scope.manager.itemError( url );
  27711. scope.manager.itemEnd( url );
  27712. } );
  27713. }
  27714. function deserializeImage( image ) {
  27715. if ( typeof image === 'string' ) {
  27716. const url = image;
  27717. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27718. return loadImage( path );
  27719. } else {
  27720. if ( image.data ) {
  27721. return {
  27722. data: getTypedArray( image.type, image.data ),
  27723. width: image.width,
  27724. height: image.height
  27725. };
  27726. } else {
  27727. return null;
  27728. }
  27729. }
  27730. }
  27731. if ( json !== undefined && json.length > 0 ) {
  27732. const manager = new LoadingManager( onLoad );
  27733. loader = new ImageLoader( manager );
  27734. loader.setCrossOrigin( this.crossOrigin );
  27735. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27736. const image = json[ i ];
  27737. const url = image.url;
  27738. if ( Array.isArray( url ) ) {
  27739. // load array of images e.g CubeTexture
  27740. const imageArray = [];
  27741. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27742. const currentUrl = url[ j ];
  27743. const deserializedImage = deserializeImage( currentUrl );
  27744. if ( deserializedImage !== null ) {
  27745. if ( deserializedImage instanceof HTMLImageElement ) {
  27746. imageArray.push( deserializedImage );
  27747. } else {
  27748. // special case: handle array of data textures for cube textures
  27749. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27750. }
  27751. }
  27752. }
  27753. images[ image.uuid ] = new Source( imageArray );
  27754. } else {
  27755. // load single image
  27756. const deserializedImage = deserializeImage( image.url );
  27757. images[ image.uuid ] = new Source( deserializedImage );
  27758. }
  27759. }
  27760. }
  27761. return images;
  27762. }
  27763. async parseImagesAsync( json ) {
  27764. const scope = this;
  27765. const images = {};
  27766. let loader;
  27767. async function deserializeImage( image ) {
  27768. if ( typeof image === 'string' ) {
  27769. const url = image;
  27770. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27771. return await loader.loadAsync( path );
  27772. } else {
  27773. if ( image.data ) {
  27774. return {
  27775. data: getTypedArray( image.type, image.data ),
  27776. width: image.width,
  27777. height: image.height
  27778. };
  27779. } else {
  27780. return null;
  27781. }
  27782. }
  27783. }
  27784. if ( json !== undefined && json.length > 0 ) {
  27785. loader = new ImageLoader( this.manager );
  27786. loader.setCrossOrigin( this.crossOrigin );
  27787. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27788. const image = json[ i ];
  27789. const url = image.url;
  27790. if ( Array.isArray( url ) ) {
  27791. // load array of images e.g CubeTexture
  27792. const imageArray = [];
  27793. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27794. const currentUrl = url[ j ];
  27795. const deserializedImage = await deserializeImage( currentUrl );
  27796. if ( deserializedImage !== null ) {
  27797. if ( deserializedImage instanceof HTMLImageElement ) {
  27798. imageArray.push( deserializedImage );
  27799. } else {
  27800. // special case: handle array of data textures for cube textures
  27801. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27802. }
  27803. }
  27804. }
  27805. images[ image.uuid ] = new Source( imageArray );
  27806. } else {
  27807. // load single image
  27808. const deserializedImage = await deserializeImage( image.url );
  27809. images[ image.uuid ] = new Source( deserializedImage );
  27810. }
  27811. }
  27812. }
  27813. return images;
  27814. }
  27815. parseTextures( json, images ) {
  27816. function parseConstant( value, type ) {
  27817. if ( typeof value === 'number' ) return value;
  27818. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27819. return type[ value ];
  27820. }
  27821. const textures = {};
  27822. if ( json !== undefined ) {
  27823. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27824. const data = json[ i ];
  27825. if ( data.image === undefined ) {
  27826. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27827. }
  27828. if ( images[ data.image ] === undefined ) {
  27829. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27830. }
  27831. const source = images[ data.image ];
  27832. const image = source.data;
  27833. let texture;
  27834. if ( Array.isArray( image ) ) {
  27835. texture = new CubeTexture();
  27836. if ( image.length === 6 ) texture.needsUpdate = true;
  27837. } else {
  27838. if ( image && image.data ) {
  27839. texture = new DataTexture();
  27840. } else {
  27841. texture = new Texture();
  27842. }
  27843. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27844. }
  27845. texture.source = source;
  27846. texture.uuid = data.uuid;
  27847. if ( data.name !== undefined ) texture.name = data.name;
  27848. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27849. if ( data.channel !== undefined ) texture.channel = data.channel;
  27850. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27851. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27852. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27853. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27854. if ( data.wrap !== undefined ) {
  27855. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27856. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27857. }
  27858. if ( data.format !== undefined ) texture.format = data.format;
  27859. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27860. if ( data.type !== undefined ) texture.type = data.type;
  27861. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27862. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27863. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27864. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27865. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27866. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27867. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27868. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27869. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27870. if ( data.userData !== undefined ) texture.userData = data.userData;
  27871. textures[ data.uuid ] = texture;
  27872. }
  27873. }
  27874. return textures;
  27875. }
  27876. parseObject( data, geometries, materials, textures, animations ) {
  27877. let object;
  27878. function getGeometry( name ) {
  27879. if ( geometries[ name ] === undefined ) {
  27880. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27881. }
  27882. return geometries[ name ];
  27883. }
  27884. function getMaterial( name ) {
  27885. if ( name === undefined ) return undefined;
  27886. if ( Array.isArray( name ) ) {
  27887. const array = [];
  27888. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27889. const uuid = name[ i ];
  27890. if ( materials[ uuid ] === undefined ) {
  27891. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27892. }
  27893. array.push( materials[ uuid ] );
  27894. }
  27895. return array;
  27896. }
  27897. if ( materials[ name ] === undefined ) {
  27898. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27899. }
  27900. return materials[ name ];
  27901. }
  27902. function getTexture( uuid ) {
  27903. if ( textures[ uuid ] === undefined ) {
  27904. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27905. }
  27906. return textures[ uuid ];
  27907. }
  27908. let geometry, material;
  27909. switch ( data.type ) {
  27910. case 'Scene':
  27911. object = new Scene();
  27912. if ( data.background !== undefined ) {
  27913. if ( Number.isInteger( data.background ) ) {
  27914. object.background = new Color( data.background );
  27915. } else {
  27916. object.background = getTexture( data.background );
  27917. }
  27918. }
  27919. if ( data.environment !== undefined ) {
  27920. object.environment = getTexture( data.environment );
  27921. }
  27922. if ( data.fog !== undefined ) {
  27923. if ( data.fog.type === 'Fog' ) {
  27924. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27925. } else if ( data.fog.type === 'FogExp2' ) {
  27926. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27927. }
  27928. if ( data.fog.name !== '' ) {
  27929. object.fog.name = data.fog.name;
  27930. }
  27931. }
  27932. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27933. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27934. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  27935. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  27936. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  27937. break;
  27938. case 'PerspectiveCamera':
  27939. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27940. if ( data.focus !== undefined ) object.focus = data.focus;
  27941. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27942. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27943. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27944. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27945. break;
  27946. case 'OrthographicCamera':
  27947. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27948. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27949. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27950. break;
  27951. case 'AmbientLight':
  27952. object = new AmbientLight( data.color, data.intensity );
  27953. break;
  27954. case 'DirectionalLight':
  27955. object = new DirectionalLight( data.color, data.intensity );
  27956. object.target = data.target || '';
  27957. break;
  27958. case 'PointLight':
  27959. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27960. break;
  27961. case 'RectAreaLight':
  27962. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27963. break;
  27964. case 'SpotLight':
  27965. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27966. object.target = data.target || '';
  27967. break;
  27968. case 'HemisphereLight':
  27969. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27970. break;
  27971. case 'LightProbe':
  27972. object = new LightProbe().fromJSON( data );
  27973. break;
  27974. case 'SkinnedMesh':
  27975. geometry = getGeometry( data.geometry );
  27976. material = getMaterial( data.material );
  27977. object = new SkinnedMesh( geometry, material );
  27978. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27979. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27980. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27981. break;
  27982. case 'Mesh':
  27983. geometry = getGeometry( data.geometry );
  27984. material = getMaterial( data.material );
  27985. object = new Mesh( geometry, material );
  27986. break;
  27987. case 'InstancedMesh':
  27988. geometry = getGeometry( data.geometry );
  27989. material = getMaterial( data.material );
  27990. const count = data.count;
  27991. const instanceMatrix = data.instanceMatrix;
  27992. const instanceColor = data.instanceColor;
  27993. object = new InstancedMesh( geometry, material, count );
  27994. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27995. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27996. break;
  27997. case 'BatchedMesh':
  27998. geometry = getGeometry( data.geometry );
  27999. material = getMaterial( data.material );
  28000. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  28001. object.geometry = geometry;
  28002. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  28003. object.sortObjects = data.sortObjects;
  28004. object._drawRanges = data.drawRanges;
  28005. object._reservedRanges = data.reservedRanges;
  28006. object._visibility = data.visibility;
  28007. object._active = data.active;
  28008. object._bounds = data.bounds.map( bound => {
  28009. const box = new Box3();
  28010. box.min.fromArray( bound.boxMin );
  28011. box.max.fromArray( bound.boxMax );
  28012. const sphere = new Sphere();
  28013. sphere.radius = bound.sphereRadius;
  28014. sphere.center.fromArray( bound.sphereCenter );
  28015. return {
  28016. boxInitialized: bound.boxInitialized,
  28017. box: box,
  28018. sphereInitialized: bound.sphereInitialized,
  28019. sphere: sphere
  28020. };
  28021. } );
  28022. object._maxInstanceCount = data.maxInstanceCount;
  28023. object._maxVertexCount = data.maxVertexCount;
  28024. object._maxIndexCount = data.maxIndexCount;
  28025. object._geometryInitialized = data.geometryInitialized;
  28026. object._geometryCount = data.geometryCount;
  28027. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  28028. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  28029. break;
  28030. case 'LOD':
  28031. object = new LOD();
  28032. break;
  28033. case 'Line':
  28034. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  28035. break;
  28036. case 'LineLoop':
  28037. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  28038. break;
  28039. case 'LineSegments':
  28040. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  28041. break;
  28042. case 'PointCloud':
  28043. case 'Points':
  28044. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  28045. break;
  28046. case 'Sprite':
  28047. object = new Sprite( getMaterial( data.material ) );
  28048. break;
  28049. case 'Group':
  28050. object = new Group();
  28051. break;
  28052. case 'Bone':
  28053. object = new Bone();
  28054. break;
  28055. default:
  28056. object = new Object3D();
  28057. }
  28058. object.uuid = data.uuid;
  28059. if ( data.name !== undefined ) object.name = data.name;
  28060. if ( data.matrix !== undefined ) {
  28061. object.matrix.fromArray( data.matrix );
  28062. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  28063. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  28064. } else {
  28065. if ( data.position !== undefined ) object.position.fromArray( data.position );
  28066. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  28067. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  28068. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  28069. }
  28070. if ( data.up !== undefined ) object.up.fromArray( data.up );
  28071. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  28072. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  28073. if ( data.shadow ) {
  28074. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  28075. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  28076. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  28077. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  28078. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  28079. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  28080. }
  28081. if ( data.visible !== undefined ) object.visible = data.visible;
  28082. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  28083. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  28084. if ( data.userData !== undefined ) object.userData = data.userData;
  28085. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  28086. if ( data.children !== undefined ) {
  28087. const children = data.children;
  28088. for ( let i = 0; i < children.length; i ++ ) {
  28089. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  28090. }
  28091. }
  28092. if ( data.animations !== undefined ) {
  28093. const objectAnimations = data.animations;
  28094. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  28095. const uuid = objectAnimations[ i ];
  28096. object.animations.push( animations[ uuid ] );
  28097. }
  28098. }
  28099. if ( data.type === 'LOD' ) {
  28100. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  28101. const levels = data.levels;
  28102. for ( let l = 0; l < levels.length; l ++ ) {
  28103. const level = levels[ l ];
  28104. const child = object.getObjectByProperty( 'uuid', level.object );
  28105. if ( child !== undefined ) {
  28106. object.addLevel( child, level.distance, level.hysteresis );
  28107. }
  28108. }
  28109. }
  28110. return object;
  28111. }
  28112. bindSkeletons( object, skeletons ) {
  28113. if ( Object.keys( skeletons ).length === 0 ) return;
  28114. object.traverse( function ( child ) {
  28115. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  28116. const skeleton = skeletons[ child.skeleton ];
  28117. if ( skeleton === undefined ) {
  28118. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  28119. } else {
  28120. child.bind( skeleton, child.bindMatrix );
  28121. }
  28122. }
  28123. } );
  28124. }
  28125. bindLightTargets( object ) {
  28126. object.traverse( function ( child ) {
  28127. if ( child.isDirectionalLight || child.isSpotLight ) {
  28128. const uuid = child.target;
  28129. const target = object.getObjectByProperty( 'uuid', uuid );
  28130. if ( target !== undefined ) {
  28131. child.target = target;
  28132. } else {
  28133. child.target = new Object3D();
  28134. }
  28135. }
  28136. } );
  28137. }
  28138. }
  28139. const TEXTURE_MAPPING = {
  28140. UVMapping: UVMapping,
  28141. CubeReflectionMapping: CubeReflectionMapping,
  28142. CubeRefractionMapping: CubeRefractionMapping,
  28143. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  28144. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  28145. CubeUVReflectionMapping: CubeUVReflectionMapping
  28146. };
  28147. const TEXTURE_WRAPPING = {
  28148. RepeatWrapping: RepeatWrapping,
  28149. ClampToEdgeWrapping: ClampToEdgeWrapping,
  28150. MirroredRepeatWrapping: MirroredRepeatWrapping
  28151. };
  28152. const TEXTURE_FILTER = {
  28153. NearestFilter: NearestFilter,
  28154. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  28155. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  28156. LinearFilter: LinearFilter,
  28157. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  28158. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  28159. };
  28160. class ImageBitmapLoader extends Loader {
  28161. constructor( manager ) {
  28162. super( manager );
  28163. this.isImageBitmapLoader = true;
  28164. if ( typeof createImageBitmap === 'undefined' ) {
  28165. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  28166. }
  28167. if ( typeof fetch === 'undefined' ) {
  28168. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  28169. }
  28170. this.options = { premultiplyAlpha: 'none' };
  28171. }
  28172. setOptions( options ) {
  28173. this.options = options;
  28174. return this;
  28175. }
  28176. load( url, onLoad, onProgress, onError ) {
  28177. if ( url === undefined ) url = '';
  28178. if ( this.path !== undefined ) url = this.path + url;
  28179. url = this.manager.resolveURL( url );
  28180. const scope = this;
  28181. const cached = Cache.get( url );
  28182. if ( cached !== undefined ) {
  28183. scope.manager.itemStart( url );
  28184. // If cached is a promise, wait for it to resolve
  28185. if ( cached.then ) {
  28186. cached.then( imageBitmap => {
  28187. if ( onLoad ) onLoad( imageBitmap );
  28188. scope.manager.itemEnd( url );
  28189. } ).catch( e => {
  28190. if ( onError ) onError( e );
  28191. } );
  28192. return;
  28193. }
  28194. // If cached is not a promise (i.e., it's already an imageBitmap)
  28195. setTimeout( function () {
  28196. if ( onLoad ) onLoad( cached );
  28197. scope.manager.itemEnd( url );
  28198. }, 0 );
  28199. return cached;
  28200. }
  28201. const fetchOptions = {};
  28202. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  28203. fetchOptions.headers = this.requestHeader;
  28204. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  28205. return res.blob();
  28206. } ).then( function ( blob ) {
  28207. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  28208. } ).then( function ( imageBitmap ) {
  28209. Cache.add( url, imageBitmap );
  28210. if ( onLoad ) onLoad( imageBitmap );
  28211. scope.manager.itemEnd( url );
  28212. return imageBitmap;
  28213. } ).catch( function ( e ) {
  28214. if ( onError ) onError( e );
  28215. Cache.remove( url );
  28216. scope.manager.itemError( url );
  28217. scope.manager.itemEnd( url );
  28218. } );
  28219. Cache.add( url, promise );
  28220. scope.manager.itemStart( url );
  28221. }
  28222. }
  28223. let _context;
  28224. class AudioContext {
  28225. static getContext() {
  28226. if ( _context === undefined ) {
  28227. _context = new ( window.AudioContext || window.webkitAudioContext )();
  28228. }
  28229. return _context;
  28230. }
  28231. static setContext( value ) {
  28232. _context = value;
  28233. }
  28234. }
  28235. class AudioLoader extends Loader {
  28236. constructor( manager ) {
  28237. super( manager );
  28238. }
  28239. load( url, onLoad, onProgress, onError ) {
  28240. const scope = this;
  28241. const loader = new FileLoader( this.manager );
  28242. loader.setResponseType( 'arraybuffer' );
  28243. loader.setPath( this.path );
  28244. loader.setRequestHeader( this.requestHeader );
  28245. loader.setWithCredentials( this.withCredentials );
  28246. loader.load( url, function ( buffer ) {
  28247. try {
  28248. // Create a copy of the buffer. The `decodeAudioData` method
  28249. // detaches the buffer when complete, preventing reuse.
  28250. const bufferCopy = buffer.slice( 0 );
  28251. const context = AudioContext.getContext();
  28252. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  28253. onLoad( audioBuffer );
  28254. } ).catch( handleError );
  28255. } catch ( e ) {
  28256. handleError( e );
  28257. }
  28258. }, onProgress, onError );
  28259. function handleError( e ) {
  28260. if ( onError ) {
  28261. onError( e );
  28262. } else {
  28263. console.error( e );
  28264. }
  28265. scope.manager.itemError( url );
  28266. }
  28267. }
  28268. }
  28269. const _eyeRight = /*@__PURE__*/ new Matrix4();
  28270. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  28271. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  28272. class StereoCamera {
  28273. constructor() {
  28274. this.type = 'StereoCamera';
  28275. this.aspect = 1;
  28276. this.eyeSep = 0.064;
  28277. this.cameraL = new PerspectiveCamera();
  28278. this.cameraL.layers.enable( 1 );
  28279. this.cameraL.matrixAutoUpdate = false;
  28280. this.cameraR = new PerspectiveCamera();
  28281. this.cameraR.layers.enable( 2 );
  28282. this.cameraR.matrixAutoUpdate = false;
  28283. this._cache = {
  28284. focus: null,
  28285. fov: null,
  28286. aspect: null,
  28287. near: null,
  28288. far: null,
  28289. zoom: null,
  28290. eyeSep: null
  28291. };
  28292. }
  28293. update( camera ) {
  28294. const cache = this._cache;
  28295. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  28296. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  28297. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  28298. if ( needsUpdate ) {
  28299. cache.focus = camera.focus;
  28300. cache.fov = camera.fov;
  28301. cache.aspect = camera.aspect * this.aspect;
  28302. cache.near = camera.near;
  28303. cache.far = camera.far;
  28304. cache.zoom = camera.zoom;
  28305. cache.eyeSep = this.eyeSep;
  28306. // Off-axis stereoscopic effect based on
  28307. // http://paulbourke.net/stereographics/stereorender/
  28308. _projectionMatrix.copy( camera.projectionMatrix );
  28309. const eyeSepHalf = cache.eyeSep / 2;
  28310. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  28311. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  28312. let xmin, xmax;
  28313. // translate xOffset
  28314. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  28315. _eyeRight.elements[ 12 ] = eyeSepHalf;
  28316. // for left eye
  28317. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  28318. xmax = ymax * cache.aspect + eyeSepOnProjection;
  28319. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28320. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28321. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  28322. // for right eye
  28323. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  28324. xmax = ymax * cache.aspect - eyeSepOnProjection;
  28325. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28326. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28327. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  28328. }
  28329. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  28330. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  28331. }
  28332. }
  28333. class Clock {
  28334. constructor( autoStart = true ) {
  28335. this.autoStart = autoStart;
  28336. this.startTime = 0;
  28337. this.oldTime = 0;
  28338. this.elapsedTime = 0;
  28339. this.running = false;
  28340. }
  28341. start() {
  28342. this.startTime = now();
  28343. this.oldTime = this.startTime;
  28344. this.elapsedTime = 0;
  28345. this.running = true;
  28346. }
  28347. stop() {
  28348. this.getElapsedTime();
  28349. this.running = false;
  28350. this.autoStart = false;
  28351. }
  28352. getElapsedTime() {
  28353. this.getDelta();
  28354. return this.elapsedTime;
  28355. }
  28356. getDelta() {
  28357. let diff = 0;
  28358. if ( this.autoStart && ! this.running ) {
  28359. this.start();
  28360. return 0;
  28361. }
  28362. if ( this.running ) {
  28363. const newTime = now();
  28364. diff = ( newTime - this.oldTime ) / 1000;
  28365. this.oldTime = newTime;
  28366. this.elapsedTime += diff;
  28367. }
  28368. return diff;
  28369. }
  28370. }
  28371. function now() {
  28372. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  28373. }
  28374. const _position$1 = /*@__PURE__*/ new Vector3();
  28375. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  28376. const _scale$1 = /*@__PURE__*/ new Vector3();
  28377. const _orientation$1 = /*@__PURE__*/ new Vector3();
  28378. class AudioListener extends Object3D {
  28379. constructor() {
  28380. super();
  28381. this.type = 'AudioListener';
  28382. this.context = AudioContext.getContext();
  28383. this.gain = this.context.createGain();
  28384. this.gain.connect( this.context.destination );
  28385. this.filter = null;
  28386. this.timeDelta = 0;
  28387. // private
  28388. this._clock = new Clock();
  28389. }
  28390. getInput() {
  28391. return this.gain;
  28392. }
  28393. removeFilter() {
  28394. if ( this.filter !== null ) {
  28395. this.gain.disconnect( this.filter );
  28396. this.filter.disconnect( this.context.destination );
  28397. this.gain.connect( this.context.destination );
  28398. this.filter = null;
  28399. }
  28400. return this;
  28401. }
  28402. getFilter() {
  28403. return this.filter;
  28404. }
  28405. setFilter( value ) {
  28406. if ( this.filter !== null ) {
  28407. this.gain.disconnect( this.filter );
  28408. this.filter.disconnect( this.context.destination );
  28409. } else {
  28410. this.gain.disconnect( this.context.destination );
  28411. }
  28412. this.filter = value;
  28413. this.gain.connect( this.filter );
  28414. this.filter.connect( this.context.destination );
  28415. return this;
  28416. }
  28417. getMasterVolume() {
  28418. return this.gain.gain.value;
  28419. }
  28420. setMasterVolume( value ) {
  28421. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28422. return this;
  28423. }
  28424. updateMatrixWorld( force ) {
  28425. super.updateMatrixWorld( force );
  28426. const listener = this.context.listener;
  28427. const up = this.up;
  28428. this.timeDelta = this._clock.getDelta();
  28429. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  28430. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  28431. if ( listener.positionX ) {
  28432. // code path for Chrome (see #14393)
  28433. const endTime = this.context.currentTime + this.timeDelta;
  28434. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  28435. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  28436. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  28437. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  28438. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  28439. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  28440. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28441. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28442. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28443. } else {
  28444. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  28445. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  28446. }
  28447. }
  28448. }
  28449. class Audio extends Object3D {
  28450. constructor( listener ) {
  28451. super();
  28452. this.type = 'Audio';
  28453. this.listener = listener;
  28454. this.context = listener.context;
  28455. this.gain = this.context.createGain();
  28456. this.gain.connect( listener.getInput() );
  28457. this.autoplay = false;
  28458. this.buffer = null;
  28459. this.detune = 0;
  28460. this.loop = false;
  28461. this.loopStart = 0;
  28462. this.loopEnd = 0;
  28463. this.offset = 0;
  28464. this.duration = undefined;
  28465. this.playbackRate = 1;
  28466. this.isPlaying = false;
  28467. this.hasPlaybackControl = true;
  28468. this.source = null;
  28469. this.sourceType = 'empty';
  28470. this._startedAt = 0;
  28471. this._progress = 0;
  28472. this._connected = false;
  28473. this.filters = [];
  28474. }
  28475. getOutput() {
  28476. return this.gain;
  28477. }
  28478. setNodeSource( audioNode ) {
  28479. this.hasPlaybackControl = false;
  28480. this.sourceType = 'audioNode';
  28481. this.source = audioNode;
  28482. this.connect();
  28483. return this;
  28484. }
  28485. setMediaElementSource( mediaElement ) {
  28486. this.hasPlaybackControl = false;
  28487. this.sourceType = 'mediaNode';
  28488. this.source = this.context.createMediaElementSource( mediaElement );
  28489. this.connect();
  28490. return this;
  28491. }
  28492. setMediaStreamSource( mediaStream ) {
  28493. this.hasPlaybackControl = false;
  28494. this.sourceType = 'mediaStreamNode';
  28495. this.source = this.context.createMediaStreamSource( mediaStream );
  28496. this.connect();
  28497. return this;
  28498. }
  28499. setBuffer( audioBuffer ) {
  28500. this.buffer = audioBuffer;
  28501. this.sourceType = 'buffer';
  28502. if ( this.autoplay ) this.play();
  28503. return this;
  28504. }
  28505. play( delay = 0 ) {
  28506. if ( this.isPlaying === true ) {
  28507. console.warn( 'THREE.Audio: Audio is already playing.' );
  28508. return;
  28509. }
  28510. if ( this.hasPlaybackControl === false ) {
  28511. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28512. return;
  28513. }
  28514. this._startedAt = this.context.currentTime + delay;
  28515. const source = this.context.createBufferSource();
  28516. source.buffer = this.buffer;
  28517. source.loop = this.loop;
  28518. source.loopStart = this.loopStart;
  28519. source.loopEnd = this.loopEnd;
  28520. source.onended = this.onEnded.bind( this );
  28521. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28522. this.isPlaying = true;
  28523. this.source = source;
  28524. this.setDetune( this.detune );
  28525. this.setPlaybackRate( this.playbackRate );
  28526. return this.connect();
  28527. }
  28528. pause() {
  28529. if ( this.hasPlaybackControl === false ) {
  28530. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28531. return;
  28532. }
  28533. if ( this.isPlaying === true ) {
  28534. // update current progress
  28535. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28536. if ( this.loop === true ) {
  28537. // ensure _progress does not exceed duration with looped audios
  28538. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28539. }
  28540. this.source.stop();
  28541. this.source.onended = null;
  28542. this.isPlaying = false;
  28543. }
  28544. return this;
  28545. }
  28546. stop() {
  28547. if ( this.hasPlaybackControl === false ) {
  28548. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28549. return;
  28550. }
  28551. this._progress = 0;
  28552. if ( this.source !== null ) {
  28553. this.source.stop();
  28554. this.source.onended = null;
  28555. }
  28556. this.isPlaying = false;
  28557. return this;
  28558. }
  28559. connect() {
  28560. if ( this.filters.length > 0 ) {
  28561. this.source.connect( this.filters[ 0 ] );
  28562. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28563. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28564. }
  28565. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28566. } else {
  28567. this.source.connect( this.getOutput() );
  28568. }
  28569. this._connected = true;
  28570. return this;
  28571. }
  28572. disconnect() {
  28573. if ( this._connected === false ) {
  28574. return;
  28575. }
  28576. if ( this.filters.length > 0 ) {
  28577. this.source.disconnect( this.filters[ 0 ] );
  28578. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28579. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28580. }
  28581. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28582. } else {
  28583. this.source.disconnect( this.getOutput() );
  28584. }
  28585. this._connected = false;
  28586. return this;
  28587. }
  28588. getFilters() {
  28589. return this.filters;
  28590. }
  28591. setFilters( value ) {
  28592. if ( ! value ) value = [];
  28593. if ( this._connected === true ) {
  28594. this.disconnect();
  28595. this.filters = value.slice();
  28596. this.connect();
  28597. } else {
  28598. this.filters = value.slice();
  28599. }
  28600. return this;
  28601. }
  28602. setDetune( value ) {
  28603. this.detune = value;
  28604. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28605. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28606. }
  28607. return this;
  28608. }
  28609. getDetune() {
  28610. return this.detune;
  28611. }
  28612. getFilter() {
  28613. return this.getFilters()[ 0 ];
  28614. }
  28615. setFilter( filter ) {
  28616. return this.setFilters( filter ? [ filter ] : [] );
  28617. }
  28618. setPlaybackRate( value ) {
  28619. if ( this.hasPlaybackControl === false ) {
  28620. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28621. return;
  28622. }
  28623. this.playbackRate = value;
  28624. if ( this.isPlaying === true ) {
  28625. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28626. }
  28627. return this;
  28628. }
  28629. getPlaybackRate() {
  28630. return this.playbackRate;
  28631. }
  28632. onEnded() {
  28633. this.isPlaying = false;
  28634. }
  28635. getLoop() {
  28636. if ( this.hasPlaybackControl === false ) {
  28637. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28638. return false;
  28639. }
  28640. return this.loop;
  28641. }
  28642. setLoop( value ) {
  28643. if ( this.hasPlaybackControl === false ) {
  28644. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28645. return;
  28646. }
  28647. this.loop = value;
  28648. if ( this.isPlaying === true ) {
  28649. this.source.loop = this.loop;
  28650. }
  28651. return this;
  28652. }
  28653. setLoopStart( value ) {
  28654. this.loopStart = value;
  28655. return this;
  28656. }
  28657. setLoopEnd( value ) {
  28658. this.loopEnd = value;
  28659. return this;
  28660. }
  28661. getVolume() {
  28662. return this.gain.gain.value;
  28663. }
  28664. setVolume( value ) {
  28665. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28666. return this;
  28667. }
  28668. }
  28669. const _position = /*@__PURE__*/ new Vector3();
  28670. const _quaternion = /*@__PURE__*/ new Quaternion();
  28671. const _scale = /*@__PURE__*/ new Vector3();
  28672. const _orientation = /*@__PURE__*/ new Vector3();
  28673. class PositionalAudio extends Audio {
  28674. constructor( listener ) {
  28675. super( listener );
  28676. this.panner = this.context.createPanner();
  28677. this.panner.panningModel = 'HRTF';
  28678. this.panner.connect( this.gain );
  28679. }
  28680. connect() {
  28681. super.connect();
  28682. this.panner.connect( this.gain );
  28683. }
  28684. disconnect() {
  28685. super.disconnect();
  28686. this.panner.disconnect( this.gain );
  28687. }
  28688. getOutput() {
  28689. return this.panner;
  28690. }
  28691. getRefDistance() {
  28692. return this.panner.refDistance;
  28693. }
  28694. setRefDistance( value ) {
  28695. this.panner.refDistance = value;
  28696. return this;
  28697. }
  28698. getRolloffFactor() {
  28699. return this.panner.rolloffFactor;
  28700. }
  28701. setRolloffFactor( value ) {
  28702. this.panner.rolloffFactor = value;
  28703. return this;
  28704. }
  28705. getDistanceModel() {
  28706. return this.panner.distanceModel;
  28707. }
  28708. setDistanceModel( value ) {
  28709. this.panner.distanceModel = value;
  28710. return this;
  28711. }
  28712. getMaxDistance() {
  28713. return this.panner.maxDistance;
  28714. }
  28715. setMaxDistance( value ) {
  28716. this.panner.maxDistance = value;
  28717. return this;
  28718. }
  28719. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28720. this.panner.coneInnerAngle = coneInnerAngle;
  28721. this.panner.coneOuterAngle = coneOuterAngle;
  28722. this.panner.coneOuterGain = coneOuterGain;
  28723. return this;
  28724. }
  28725. updateMatrixWorld( force ) {
  28726. super.updateMatrixWorld( force );
  28727. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28728. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28729. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28730. const panner = this.panner;
  28731. if ( panner.positionX ) {
  28732. // code path for Chrome and Firefox (see #14393)
  28733. const endTime = this.context.currentTime + this.listener.timeDelta;
  28734. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28735. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28736. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28737. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28738. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28739. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28740. } else {
  28741. panner.setPosition( _position.x, _position.y, _position.z );
  28742. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28743. }
  28744. }
  28745. }
  28746. class AudioAnalyser {
  28747. constructor( audio, fftSize = 2048 ) {
  28748. this.analyser = audio.context.createAnalyser();
  28749. this.analyser.fftSize = fftSize;
  28750. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28751. audio.getOutput().connect( this.analyser );
  28752. }
  28753. getFrequencyData() {
  28754. this.analyser.getByteFrequencyData( this.data );
  28755. return this.data;
  28756. }
  28757. getAverageFrequency() {
  28758. let value = 0;
  28759. const data = this.getFrequencyData();
  28760. for ( let i = 0; i < data.length; i ++ ) {
  28761. value += data[ i ];
  28762. }
  28763. return value / data.length;
  28764. }
  28765. }
  28766. class PropertyMixer {
  28767. constructor( binding, typeName, valueSize ) {
  28768. this.binding = binding;
  28769. this.valueSize = valueSize;
  28770. let mixFunction,
  28771. mixFunctionAdditive,
  28772. setIdentity;
  28773. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28774. //
  28775. // interpolators can use .buffer as their .result
  28776. // the data then goes to 'incoming'
  28777. //
  28778. // 'accu0' and 'accu1' are used frame-interleaved for
  28779. // the cumulative result and are compared to detect
  28780. // changes
  28781. //
  28782. // 'orig' stores the original state of the property
  28783. //
  28784. // 'add' is used for additive cumulative results
  28785. //
  28786. // 'work' is optional and is only present for quaternion types. It is used
  28787. // to store intermediate quaternion multiplication results
  28788. switch ( typeName ) {
  28789. case 'quaternion':
  28790. mixFunction = this._slerp;
  28791. mixFunctionAdditive = this._slerpAdditive;
  28792. setIdentity = this._setAdditiveIdentityQuaternion;
  28793. this.buffer = new Float64Array( valueSize * 6 );
  28794. this._workIndex = 5;
  28795. break;
  28796. case 'string':
  28797. case 'bool':
  28798. mixFunction = this._select;
  28799. // Use the regular mix function and for additive on these types,
  28800. // additive is not relevant for non-numeric types
  28801. mixFunctionAdditive = this._select;
  28802. setIdentity = this._setAdditiveIdentityOther;
  28803. this.buffer = new Array( valueSize * 5 );
  28804. break;
  28805. default:
  28806. mixFunction = this._lerp;
  28807. mixFunctionAdditive = this._lerpAdditive;
  28808. setIdentity = this._setAdditiveIdentityNumeric;
  28809. this.buffer = new Float64Array( valueSize * 5 );
  28810. }
  28811. this._mixBufferRegion = mixFunction;
  28812. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28813. this._setIdentity = setIdentity;
  28814. this._origIndex = 3;
  28815. this._addIndex = 4;
  28816. this.cumulativeWeight = 0;
  28817. this.cumulativeWeightAdditive = 0;
  28818. this.useCount = 0;
  28819. this.referenceCount = 0;
  28820. }
  28821. // accumulate data in the 'incoming' region into 'accu<i>'
  28822. accumulate( accuIndex, weight ) {
  28823. // note: happily accumulating nothing when weight = 0, the caller knows
  28824. // the weight and shouldn't have made the call in the first place
  28825. const buffer = this.buffer,
  28826. stride = this.valueSize,
  28827. offset = accuIndex * stride + stride;
  28828. let currentWeight = this.cumulativeWeight;
  28829. if ( currentWeight === 0 ) {
  28830. // accuN := incoming * weight
  28831. for ( let i = 0; i !== stride; ++ i ) {
  28832. buffer[ offset + i ] = buffer[ i ];
  28833. }
  28834. currentWeight = weight;
  28835. } else {
  28836. // accuN := accuN + incoming * weight
  28837. currentWeight += weight;
  28838. const mix = weight / currentWeight;
  28839. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28840. }
  28841. this.cumulativeWeight = currentWeight;
  28842. }
  28843. // accumulate data in the 'incoming' region into 'add'
  28844. accumulateAdditive( weight ) {
  28845. const buffer = this.buffer,
  28846. stride = this.valueSize,
  28847. offset = stride * this._addIndex;
  28848. if ( this.cumulativeWeightAdditive === 0 ) {
  28849. // add = identity
  28850. this._setIdentity();
  28851. }
  28852. // add := add + incoming * weight
  28853. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28854. this.cumulativeWeightAdditive += weight;
  28855. }
  28856. // apply the state of 'accu<i>' to the binding when accus differ
  28857. apply( accuIndex ) {
  28858. const stride = this.valueSize,
  28859. buffer = this.buffer,
  28860. offset = accuIndex * stride + stride,
  28861. weight = this.cumulativeWeight,
  28862. weightAdditive = this.cumulativeWeightAdditive,
  28863. binding = this.binding;
  28864. this.cumulativeWeight = 0;
  28865. this.cumulativeWeightAdditive = 0;
  28866. if ( weight < 1 ) {
  28867. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28868. const originalValueOffset = stride * this._origIndex;
  28869. this._mixBufferRegion(
  28870. buffer, offset, originalValueOffset, 1 - weight, stride );
  28871. }
  28872. if ( weightAdditive > 0 ) {
  28873. // accuN := accuN + additive accuN
  28874. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28875. }
  28876. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28877. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28878. // value has changed -> update scene graph
  28879. binding.setValue( buffer, offset );
  28880. break;
  28881. }
  28882. }
  28883. }
  28884. // remember the state of the bound property and copy it to both accus
  28885. saveOriginalState() {
  28886. const binding = this.binding;
  28887. const buffer = this.buffer,
  28888. stride = this.valueSize,
  28889. originalValueOffset = stride * this._origIndex;
  28890. binding.getValue( buffer, originalValueOffset );
  28891. // accu[0..1] := orig -- initially detect changes against the original
  28892. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28893. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28894. }
  28895. // Add to identity for additive
  28896. this._setIdentity();
  28897. this.cumulativeWeight = 0;
  28898. this.cumulativeWeightAdditive = 0;
  28899. }
  28900. // apply the state previously taken via 'saveOriginalState' to the binding
  28901. restoreOriginalState() {
  28902. const originalValueOffset = this.valueSize * 3;
  28903. this.binding.setValue( this.buffer, originalValueOffset );
  28904. }
  28905. _setAdditiveIdentityNumeric() {
  28906. const startIndex = this._addIndex * this.valueSize;
  28907. const endIndex = startIndex + this.valueSize;
  28908. for ( let i = startIndex; i < endIndex; i ++ ) {
  28909. this.buffer[ i ] = 0;
  28910. }
  28911. }
  28912. _setAdditiveIdentityQuaternion() {
  28913. this._setAdditiveIdentityNumeric();
  28914. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28915. }
  28916. _setAdditiveIdentityOther() {
  28917. const startIndex = this._origIndex * this.valueSize;
  28918. const targetIndex = this._addIndex * this.valueSize;
  28919. for ( let i = 0; i < this.valueSize; i ++ ) {
  28920. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28921. }
  28922. }
  28923. // mix functions
  28924. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28925. if ( t >= 0.5 ) {
  28926. for ( let i = 0; i !== stride; ++ i ) {
  28927. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28928. }
  28929. }
  28930. }
  28931. _slerp( buffer, dstOffset, srcOffset, t ) {
  28932. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28933. }
  28934. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28935. const workOffset = this._workIndex * stride;
  28936. // Store result in intermediate buffer offset
  28937. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  28938. // Slerp to the intermediate result
  28939. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  28940. }
  28941. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  28942. const s = 1 - t;
  28943. for ( let i = 0; i !== stride; ++ i ) {
  28944. const j = dstOffset + i;
  28945. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28946. }
  28947. }
  28948. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28949. for ( let i = 0; i !== stride; ++ i ) {
  28950. const j = dstOffset + i;
  28951. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  28952. }
  28953. }
  28954. }
  28955. // Characters [].:/ are reserved for track binding syntax.
  28956. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28957. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  28958. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28959. // only latin characters, and the unicode \p{L} is not yet supported. So
  28960. // instead, we exclude reserved characters and match everything else.
  28961. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  28962. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28963. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28964. // be matched to parse the rest of the track name.
  28965. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  28966. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28967. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  28968. // Object on target node, and accessor. May not contain reserved
  28969. // characters. Accessor may contain any character except closing bracket.
  28970. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  28971. // Property and accessor. May not contain reserved characters. Accessor may
  28972. // contain any non-bracket characters.
  28973. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  28974. const _trackRe = new RegExp( ''
  28975. + '^'
  28976. + _directoryRe
  28977. + _nodeRe
  28978. + _objectRe
  28979. + _propertyRe
  28980. + '$'
  28981. );
  28982. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  28983. class Composite {
  28984. constructor( targetGroup, path, optionalParsedPath ) {
  28985. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28986. this._targetGroup = targetGroup;
  28987. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28988. }
  28989. getValue( array, offset ) {
  28990. this.bind(); // bind all binding
  28991. const firstValidIndex = this._targetGroup.nCachedObjects_,
  28992. binding = this._bindings[ firstValidIndex ];
  28993. // and only call .getValue on the first
  28994. if ( binding !== undefined ) binding.getValue( array, offset );
  28995. }
  28996. setValue( array, offset ) {
  28997. const bindings = this._bindings;
  28998. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28999. bindings[ i ].setValue( array, offset );
  29000. }
  29001. }
  29002. bind() {
  29003. const bindings = this._bindings;
  29004. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29005. bindings[ i ].bind();
  29006. }
  29007. }
  29008. unbind() {
  29009. const bindings = this._bindings;
  29010. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29011. bindings[ i ].unbind();
  29012. }
  29013. }
  29014. }
  29015. // Note: This class uses a State pattern on a per-method basis:
  29016. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  29017. // prototype version of these methods with one that represents
  29018. // the bound state. When the property is not found, the methods
  29019. // become no-ops.
  29020. class PropertyBinding {
  29021. constructor( rootNode, path, parsedPath ) {
  29022. this.path = path;
  29023. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  29024. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  29025. this.rootNode = rootNode;
  29026. // initial state of these methods that calls 'bind'
  29027. this.getValue = this._getValue_unbound;
  29028. this.setValue = this._setValue_unbound;
  29029. }
  29030. static create( root, path, parsedPath ) {
  29031. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  29032. return new PropertyBinding( root, path, parsedPath );
  29033. } else {
  29034. return new PropertyBinding.Composite( root, path, parsedPath );
  29035. }
  29036. }
  29037. /**
  29038. * Replaces spaces with underscores and removes unsupported characters from
  29039. * node names, to ensure compatibility with parseTrackName().
  29040. *
  29041. * @param {string} name Node name to be sanitized.
  29042. * @return {string}
  29043. */
  29044. static sanitizeNodeName( name ) {
  29045. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  29046. }
  29047. static parseTrackName( trackName ) {
  29048. const matches = _trackRe.exec( trackName );
  29049. if ( matches === null ) {
  29050. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  29051. }
  29052. const results = {
  29053. // directoryName: matches[ 1 ], // (tschw) currently unused
  29054. nodeName: matches[ 2 ],
  29055. objectName: matches[ 3 ],
  29056. objectIndex: matches[ 4 ],
  29057. propertyName: matches[ 5 ], // required
  29058. propertyIndex: matches[ 6 ]
  29059. };
  29060. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  29061. if ( lastDot !== undefined && lastDot !== - 1 ) {
  29062. const objectName = results.nodeName.substring( lastDot + 1 );
  29063. // Object names must be checked against an allowlist. Otherwise, there
  29064. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  29065. // 'bar' could be the objectName, or part of a nodeName (which can
  29066. // include '.' characters).
  29067. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  29068. results.nodeName = results.nodeName.substring( 0, lastDot );
  29069. results.objectName = objectName;
  29070. }
  29071. }
  29072. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  29073. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  29074. }
  29075. return results;
  29076. }
  29077. static findNode( root, nodeName ) {
  29078. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  29079. return root;
  29080. }
  29081. // search into skeleton bones.
  29082. if ( root.skeleton ) {
  29083. const bone = root.skeleton.getBoneByName( nodeName );
  29084. if ( bone !== undefined ) {
  29085. return bone;
  29086. }
  29087. }
  29088. // search into node subtree.
  29089. if ( root.children ) {
  29090. const searchNodeSubtree = function ( children ) {
  29091. for ( let i = 0; i < children.length; i ++ ) {
  29092. const childNode = children[ i ];
  29093. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  29094. return childNode;
  29095. }
  29096. const result = searchNodeSubtree( childNode.children );
  29097. if ( result ) return result;
  29098. }
  29099. return null;
  29100. };
  29101. const subTreeNode = searchNodeSubtree( root.children );
  29102. if ( subTreeNode ) {
  29103. return subTreeNode;
  29104. }
  29105. }
  29106. return null;
  29107. }
  29108. // these are used to "bind" a nonexistent property
  29109. _getValue_unavailable() {}
  29110. _setValue_unavailable() {}
  29111. // Getters
  29112. _getValue_direct( buffer, offset ) {
  29113. buffer[ offset ] = this.targetObject[ this.propertyName ];
  29114. }
  29115. _getValue_array( buffer, offset ) {
  29116. const source = this.resolvedProperty;
  29117. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  29118. buffer[ offset ++ ] = source[ i ];
  29119. }
  29120. }
  29121. _getValue_arrayElement( buffer, offset ) {
  29122. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  29123. }
  29124. _getValue_toArray( buffer, offset ) {
  29125. this.resolvedProperty.toArray( buffer, offset );
  29126. }
  29127. // Direct
  29128. _setValue_direct( buffer, offset ) {
  29129. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29130. }
  29131. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  29132. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29133. this.targetObject.needsUpdate = true;
  29134. }
  29135. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29136. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29137. this.targetObject.matrixWorldNeedsUpdate = true;
  29138. }
  29139. // EntireArray
  29140. _setValue_array( buffer, offset ) {
  29141. const dest = this.resolvedProperty;
  29142. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29143. dest[ i ] = buffer[ offset ++ ];
  29144. }
  29145. }
  29146. _setValue_array_setNeedsUpdate( buffer, offset ) {
  29147. const dest = this.resolvedProperty;
  29148. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29149. dest[ i ] = buffer[ offset ++ ];
  29150. }
  29151. this.targetObject.needsUpdate = true;
  29152. }
  29153. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29154. const dest = this.resolvedProperty;
  29155. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29156. dest[ i ] = buffer[ offset ++ ];
  29157. }
  29158. this.targetObject.matrixWorldNeedsUpdate = true;
  29159. }
  29160. // ArrayElement
  29161. _setValue_arrayElement( buffer, offset ) {
  29162. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29163. }
  29164. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  29165. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29166. this.targetObject.needsUpdate = true;
  29167. }
  29168. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29169. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29170. this.targetObject.matrixWorldNeedsUpdate = true;
  29171. }
  29172. // HasToFromArray
  29173. _setValue_fromArray( buffer, offset ) {
  29174. this.resolvedProperty.fromArray( buffer, offset );
  29175. }
  29176. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  29177. this.resolvedProperty.fromArray( buffer, offset );
  29178. this.targetObject.needsUpdate = true;
  29179. }
  29180. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29181. this.resolvedProperty.fromArray( buffer, offset );
  29182. this.targetObject.matrixWorldNeedsUpdate = true;
  29183. }
  29184. _getValue_unbound( targetArray, offset ) {
  29185. this.bind();
  29186. this.getValue( targetArray, offset );
  29187. }
  29188. _setValue_unbound( sourceArray, offset ) {
  29189. this.bind();
  29190. this.setValue( sourceArray, offset );
  29191. }
  29192. // create getter / setter pair for a property in the scene graph
  29193. bind() {
  29194. let targetObject = this.node;
  29195. const parsedPath = this.parsedPath;
  29196. const objectName = parsedPath.objectName;
  29197. const propertyName = parsedPath.propertyName;
  29198. let propertyIndex = parsedPath.propertyIndex;
  29199. if ( ! targetObject ) {
  29200. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  29201. this.node = targetObject;
  29202. }
  29203. // set fail state so we can just 'return' on error
  29204. this.getValue = this._getValue_unavailable;
  29205. this.setValue = this._setValue_unavailable;
  29206. // ensure there is a value node
  29207. if ( ! targetObject ) {
  29208. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  29209. return;
  29210. }
  29211. if ( objectName ) {
  29212. let objectIndex = parsedPath.objectIndex;
  29213. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29214. switch ( objectName ) {
  29215. case 'materials':
  29216. if ( ! targetObject.material ) {
  29217. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29218. return;
  29219. }
  29220. if ( ! targetObject.material.materials ) {
  29221. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29222. return;
  29223. }
  29224. targetObject = targetObject.material.materials;
  29225. break;
  29226. case 'bones':
  29227. if ( ! targetObject.skeleton ) {
  29228. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29229. return;
  29230. }
  29231. // potential future optimization: skip this if propertyIndex is already an integer
  29232. // and convert the integer string to a true integer.
  29233. targetObject = targetObject.skeleton.bones;
  29234. // support resolving morphTarget names into indices.
  29235. for ( let i = 0; i < targetObject.length; i ++ ) {
  29236. if ( targetObject[ i ].name === objectIndex ) {
  29237. objectIndex = i;
  29238. break;
  29239. }
  29240. }
  29241. break;
  29242. case 'map':
  29243. if ( 'map' in targetObject ) {
  29244. targetObject = targetObject.map;
  29245. break;
  29246. }
  29247. if ( ! targetObject.material ) {
  29248. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29249. return;
  29250. }
  29251. if ( ! targetObject.material.map ) {
  29252. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  29253. return;
  29254. }
  29255. targetObject = targetObject.material.map;
  29256. break;
  29257. default:
  29258. if ( targetObject[ objectName ] === undefined ) {
  29259. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29260. return;
  29261. }
  29262. targetObject = targetObject[ objectName ];
  29263. }
  29264. if ( objectIndex !== undefined ) {
  29265. if ( targetObject[ objectIndex ] === undefined ) {
  29266. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29267. return;
  29268. }
  29269. targetObject = targetObject[ objectIndex ];
  29270. }
  29271. }
  29272. // resolve property
  29273. const nodeProperty = targetObject[ propertyName ];
  29274. if ( nodeProperty === undefined ) {
  29275. const nodeName = parsedPath.nodeName;
  29276. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29277. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29278. return;
  29279. }
  29280. // determine versioning scheme
  29281. let versioning = this.Versioning.None;
  29282. this.targetObject = targetObject;
  29283. if ( targetObject.needsUpdate !== undefined ) { // material
  29284. versioning = this.Versioning.NeedsUpdate;
  29285. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  29286. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29287. }
  29288. // determine how the property gets bound
  29289. let bindingType = this.BindingType.Direct;
  29290. if ( propertyIndex !== undefined ) {
  29291. // access a sub element of the property array (only primitives are supported right now)
  29292. if ( propertyName === 'morphTargetInfluences' ) {
  29293. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29294. // support resolving morphTarget names into indices.
  29295. if ( ! targetObject.geometry ) {
  29296. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29297. return;
  29298. }
  29299. if ( ! targetObject.geometry.morphAttributes ) {
  29300. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29301. return;
  29302. }
  29303. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  29304. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  29305. }
  29306. }
  29307. bindingType = this.BindingType.ArrayElement;
  29308. this.resolvedProperty = nodeProperty;
  29309. this.propertyIndex = propertyIndex;
  29310. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29311. // must use copy for Object3D.Euler/Quaternion
  29312. bindingType = this.BindingType.HasFromToArray;
  29313. this.resolvedProperty = nodeProperty;
  29314. } else if ( Array.isArray( nodeProperty ) ) {
  29315. bindingType = this.BindingType.EntireArray;
  29316. this.resolvedProperty = nodeProperty;
  29317. } else {
  29318. this.propertyName = propertyName;
  29319. }
  29320. // select getter / setter
  29321. this.getValue = this.GetterByBindingType[ bindingType ];
  29322. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29323. }
  29324. unbind() {
  29325. this.node = null;
  29326. // back to the prototype version of getValue / setValue
  29327. // note: avoiding to mutate the shape of 'this' via 'delete'
  29328. this.getValue = this._getValue_unbound;
  29329. this.setValue = this._setValue_unbound;
  29330. }
  29331. }
  29332. PropertyBinding.Composite = Composite;
  29333. PropertyBinding.prototype.BindingType = {
  29334. Direct: 0,
  29335. EntireArray: 1,
  29336. ArrayElement: 2,
  29337. HasFromToArray: 3
  29338. };
  29339. PropertyBinding.prototype.Versioning = {
  29340. None: 0,
  29341. NeedsUpdate: 1,
  29342. MatrixWorldNeedsUpdate: 2
  29343. };
  29344. PropertyBinding.prototype.GetterByBindingType = [
  29345. PropertyBinding.prototype._getValue_direct,
  29346. PropertyBinding.prototype._getValue_array,
  29347. PropertyBinding.prototype._getValue_arrayElement,
  29348. PropertyBinding.prototype._getValue_toArray,
  29349. ];
  29350. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  29351. [
  29352. // Direct
  29353. PropertyBinding.prototype._setValue_direct,
  29354. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  29355. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  29356. ], [
  29357. // EntireArray
  29358. PropertyBinding.prototype._setValue_array,
  29359. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  29360. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  29361. ], [
  29362. // ArrayElement
  29363. PropertyBinding.prototype._setValue_arrayElement,
  29364. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  29365. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  29366. ], [
  29367. // HasToFromArray
  29368. PropertyBinding.prototype._setValue_fromArray,
  29369. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  29370. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  29371. ]
  29372. ];
  29373. /**
  29374. *
  29375. * A group of objects that receives a shared animation state.
  29376. *
  29377. * Usage:
  29378. *
  29379. * - Add objects you would otherwise pass as 'root' to the
  29380. * constructor or the .clipAction method of AnimationMixer.
  29381. *
  29382. * - Instead pass this object as 'root'.
  29383. *
  29384. * - You can also add and remove objects later when the mixer
  29385. * is running.
  29386. *
  29387. * Note:
  29388. *
  29389. * Objects of this class appear as one object to the mixer,
  29390. * so cache control of the individual objects must be done
  29391. * on the group.
  29392. *
  29393. * Limitation:
  29394. *
  29395. * - The animated properties must be compatible among the
  29396. * all objects in the group.
  29397. *
  29398. * - A single property can either be controlled through a
  29399. * target group or directly, but not both.
  29400. */
  29401. class AnimationObjectGroup {
  29402. constructor() {
  29403. this.isAnimationObjectGroup = true;
  29404. this.uuid = generateUUID();
  29405. // cached objects followed by the active ones
  29406. this._objects = Array.prototype.slice.call( arguments );
  29407. this.nCachedObjects_ = 0; // threshold
  29408. // note: read by PropertyBinding.Composite
  29409. const indices = {};
  29410. this._indicesByUUID = indices; // for bookkeeping
  29411. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29412. indices[ arguments[ i ].uuid ] = i;
  29413. }
  29414. this._paths = []; // inside: string
  29415. this._parsedPaths = []; // inside: { we don't care, here }
  29416. this._bindings = []; // inside: Array< PropertyBinding >
  29417. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29418. const scope = this;
  29419. this.stats = {
  29420. objects: {
  29421. get total() {
  29422. return scope._objects.length;
  29423. },
  29424. get inUse() {
  29425. return this.total - scope.nCachedObjects_;
  29426. }
  29427. },
  29428. get bindingsPerObject() {
  29429. return scope._bindings.length;
  29430. }
  29431. };
  29432. }
  29433. add() {
  29434. const objects = this._objects,
  29435. indicesByUUID = this._indicesByUUID,
  29436. paths = this._paths,
  29437. parsedPaths = this._parsedPaths,
  29438. bindings = this._bindings,
  29439. nBindings = bindings.length;
  29440. let knownObject = undefined,
  29441. nObjects = objects.length,
  29442. nCachedObjects = this.nCachedObjects_;
  29443. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29444. const object = arguments[ i ],
  29445. uuid = object.uuid;
  29446. let index = indicesByUUID[ uuid ];
  29447. if ( index === undefined ) {
  29448. // unknown object -> add it to the ACTIVE region
  29449. index = nObjects ++;
  29450. indicesByUUID[ uuid ] = index;
  29451. objects.push( object );
  29452. // accounting is done, now do the same for all bindings
  29453. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29454. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29455. }
  29456. } else if ( index < nCachedObjects ) {
  29457. knownObject = objects[ index ];
  29458. // move existing object to the ACTIVE region
  29459. const firstActiveIndex = -- nCachedObjects,
  29460. lastCachedObject = objects[ firstActiveIndex ];
  29461. indicesByUUID[ lastCachedObject.uuid ] = index;
  29462. objects[ index ] = lastCachedObject;
  29463. indicesByUUID[ uuid ] = firstActiveIndex;
  29464. objects[ firstActiveIndex ] = object;
  29465. // accounting is done, now do the same for all bindings
  29466. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29467. const bindingsForPath = bindings[ j ],
  29468. lastCached = bindingsForPath[ firstActiveIndex ];
  29469. let binding = bindingsForPath[ index ];
  29470. bindingsForPath[ index ] = lastCached;
  29471. if ( binding === undefined ) {
  29472. // since we do not bother to create new bindings
  29473. // for objects that are cached, the binding may
  29474. // or may not exist
  29475. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29476. }
  29477. bindingsForPath[ firstActiveIndex ] = binding;
  29478. }
  29479. } else if ( objects[ index ] !== knownObject ) {
  29480. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29481. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29482. } // else the object is already where we want it to be
  29483. } // for arguments
  29484. this.nCachedObjects_ = nCachedObjects;
  29485. }
  29486. remove() {
  29487. const objects = this._objects,
  29488. indicesByUUID = this._indicesByUUID,
  29489. bindings = this._bindings,
  29490. nBindings = bindings.length;
  29491. let nCachedObjects = this.nCachedObjects_;
  29492. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29493. const object = arguments[ i ],
  29494. uuid = object.uuid,
  29495. index = indicesByUUID[ uuid ];
  29496. if ( index !== undefined && index >= nCachedObjects ) {
  29497. // move existing object into the CACHED region
  29498. const lastCachedIndex = nCachedObjects ++,
  29499. firstActiveObject = objects[ lastCachedIndex ];
  29500. indicesByUUID[ firstActiveObject.uuid ] = index;
  29501. objects[ index ] = firstActiveObject;
  29502. indicesByUUID[ uuid ] = lastCachedIndex;
  29503. objects[ lastCachedIndex ] = object;
  29504. // accounting is done, now do the same for all bindings
  29505. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29506. const bindingsForPath = bindings[ j ],
  29507. firstActive = bindingsForPath[ lastCachedIndex ],
  29508. binding = bindingsForPath[ index ];
  29509. bindingsForPath[ index ] = firstActive;
  29510. bindingsForPath[ lastCachedIndex ] = binding;
  29511. }
  29512. }
  29513. } // for arguments
  29514. this.nCachedObjects_ = nCachedObjects;
  29515. }
  29516. // remove & forget
  29517. uncache() {
  29518. const objects = this._objects,
  29519. indicesByUUID = this._indicesByUUID,
  29520. bindings = this._bindings,
  29521. nBindings = bindings.length;
  29522. let nCachedObjects = this.nCachedObjects_,
  29523. nObjects = objects.length;
  29524. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29525. const object = arguments[ i ],
  29526. uuid = object.uuid,
  29527. index = indicesByUUID[ uuid ];
  29528. if ( index !== undefined ) {
  29529. delete indicesByUUID[ uuid ];
  29530. if ( index < nCachedObjects ) {
  29531. // object is cached, shrink the CACHED region
  29532. const firstActiveIndex = -- nCachedObjects,
  29533. lastCachedObject = objects[ firstActiveIndex ],
  29534. lastIndex = -- nObjects,
  29535. lastObject = objects[ lastIndex ];
  29536. // last cached object takes this object's place
  29537. indicesByUUID[ lastCachedObject.uuid ] = index;
  29538. objects[ index ] = lastCachedObject;
  29539. // last object goes to the activated slot and pop
  29540. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29541. objects[ firstActiveIndex ] = lastObject;
  29542. objects.pop();
  29543. // accounting is done, now do the same for all bindings
  29544. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29545. const bindingsForPath = bindings[ j ],
  29546. lastCached = bindingsForPath[ firstActiveIndex ],
  29547. last = bindingsForPath[ lastIndex ];
  29548. bindingsForPath[ index ] = lastCached;
  29549. bindingsForPath[ firstActiveIndex ] = last;
  29550. bindingsForPath.pop();
  29551. }
  29552. } else {
  29553. // object is active, just swap with the last and pop
  29554. const lastIndex = -- nObjects,
  29555. lastObject = objects[ lastIndex ];
  29556. if ( lastIndex > 0 ) {
  29557. indicesByUUID[ lastObject.uuid ] = index;
  29558. }
  29559. objects[ index ] = lastObject;
  29560. objects.pop();
  29561. // accounting is done, now do the same for all bindings
  29562. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29563. const bindingsForPath = bindings[ j ];
  29564. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29565. bindingsForPath.pop();
  29566. }
  29567. } // cached or active
  29568. } // if object is known
  29569. } // for arguments
  29570. this.nCachedObjects_ = nCachedObjects;
  29571. }
  29572. // Internal interface used by befriended PropertyBinding.Composite:
  29573. subscribe_( path, parsedPath ) {
  29574. // returns an array of bindings for the given path that is changed
  29575. // according to the contained objects in the group
  29576. const indicesByPath = this._bindingsIndicesByPath;
  29577. let index = indicesByPath[ path ];
  29578. const bindings = this._bindings;
  29579. if ( index !== undefined ) return bindings[ index ];
  29580. const paths = this._paths,
  29581. parsedPaths = this._parsedPaths,
  29582. objects = this._objects,
  29583. nObjects = objects.length,
  29584. nCachedObjects = this.nCachedObjects_,
  29585. bindingsForPath = new Array( nObjects );
  29586. index = bindings.length;
  29587. indicesByPath[ path ] = index;
  29588. paths.push( path );
  29589. parsedPaths.push( parsedPath );
  29590. bindings.push( bindingsForPath );
  29591. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29592. const object = objects[ i ];
  29593. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29594. }
  29595. return bindingsForPath;
  29596. }
  29597. unsubscribe_( path ) {
  29598. // tells the group to forget about a property path and no longer
  29599. // update the array previously obtained with 'subscribe_'
  29600. const indicesByPath = this._bindingsIndicesByPath,
  29601. index = indicesByPath[ path ];
  29602. if ( index !== undefined ) {
  29603. const paths = this._paths,
  29604. parsedPaths = this._parsedPaths,
  29605. bindings = this._bindings,
  29606. lastBindingsIndex = bindings.length - 1,
  29607. lastBindings = bindings[ lastBindingsIndex ],
  29608. lastBindingsPath = path[ lastBindingsIndex ];
  29609. indicesByPath[ lastBindingsPath ] = index;
  29610. bindings[ index ] = lastBindings;
  29611. bindings.pop();
  29612. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29613. parsedPaths.pop();
  29614. paths[ index ] = paths[ lastBindingsIndex ];
  29615. paths.pop();
  29616. }
  29617. }
  29618. }
  29619. class AnimationAction {
  29620. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29621. this._mixer = mixer;
  29622. this._clip = clip;
  29623. this._localRoot = localRoot;
  29624. this.blendMode = blendMode;
  29625. const tracks = clip.tracks,
  29626. nTracks = tracks.length,
  29627. interpolants = new Array( nTracks );
  29628. const interpolantSettings = {
  29629. endingStart: ZeroCurvatureEnding,
  29630. endingEnd: ZeroCurvatureEnding
  29631. };
  29632. for ( let i = 0; i !== nTracks; ++ i ) {
  29633. const interpolant = tracks[ i ].createInterpolant( null );
  29634. interpolants[ i ] = interpolant;
  29635. interpolant.settings = interpolantSettings;
  29636. }
  29637. this._interpolantSettings = interpolantSettings;
  29638. this._interpolants = interpolants; // bound by the mixer
  29639. // inside: PropertyMixer (managed by the mixer)
  29640. this._propertyBindings = new Array( nTracks );
  29641. this._cacheIndex = null; // for the memory manager
  29642. this._byClipCacheIndex = null; // for the memory manager
  29643. this._timeScaleInterpolant = null;
  29644. this._weightInterpolant = null;
  29645. this.loop = LoopRepeat;
  29646. this._loopCount = - 1;
  29647. // global mixer time when the action is to be started
  29648. // it's set back to 'null' upon start of the action
  29649. this._startTime = null;
  29650. // scaled local time of the action
  29651. // gets clamped or wrapped to 0..clip.duration according to loop
  29652. this.time = 0;
  29653. this.timeScale = 1;
  29654. this._effectiveTimeScale = 1;
  29655. this.weight = 1;
  29656. this._effectiveWeight = 1;
  29657. this.repetitions = Infinity; // no. of repetitions when looping
  29658. this.paused = false; // true -> zero effective time scale
  29659. this.enabled = true; // false -> zero effective weight
  29660. this.clampWhenFinished = false;// keep feeding the last frame?
  29661. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29662. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29663. }
  29664. // State & Scheduling
  29665. play() {
  29666. this._mixer._activateAction( this );
  29667. return this;
  29668. }
  29669. stop() {
  29670. this._mixer._deactivateAction( this );
  29671. return this.reset();
  29672. }
  29673. reset() {
  29674. this.paused = false;
  29675. this.enabled = true;
  29676. this.time = 0; // restart clip
  29677. this._loopCount = - 1;// forget previous loops
  29678. this._startTime = null;// forget scheduling
  29679. return this.stopFading().stopWarping();
  29680. }
  29681. isRunning() {
  29682. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29683. this._startTime === null && this._mixer._isActiveAction( this );
  29684. }
  29685. // return true when play has been called
  29686. isScheduled() {
  29687. return this._mixer._isActiveAction( this );
  29688. }
  29689. startAt( time ) {
  29690. this._startTime = time;
  29691. return this;
  29692. }
  29693. setLoop( mode, repetitions ) {
  29694. this.loop = mode;
  29695. this.repetitions = repetitions;
  29696. return this;
  29697. }
  29698. // Weight
  29699. // set the weight stopping any scheduled fading
  29700. // although .enabled = false yields an effective weight of zero, this
  29701. // method does *not* change .enabled, because it would be confusing
  29702. setEffectiveWeight( weight ) {
  29703. this.weight = weight;
  29704. // note: same logic as when updated at runtime
  29705. this._effectiveWeight = this.enabled ? weight : 0;
  29706. return this.stopFading();
  29707. }
  29708. // return the weight considering fading and .enabled
  29709. getEffectiveWeight() {
  29710. return this._effectiveWeight;
  29711. }
  29712. fadeIn( duration ) {
  29713. return this._scheduleFading( duration, 0, 1 );
  29714. }
  29715. fadeOut( duration ) {
  29716. return this._scheduleFading( duration, 1, 0 );
  29717. }
  29718. crossFadeFrom( fadeOutAction, duration, warp ) {
  29719. fadeOutAction.fadeOut( duration );
  29720. this.fadeIn( duration );
  29721. if ( warp ) {
  29722. const fadeInDuration = this._clip.duration,
  29723. fadeOutDuration = fadeOutAction._clip.duration,
  29724. startEndRatio = fadeOutDuration / fadeInDuration,
  29725. endStartRatio = fadeInDuration / fadeOutDuration;
  29726. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29727. this.warp( endStartRatio, 1.0, duration );
  29728. }
  29729. return this;
  29730. }
  29731. crossFadeTo( fadeInAction, duration, warp ) {
  29732. return fadeInAction.crossFadeFrom( this, duration, warp );
  29733. }
  29734. stopFading() {
  29735. const weightInterpolant = this._weightInterpolant;
  29736. if ( weightInterpolant !== null ) {
  29737. this._weightInterpolant = null;
  29738. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29739. }
  29740. return this;
  29741. }
  29742. // Time Scale Control
  29743. // set the time scale stopping any scheduled warping
  29744. // although .paused = true yields an effective time scale of zero, this
  29745. // method does *not* change .paused, because it would be confusing
  29746. setEffectiveTimeScale( timeScale ) {
  29747. this.timeScale = timeScale;
  29748. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29749. return this.stopWarping();
  29750. }
  29751. // return the time scale considering warping and .paused
  29752. getEffectiveTimeScale() {
  29753. return this._effectiveTimeScale;
  29754. }
  29755. setDuration( duration ) {
  29756. this.timeScale = this._clip.duration / duration;
  29757. return this.stopWarping();
  29758. }
  29759. syncWith( action ) {
  29760. this.time = action.time;
  29761. this.timeScale = action.timeScale;
  29762. return this.stopWarping();
  29763. }
  29764. halt( duration ) {
  29765. return this.warp( this._effectiveTimeScale, 0, duration );
  29766. }
  29767. warp( startTimeScale, endTimeScale, duration ) {
  29768. const mixer = this._mixer,
  29769. now = mixer.time,
  29770. timeScale = this.timeScale;
  29771. let interpolant = this._timeScaleInterpolant;
  29772. if ( interpolant === null ) {
  29773. interpolant = mixer._lendControlInterpolant();
  29774. this._timeScaleInterpolant = interpolant;
  29775. }
  29776. const times = interpolant.parameterPositions,
  29777. values = interpolant.sampleValues;
  29778. times[ 0 ] = now;
  29779. times[ 1 ] = now + duration;
  29780. values[ 0 ] = startTimeScale / timeScale;
  29781. values[ 1 ] = endTimeScale / timeScale;
  29782. return this;
  29783. }
  29784. stopWarping() {
  29785. const timeScaleInterpolant = this._timeScaleInterpolant;
  29786. if ( timeScaleInterpolant !== null ) {
  29787. this._timeScaleInterpolant = null;
  29788. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29789. }
  29790. return this;
  29791. }
  29792. // Object Accessors
  29793. getMixer() {
  29794. return this._mixer;
  29795. }
  29796. getClip() {
  29797. return this._clip;
  29798. }
  29799. getRoot() {
  29800. return this._localRoot || this._mixer._root;
  29801. }
  29802. // Interna
  29803. _update( time, deltaTime, timeDirection, accuIndex ) {
  29804. // called by the mixer
  29805. if ( ! this.enabled ) {
  29806. // call ._updateWeight() to update ._effectiveWeight
  29807. this._updateWeight( time );
  29808. return;
  29809. }
  29810. const startTime = this._startTime;
  29811. if ( startTime !== null ) {
  29812. // check for scheduled start of action
  29813. const timeRunning = ( time - startTime ) * timeDirection;
  29814. if ( timeRunning < 0 || timeDirection === 0 ) {
  29815. deltaTime = 0;
  29816. } else {
  29817. this._startTime = null; // unschedule
  29818. deltaTime = timeDirection * timeRunning;
  29819. }
  29820. }
  29821. // apply time scale and advance time
  29822. deltaTime *= this._updateTimeScale( time );
  29823. const clipTime = this._updateTime( deltaTime );
  29824. // note: _updateTime may disable the action resulting in
  29825. // an effective weight of 0
  29826. const weight = this._updateWeight( time );
  29827. if ( weight > 0 ) {
  29828. const interpolants = this._interpolants;
  29829. const propertyMixers = this._propertyBindings;
  29830. switch ( this.blendMode ) {
  29831. case AdditiveAnimationBlendMode:
  29832. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29833. interpolants[ j ].evaluate( clipTime );
  29834. propertyMixers[ j ].accumulateAdditive( weight );
  29835. }
  29836. break;
  29837. case NormalAnimationBlendMode:
  29838. default:
  29839. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29840. interpolants[ j ].evaluate( clipTime );
  29841. propertyMixers[ j ].accumulate( accuIndex, weight );
  29842. }
  29843. }
  29844. }
  29845. }
  29846. _updateWeight( time ) {
  29847. let weight = 0;
  29848. if ( this.enabled ) {
  29849. weight = this.weight;
  29850. const interpolant = this._weightInterpolant;
  29851. if ( interpolant !== null ) {
  29852. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29853. weight *= interpolantValue;
  29854. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29855. this.stopFading();
  29856. if ( interpolantValue === 0 ) {
  29857. // faded out, disable
  29858. this.enabled = false;
  29859. }
  29860. }
  29861. }
  29862. }
  29863. this._effectiveWeight = weight;
  29864. return weight;
  29865. }
  29866. _updateTimeScale( time ) {
  29867. let timeScale = 0;
  29868. if ( ! this.paused ) {
  29869. timeScale = this.timeScale;
  29870. const interpolant = this._timeScaleInterpolant;
  29871. if ( interpolant !== null ) {
  29872. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29873. timeScale *= interpolantValue;
  29874. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29875. this.stopWarping();
  29876. if ( timeScale === 0 ) {
  29877. // motion has halted, pause
  29878. this.paused = true;
  29879. } else {
  29880. // warp done - apply final time scale
  29881. this.timeScale = timeScale;
  29882. }
  29883. }
  29884. }
  29885. }
  29886. this._effectiveTimeScale = timeScale;
  29887. return timeScale;
  29888. }
  29889. _updateTime( deltaTime ) {
  29890. const duration = this._clip.duration;
  29891. const loop = this.loop;
  29892. let time = this.time + deltaTime;
  29893. let loopCount = this._loopCount;
  29894. const pingPong = ( loop === LoopPingPong );
  29895. if ( deltaTime === 0 ) {
  29896. if ( loopCount === - 1 ) return time;
  29897. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29898. }
  29899. if ( loop === LoopOnce ) {
  29900. if ( loopCount === - 1 ) {
  29901. // just started
  29902. this._loopCount = 0;
  29903. this._setEndings( true, true, false );
  29904. }
  29905. handle_stop: {
  29906. if ( time >= duration ) {
  29907. time = duration;
  29908. } else if ( time < 0 ) {
  29909. time = 0;
  29910. } else {
  29911. this.time = time;
  29912. break handle_stop;
  29913. }
  29914. if ( this.clampWhenFinished ) this.paused = true;
  29915. else this.enabled = false;
  29916. this.time = time;
  29917. this._mixer.dispatchEvent( {
  29918. type: 'finished', action: this,
  29919. direction: deltaTime < 0 ? - 1 : 1
  29920. } );
  29921. }
  29922. } else { // repetitive Repeat or PingPong
  29923. if ( loopCount === - 1 ) {
  29924. // just started
  29925. if ( deltaTime >= 0 ) {
  29926. loopCount = 0;
  29927. this._setEndings( true, this.repetitions === 0, pingPong );
  29928. } else {
  29929. // when looping in reverse direction, the initial
  29930. // transition through zero counts as a repetition,
  29931. // so leave loopCount at -1
  29932. this._setEndings( this.repetitions === 0, true, pingPong );
  29933. }
  29934. }
  29935. if ( time >= duration || time < 0 ) {
  29936. // wrap around
  29937. const loopDelta = Math.floor( time / duration ); // signed
  29938. time -= duration * loopDelta;
  29939. loopCount += Math.abs( loopDelta );
  29940. const pending = this.repetitions - loopCount;
  29941. if ( pending <= 0 ) {
  29942. // have to stop (switch state, clamp time, fire event)
  29943. if ( this.clampWhenFinished ) this.paused = true;
  29944. else this.enabled = false;
  29945. time = deltaTime > 0 ? duration : 0;
  29946. this.time = time;
  29947. this._mixer.dispatchEvent( {
  29948. type: 'finished', action: this,
  29949. direction: deltaTime > 0 ? 1 : - 1
  29950. } );
  29951. } else {
  29952. // keep running
  29953. if ( pending === 1 ) {
  29954. // entering the last round
  29955. const atStart = deltaTime < 0;
  29956. this._setEndings( atStart, ! atStart, pingPong );
  29957. } else {
  29958. this._setEndings( false, false, pingPong );
  29959. }
  29960. this._loopCount = loopCount;
  29961. this.time = time;
  29962. this._mixer.dispatchEvent( {
  29963. type: 'loop', action: this, loopDelta: loopDelta
  29964. } );
  29965. }
  29966. } else {
  29967. this.time = time;
  29968. }
  29969. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29970. // invert time for the "pong round"
  29971. return duration - time;
  29972. }
  29973. }
  29974. return time;
  29975. }
  29976. _setEndings( atStart, atEnd, pingPong ) {
  29977. const settings = this._interpolantSettings;
  29978. if ( pingPong ) {
  29979. settings.endingStart = ZeroSlopeEnding;
  29980. settings.endingEnd = ZeroSlopeEnding;
  29981. } else {
  29982. // assuming for LoopOnce atStart == atEnd == true
  29983. if ( atStart ) {
  29984. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29985. } else {
  29986. settings.endingStart = WrapAroundEnding;
  29987. }
  29988. if ( atEnd ) {
  29989. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29990. } else {
  29991. settings.endingEnd = WrapAroundEnding;
  29992. }
  29993. }
  29994. }
  29995. _scheduleFading( duration, weightNow, weightThen ) {
  29996. const mixer = this._mixer, now = mixer.time;
  29997. let interpolant = this._weightInterpolant;
  29998. if ( interpolant === null ) {
  29999. interpolant = mixer._lendControlInterpolant();
  30000. this._weightInterpolant = interpolant;
  30001. }
  30002. const times = interpolant.parameterPositions,
  30003. values = interpolant.sampleValues;
  30004. times[ 0 ] = now;
  30005. values[ 0 ] = weightNow;
  30006. times[ 1 ] = now + duration;
  30007. values[ 1 ] = weightThen;
  30008. return this;
  30009. }
  30010. }
  30011. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  30012. class AnimationMixer extends EventDispatcher {
  30013. constructor( root ) {
  30014. super();
  30015. this._root = root;
  30016. this._initMemoryManager();
  30017. this._accuIndex = 0;
  30018. this.time = 0;
  30019. this.timeScale = 1.0;
  30020. }
  30021. _bindAction( action, prototypeAction ) {
  30022. const root = action._localRoot || this._root,
  30023. tracks = action._clip.tracks,
  30024. nTracks = tracks.length,
  30025. bindings = action._propertyBindings,
  30026. interpolants = action._interpolants,
  30027. rootUuid = root.uuid,
  30028. bindingsByRoot = this._bindingsByRootAndName;
  30029. let bindingsByName = bindingsByRoot[ rootUuid ];
  30030. if ( bindingsByName === undefined ) {
  30031. bindingsByName = {};
  30032. bindingsByRoot[ rootUuid ] = bindingsByName;
  30033. }
  30034. for ( let i = 0; i !== nTracks; ++ i ) {
  30035. const track = tracks[ i ],
  30036. trackName = track.name;
  30037. let binding = bindingsByName[ trackName ];
  30038. if ( binding !== undefined ) {
  30039. ++ binding.referenceCount;
  30040. bindings[ i ] = binding;
  30041. } else {
  30042. binding = bindings[ i ];
  30043. if ( binding !== undefined ) {
  30044. // existing binding, make sure the cache knows
  30045. if ( binding._cacheIndex === null ) {
  30046. ++ binding.referenceCount;
  30047. this._addInactiveBinding( binding, rootUuid, trackName );
  30048. }
  30049. continue;
  30050. }
  30051. const path = prototypeAction && prototypeAction.
  30052. _propertyBindings[ i ].binding.parsedPath;
  30053. binding = new PropertyMixer(
  30054. PropertyBinding.create( root, trackName, path ),
  30055. track.ValueTypeName, track.getValueSize() );
  30056. ++ binding.referenceCount;
  30057. this._addInactiveBinding( binding, rootUuid, trackName );
  30058. bindings[ i ] = binding;
  30059. }
  30060. interpolants[ i ].resultBuffer = binding.buffer;
  30061. }
  30062. }
  30063. _activateAction( action ) {
  30064. if ( ! this._isActiveAction( action ) ) {
  30065. if ( action._cacheIndex === null ) {
  30066. // this action has been forgotten by the cache, but the user
  30067. // appears to be still using it -> rebind
  30068. const rootUuid = ( action._localRoot || this._root ).uuid,
  30069. clipUuid = action._clip.uuid,
  30070. actionsForClip = this._actionsByClip[ clipUuid ];
  30071. this._bindAction( action,
  30072. actionsForClip && actionsForClip.knownActions[ 0 ] );
  30073. this._addInactiveAction( action, clipUuid, rootUuid );
  30074. }
  30075. const bindings = action._propertyBindings;
  30076. // increment reference counts / sort out state
  30077. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30078. const binding = bindings[ i ];
  30079. if ( binding.useCount ++ === 0 ) {
  30080. this._lendBinding( binding );
  30081. binding.saveOriginalState();
  30082. }
  30083. }
  30084. this._lendAction( action );
  30085. }
  30086. }
  30087. _deactivateAction( action ) {
  30088. if ( this._isActiveAction( action ) ) {
  30089. const bindings = action._propertyBindings;
  30090. // decrement reference counts / sort out state
  30091. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30092. const binding = bindings[ i ];
  30093. if ( -- binding.useCount === 0 ) {
  30094. binding.restoreOriginalState();
  30095. this._takeBackBinding( binding );
  30096. }
  30097. }
  30098. this._takeBackAction( action );
  30099. }
  30100. }
  30101. // Memory manager
  30102. _initMemoryManager() {
  30103. this._actions = []; // 'nActiveActions' followed by inactive ones
  30104. this._nActiveActions = 0;
  30105. this._actionsByClip = {};
  30106. // inside:
  30107. // {
  30108. // knownActions: Array< AnimationAction > - used as prototypes
  30109. // actionByRoot: AnimationAction - lookup
  30110. // }
  30111. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  30112. this._nActiveBindings = 0;
  30113. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  30114. this._controlInterpolants = []; // same game as above
  30115. this._nActiveControlInterpolants = 0;
  30116. const scope = this;
  30117. this.stats = {
  30118. actions: {
  30119. get total() {
  30120. return scope._actions.length;
  30121. },
  30122. get inUse() {
  30123. return scope._nActiveActions;
  30124. }
  30125. },
  30126. bindings: {
  30127. get total() {
  30128. return scope._bindings.length;
  30129. },
  30130. get inUse() {
  30131. return scope._nActiveBindings;
  30132. }
  30133. },
  30134. controlInterpolants: {
  30135. get total() {
  30136. return scope._controlInterpolants.length;
  30137. },
  30138. get inUse() {
  30139. return scope._nActiveControlInterpolants;
  30140. }
  30141. }
  30142. };
  30143. }
  30144. // Memory management for AnimationAction objects
  30145. _isActiveAction( action ) {
  30146. const index = action._cacheIndex;
  30147. return index !== null && index < this._nActiveActions;
  30148. }
  30149. _addInactiveAction( action, clipUuid, rootUuid ) {
  30150. const actions = this._actions,
  30151. actionsByClip = this._actionsByClip;
  30152. let actionsForClip = actionsByClip[ clipUuid ];
  30153. if ( actionsForClip === undefined ) {
  30154. actionsForClip = {
  30155. knownActions: [ action ],
  30156. actionByRoot: {}
  30157. };
  30158. action._byClipCacheIndex = 0;
  30159. actionsByClip[ clipUuid ] = actionsForClip;
  30160. } else {
  30161. const knownActions = actionsForClip.knownActions;
  30162. action._byClipCacheIndex = knownActions.length;
  30163. knownActions.push( action );
  30164. }
  30165. action._cacheIndex = actions.length;
  30166. actions.push( action );
  30167. actionsForClip.actionByRoot[ rootUuid ] = action;
  30168. }
  30169. _removeInactiveAction( action ) {
  30170. const actions = this._actions,
  30171. lastInactiveAction = actions[ actions.length - 1 ],
  30172. cacheIndex = action._cacheIndex;
  30173. lastInactiveAction._cacheIndex = cacheIndex;
  30174. actions[ cacheIndex ] = lastInactiveAction;
  30175. actions.pop();
  30176. action._cacheIndex = null;
  30177. const clipUuid = action._clip.uuid,
  30178. actionsByClip = this._actionsByClip,
  30179. actionsForClip = actionsByClip[ clipUuid ],
  30180. knownActionsForClip = actionsForClip.knownActions,
  30181. lastKnownAction =
  30182. knownActionsForClip[ knownActionsForClip.length - 1 ],
  30183. byClipCacheIndex = action._byClipCacheIndex;
  30184. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  30185. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  30186. knownActionsForClip.pop();
  30187. action._byClipCacheIndex = null;
  30188. const actionByRoot = actionsForClip.actionByRoot,
  30189. rootUuid = ( action._localRoot || this._root ).uuid;
  30190. delete actionByRoot[ rootUuid ];
  30191. if ( knownActionsForClip.length === 0 ) {
  30192. delete actionsByClip[ clipUuid ];
  30193. }
  30194. this._removeInactiveBindingsForAction( action );
  30195. }
  30196. _removeInactiveBindingsForAction( action ) {
  30197. const bindings = action._propertyBindings;
  30198. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30199. const binding = bindings[ i ];
  30200. if ( -- binding.referenceCount === 0 ) {
  30201. this._removeInactiveBinding( binding );
  30202. }
  30203. }
  30204. }
  30205. _lendAction( action ) {
  30206. // [ active actions | inactive actions ]
  30207. // [ active actions >| inactive actions ]
  30208. // s a
  30209. // <-swap->
  30210. // a s
  30211. const actions = this._actions,
  30212. prevIndex = action._cacheIndex,
  30213. lastActiveIndex = this._nActiveActions ++,
  30214. firstInactiveAction = actions[ lastActiveIndex ];
  30215. action._cacheIndex = lastActiveIndex;
  30216. actions[ lastActiveIndex ] = action;
  30217. firstInactiveAction._cacheIndex = prevIndex;
  30218. actions[ prevIndex ] = firstInactiveAction;
  30219. }
  30220. _takeBackAction( action ) {
  30221. // [ active actions | inactive actions ]
  30222. // [ active actions |< inactive actions ]
  30223. // a s
  30224. // <-swap->
  30225. // s a
  30226. const actions = this._actions,
  30227. prevIndex = action._cacheIndex,
  30228. firstInactiveIndex = -- this._nActiveActions,
  30229. lastActiveAction = actions[ firstInactiveIndex ];
  30230. action._cacheIndex = firstInactiveIndex;
  30231. actions[ firstInactiveIndex ] = action;
  30232. lastActiveAction._cacheIndex = prevIndex;
  30233. actions[ prevIndex ] = lastActiveAction;
  30234. }
  30235. // Memory management for PropertyMixer objects
  30236. _addInactiveBinding( binding, rootUuid, trackName ) {
  30237. const bindingsByRoot = this._bindingsByRootAndName,
  30238. bindings = this._bindings;
  30239. let bindingByName = bindingsByRoot[ rootUuid ];
  30240. if ( bindingByName === undefined ) {
  30241. bindingByName = {};
  30242. bindingsByRoot[ rootUuid ] = bindingByName;
  30243. }
  30244. bindingByName[ trackName ] = binding;
  30245. binding._cacheIndex = bindings.length;
  30246. bindings.push( binding );
  30247. }
  30248. _removeInactiveBinding( binding ) {
  30249. const bindings = this._bindings,
  30250. propBinding = binding.binding,
  30251. rootUuid = propBinding.rootNode.uuid,
  30252. trackName = propBinding.path,
  30253. bindingsByRoot = this._bindingsByRootAndName,
  30254. bindingByName = bindingsByRoot[ rootUuid ],
  30255. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30256. cacheIndex = binding._cacheIndex;
  30257. lastInactiveBinding._cacheIndex = cacheIndex;
  30258. bindings[ cacheIndex ] = lastInactiveBinding;
  30259. bindings.pop();
  30260. delete bindingByName[ trackName ];
  30261. if ( Object.keys( bindingByName ).length === 0 ) {
  30262. delete bindingsByRoot[ rootUuid ];
  30263. }
  30264. }
  30265. _lendBinding( binding ) {
  30266. const bindings = this._bindings,
  30267. prevIndex = binding._cacheIndex,
  30268. lastActiveIndex = this._nActiveBindings ++,
  30269. firstInactiveBinding = bindings[ lastActiveIndex ];
  30270. binding._cacheIndex = lastActiveIndex;
  30271. bindings[ lastActiveIndex ] = binding;
  30272. firstInactiveBinding._cacheIndex = prevIndex;
  30273. bindings[ prevIndex ] = firstInactiveBinding;
  30274. }
  30275. _takeBackBinding( binding ) {
  30276. const bindings = this._bindings,
  30277. prevIndex = binding._cacheIndex,
  30278. firstInactiveIndex = -- this._nActiveBindings,
  30279. lastActiveBinding = bindings[ firstInactiveIndex ];
  30280. binding._cacheIndex = firstInactiveIndex;
  30281. bindings[ firstInactiveIndex ] = binding;
  30282. lastActiveBinding._cacheIndex = prevIndex;
  30283. bindings[ prevIndex ] = lastActiveBinding;
  30284. }
  30285. // Memory management of Interpolants for weight and time scale
  30286. _lendControlInterpolant() {
  30287. const interpolants = this._controlInterpolants,
  30288. lastActiveIndex = this._nActiveControlInterpolants ++;
  30289. let interpolant = interpolants[ lastActiveIndex ];
  30290. if ( interpolant === undefined ) {
  30291. interpolant = new LinearInterpolant(
  30292. new Float32Array( 2 ), new Float32Array( 2 ),
  30293. 1, _controlInterpolantsResultBuffer );
  30294. interpolant.__cacheIndex = lastActiveIndex;
  30295. interpolants[ lastActiveIndex ] = interpolant;
  30296. }
  30297. return interpolant;
  30298. }
  30299. _takeBackControlInterpolant( interpolant ) {
  30300. const interpolants = this._controlInterpolants,
  30301. prevIndex = interpolant.__cacheIndex,
  30302. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30303. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30304. interpolant.__cacheIndex = firstInactiveIndex;
  30305. interpolants[ firstInactiveIndex ] = interpolant;
  30306. lastActiveInterpolant.__cacheIndex = prevIndex;
  30307. interpolants[ prevIndex ] = lastActiveInterpolant;
  30308. }
  30309. // return an action for a clip optionally using a custom root target
  30310. // object (this method allocates a lot of dynamic memory in case a
  30311. // previously unknown clip/root combination is specified)
  30312. clipAction( clip, optionalRoot, blendMode ) {
  30313. const root = optionalRoot || this._root,
  30314. rootUuid = root.uuid;
  30315. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  30316. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  30317. const actionsForClip = this._actionsByClip[ clipUuid ];
  30318. let prototypeAction = null;
  30319. if ( blendMode === undefined ) {
  30320. if ( clipObject !== null ) {
  30321. blendMode = clipObject.blendMode;
  30322. } else {
  30323. blendMode = NormalAnimationBlendMode;
  30324. }
  30325. }
  30326. if ( actionsForClip !== undefined ) {
  30327. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  30328. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  30329. return existingAction;
  30330. }
  30331. // we know the clip, so we don't have to parse all
  30332. // the bindings again but can just copy
  30333. prototypeAction = actionsForClip.knownActions[ 0 ];
  30334. // also, take the clip from the prototype action
  30335. if ( clipObject === null )
  30336. clipObject = prototypeAction._clip;
  30337. }
  30338. // clip must be known when specified via string
  30339. if ( clipObject === null ) return null;
  30340. // allocate all resources required to run it
  30341. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  30342. this._bindAction( newAction, prototypeAction );
  30343. // and make the action known to the memory manager
  30344. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30345. return newAction;
  30346. }
  30347. // get an existing action
  30348. existingAction( clip, optionalRoot ) {
  30349. const root = optionalRoot || this._root,
  30350. rootUuid = root.uuid,
  30351. clipObject = typeof clip === 'string' ?
  30352. AnimationClip.findByName( root, clip ) : clip,
  30353. clipUuid = clipObject ? clipObject.uuid : clip,
  30354. actionsForClip = this._actionsByClip[ clipUuid ];
  30355. if ( actionsForClip !== undefined ) {
  30356. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30357. }
  30358. return null;
  30359. }
  30360. // deactivates all previously scheduled actions
  30361. stopAllAction() {
  30362. const actions = this._actions,
  30363. nActions = this._nActiveActions;
  30364. for ( let i = nActions - 1; i >= 0; -- i ) {
  30365. actions[ i ].stop();
  30366. }
  30367. return this;
  30368. }
  30369. // advance the time and update apply the animation
  30370. update( deltaTime ) {
  30371. deltaTime *= this.timeScale;
  30372. const actions = this._actions,
  30373. nActions = this._nActiveActions,
  30374. time = this.time += deltaTime,
  30375. timeDirection = Math.sign( deltaTime ),
  30376. accuIndex = this._accuIndex ^= 1;
  30377. // run active actions
  30378. for ( let i = 0; i !== nActions; ++ i ) {
  30379. const action = actions[ i ];
  30380. action._update( time, deltaTime, timeDirection, accuIndex );
  30381. }
  30382. // update scene graph
  30383. const bindings = this._bindings,
  30384. nBindings = this._nActiveBindings;
  30385. for ( let i = 0; i !== nBindings; ++ i ) {
  30386. bindings[ i ].apply( accuIndex );
  30387. }
  30388. return this;
  30389. }
  30390. // Allows you to seek to a specific time in an animation.
  30391. setTime( timeInSeconds ) {
  30392. this.time = 0; // Zero out time attribute for AnimationMixer object;
  30393. for ( let i = 0; i < this._actions.length; i ++ ) {
  30394. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  30395. }
  30396. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  30397. }
  30398. // return this mixer's root target object
  30399. getRoot() {
  30400. return this._root;
  30401. }
  30402. // free all resources specific to a particular clip
  30403. uncacheClip( clip ) {
  30404. const actions = this._actions,
  30405. clipUuid = clip.uuid,
  30406. actionsByClip = this._actionsByClip,
  30407. actionsForClip = actionsByClip[ clipUuid ];
  30408. if ( actionsForClip !== undefined ) {
  30409. // note: just calling _removeInactiveAction would mess up the
  30410. // iteration state and also require updating the state we can
  30411. // just throw away
  30412. const actionsToRemove = actionsForClip.knownActions;
  30413. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30414. const action = actionsToRemove[ i ];
  30415. this._deactivateAction( action );
  30416. const cacheIndex = action._cacheIndex,
  30417. lastInactiveAction = actions[ actions.length - 1 ];
  30418. action._cacheIndex = null;
  30419. action._byClipCacheIndex = null;
  30420. lastInactiveAction._cacheIndex = cacheIndex;
  30421. actions[ cacheIndex ] = lastInactiveAction;
  30422. actions.pop();
  30423. this._removeInactiveBindingsForAction( action );
  30424. }
  30425. delete actionsByClip[ clipUuid ];
  30426. }
  30427. }
  30428. // free all resources specific to a particular root target object
  30429. uncacheRoot( root ) {
  30430. const rootUuid = root.uuid,
  30431. actionsByClip = this._actionsByClip;
  30432. for ( const clipUuid in actionsByClip ) {
  30433. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30434. action = actionByRoot[ rootUuid ];
  30435. if ( action !== undefined ) {
  30436. this._deactivateAction( action );
  30437. this._removeInactiveAction( action );
  30438. }
  30439. }
  30440. const bindingsByRoot = this._bindingsByRootAndName,
  30441. bindingByName = bindingsByRoot[ rootUuid ];
  30442. if ( bindingByName !== undefined ) {
  30443. for ( const trackName in bindingByName ) {
  30444. const binding = bindingByName[ trackName ];
  30445. binding.restoreOriginalState();
  30446. this._removeInactiveBinding( binding );
  30447. }
  30448. }
  30449. }
  30450. // remove a targeted clip from the cache
  30451. uncacheAction( clip, optionalRoot ) {
  30452. const action = this.existingAction( clip, optionalRoot );
  30453. if ( action !== null ) {
  30454. this._deactivateAction( action );
  30455. this._removeInactiveAction( action );
  30456. }
  30457. }
  30458. }
  30459. class Uniform {
  30460. constructor( value ) {
  30461. this.value = value;
  30462. }
  30463. clone() {
  30464. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30465. }
  30466. }
  30467. let _id = 0;
  30468. class UniformsGroup extends EventDispatcher {
  30469. constructor() {
  30470. super();
  30471. this.isUniformsGroup = true;
  30472. Object.defineProperty( this, 'id', { value: _id ++ } );
  30473. this.name = '';
  30474. this.usage = StaticDrawUsage;
  30475. this.uniforms = [];
  30476. }
  30477. add( uniform ) {
  30478. this.uniforms.push( uniform );
  30479. return this;
  30480. }
  30481. remove( uniform ) {
  30482. const index = this.uniforms.indexOf( uniform );
  30483. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  30484. return this;
  30485. }
  30486. setName( name ) {
  30487. this.name = name;
  30488. return this;
  30489. }
  30490. setUsage( value ) {
  30491. this.usage = value;
  30492. return this;
  30493. }
  30494. dispose() {
  30495. this.dispatchEvent( { type: 'dispose' } );
  30496. return this;
  30497. }
  30498. copy( source ) {
  30499. this.name = source.name;
  30500. this.usage = source.usage;
  30501. const uniformsSource = source.uniforms;
  30502. this.uniforms.length = 0;
  30503. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30504. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30505. for ( let j = 0; j < uniforms.length; j ++ ) {
  30506. this.uniforms.push( uniforms[ j ].clone() );
  30507. }
  30508. }
  30509. return this;
  30510. }
  30511. clone() {
  30512. return new this.constructor().copy( this );
  30513. }
  30514. }
  30515. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30516. constructor( array, stride, meshPerAttribute = 1 ) {
  30517. super( array, stride );
  30518. this.isInstancedInterleavedBuffer = true;
  30519. this.meshPerAttribute = meshPerAttribute;
  30520. }
  30521. copy( source ) {
  30522. super.copy( source );
  30523. this.meshPerAttribute = source.meshPerAttribute;
  30524. return this;
  30525. }
  30526. clone( data ) {
  30527. const ib = super.clone( data );
  30528. ib.meshPerAttribute = this.meshPerAttribute;
  30529. return ib;
  30530. }
  30531. toJSON( data ) {
  30532. const json = super.toJSON( data );
  30533. json.isInstancedInterleavedBuffer = true;
  30534. json.meshPerAttribute = this.meshPerAttribute;
  30535. return json;
  30536. }
  30537. }
  30538. class GLBufferAttribute {
  30539. constructor( buffer, type, itemSize, elementSize, count ) {
  30540. this.isGLBufferAttribute = true;
  30541. this.name = '';
  30542. this.buffer = buffer;
  30543. this.type = type;
  30544. this.itemSize = itemSize;
  30545. this.elementSize = elementSize;
  30546. this.count = count;
  30547. this.version = 0;
  30548. }
  30549. set needsUpdate( value ) {
  30550. if ( value === true ) this.version ++;
  30551. }
  30552. setBuffer( buffer ) {
  30553. this.buffer = buffer;
  30554. return this;
  30555. }
  30556. setType( type, elementSize ) {
  30557. this.type = type;
  30558. this.elementSize = elementSize;
  30559. return this;
  30560. }
  30561. setItemSize( itemSize ) {
  30562. this.itemSize = itemSize;
  30563. return this;
  30564. }
  30565. setCount( count ) {
  30566. this.count = count;
  30567. return this;
  30568. }
  30569. }
  30570. const _matrix = /*@__PURE__*/ new Matrix4();
  30571. class Raycaster {
  30572. constructor( origin, direction, near = 0, far = Infinity ) {
  30573. this.ray = new Ray( origin, direction );
  30574. // direction is assumed to be normalized (for accurate distance calculations)
  30575. this.near = near;
  30576. this.far = far;
  30577. this.camera = null;
  30578. this.layers = new Layers();
  30579. this.params = {
  30580. Mesh: {},
  30581. Line: { threshold: 1 },
  30582. LOD: {},
  30583. Points: { threshold: 1 },
  30584. Sprite: {}
  30585. };
  30586. }
  30587. set( origin, direction ) {
  30588. // direction is assumed to be normalized (for accurate distance calculations)
  30589. this.ray.set( origin, direction );
  30590. }
  30591. setFromCamera( coords, camera ) {
  30592. if ( camera.isPerspectiveCamera ) {
  30593. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30594. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30595. this.camera = camera;
  30596. } else if ( camera.isOrthographicCamera ) {
  30597. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30598. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30599. this.camera = camera;
  30600. } else {
  30601. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30602. }
  30603. }
  30604. setFromXRController( controller ) {
  30605. _matrix.identity().extractRotation( controller.matrixWorld );
  30606. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30607. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  30608. return this;
  30609. }
  30610. intersectObject( object, recursive = true, intersects = [] ) {
  30611. intersect( object, this, intersects, recursive );
  30612. intersects.sort( ascSort );
  30613. return intersects;
  30614. }
  30615. intersectObjects( objects, recursive = true, intersects = [] ) {
  30616. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30617. intersect( objects[ i ], this, intersects, recursive );
  30618. }
  30619. intersects.sort( ascSort );
  30620. return intersects;
  30621. }
  30622. }
  30623. function ascSort( a, b ) {
  30624. return a.distance - b.distance;
  30625. }
  30626. function intersect( object, raycaster, intersects, recursive ) {
  30627. let propagate = true;
  30628. if ( object.layers.test( raycaster.layers ) ) {
  30629. const result = object.raycast( raycaster, intersects );
  30630. if ( result === false ) propagate = false;
  30631. }
  30632. if ( propagate === true && recursive === true ) {
  30633. const children = object.children;
  30634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30635. intersect( children[ i ], raycaster, intersects, true );
  30636. }
  30637. }
  30638. }
  30639. /**
  30640. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30641. *
  30642. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  30643. * theta (the azimuthal angle) is measured from the positive z-axis.
  30644. */
  30645. class Spherical {
  30646. constructor( radius = 1, phi = 0, theta = 0 ) {
  30647. this.radius = radius;
  30648. this.phi = phi; // polar angle
  30649. this.theta = theta; // azimuthal angle
  30650. return this;
  30651. }
  30652. set( radius, phi, theta ) {
  30653. this.radius = radius;
  30654. this.phi = phi;
  30655. this.theta = theta;
  30656. return this;
  30657. }
  30658. copy( other ) {
  30659. this.radius = other.radius;
  30660. this.phi = other.phi;
  30661. this.theta = other.theta;
  30662. return this;
  30663. }
  30664. // restrict phi to be between EPS and PI-EPS
  30665. makeSafe() {
  30666. const EPS = 0.000001;
  30667. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30668. return this;
  30669. }
  30670. setFromVector3( v ) {
  30671. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30672. }
  30673. setFromCartesianCoords( x, y, z ) {
  30674. this.radius = Math.sqrt( x * x + y * y + z * z );
  30675. if ( this.radius === 0 ) {
  30676. this.theta = 0;
  30677. this.phi = 0;
  30678. } else {
  30679. this.theta = Math.atan2( x, z );
  30680. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30681. }
  30682. return this;
  30683. }
  30684. clone() {
  30685. return new this.constructor().copy( this );
  30686. }
  30687. }
  30688. /**
  30689. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30690. */
  30691. class Cylindrical {
  30692. constructor( radius = 1, theta = 0, y = 0 ) {
  30693. this.radius = radius; // distance from the origin to a point in the x-z plane
  30694. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30695. this.y = y; // height above the x-z plane
  30696. return this;
  30697. }
  30698. set( radius, theta, y ) {
  30699. this.radius = radius;
  30700. this.theta = theta;
  30701. this.y = y;
  30702. return this;
  30703. }
  30704. copy( other ) {
  30705. this.radius = other.radius;
  30706. this.theta = other.theta;
  30707. this.y = other.y;
  30708. return this;
  30709. }
  30710. setFromVector3( v ) {
  30711. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30712. }
  30713. setFromCartesianCoords( x, y, z ) {
  30714. this.radius = Math.sqrt( x * x + z * z );
  30715. this.theta = Math.atan2( x, z );
  30716. this.y = y;
  30717. return this;
  30718. }
  30719. clone() {
  30720. return new this.constructor().copy( this );
  30721. }
  30722. }
  30723. class Matrix2 {
  30724. constructor( n11, n12, n21, n22 ) {
  30725. Matrix2.prototype.isMatrix2 = true;
  30726. this.elements = [
  30727. 1, 0,
  30728. 0, 1,
  30729. ];
  30730. if ( n11 !== undefined ) {
  30731. this.set( n11, n12, n21, n22 );
  30732. }
  30733. }
  30734. identity() {
  30735. this.set(
  30736. 1, 0,
  30737. 0, 1,
  30738. );
  30739. return this;
  30740. }
  30741. fromArray( array, offset = 0 ) {
  30742. for ( let i = 0; i < 4; i ++ ) {
  30743. this.elements[ i ] = array[ i + offset ];
  30744. }
  30745. return this;
  30746. }
  30747. set( n11, n12, n21, n22 ) {
  30748. const te = this.elements;
  30749. te[ 0 ] = n11; te[ 2 ] = n12;
  30750. te[ 1 ] = n21; te[ 3 ] = n22;
  30751. return this;
  30752. }
  30753. }
  30754. const _vector$4 = /*@__PURE__*/ new Vector2();
  30755. class Box2 {
  30756. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30757. this.isBox2 = true;
  30758. this.min = min;
  30759. this.max = max;
  30760. }
  30761. set( min, max ) {
  30762. this.min.copy( min );
  30763. this.max.copy( max );
  30764. return this;
  30765. }
  30766. setFromPoints( points ) {
  30767. this.makeEmpty();
  30768. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30769. this.expandByPoint( points[ i ] );
  30770. }
  30771. return this;
  30772. }
  30773. setFromCenterAndSize( center, size ) {
  30774. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30775. this.min.copy( center ).sub( halfSize );
  30776. this.max.copy( center ).add( halfSize );
  30777. return this;
  30778. }
  30779. clone() {
  30780. return new this.constructor().copy( this );
  30781. }
  30782. copy( box ) {
  30783. this.min.copy( box.min );
  30784. this.max.copy( box.max );
  30785. return this;
  30786. }
  30787. makeEmpty() {
  30788. this.min.x = this.min.y = + Infinity;
  30789. this.max.x = this.max.y = - Infinity;
  30790. return this;
  30791. }
  30792. isEmpty() {
  30793. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30794. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30795. }
  30796. getCenter( target ) {
  30797. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30798. }
  30799. getSize( target ) {
  30800. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30801. }
  30802. expandByPoint( point ) {
  30803. this.min.min( point );
  30804. this.max.max( point );
  30805. return this;
  30806. }
  30807. expandByVector( vector ) {
  30808. this.min.sub( vector );
  30809. this.max.add( vector );
  30810. return this;
  30811. }
  30812. expandByScalar( scalar ) {
  30813. this.min.addScalar( - scalar );
  30814. this.max.addScalar( scalar );
  30815. return this;
  30816. }
  30817. containsPoint( point ) {
  30818. return point.x >= this.min.x && point.x <= this.max.x &&
  30819. point.y >= this.min.y && point.y <= this.max.y;
  30820. }
  30821. containsBox( box ) {
  30822. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30823. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30824. }
  30825. getParameter( point, target ) {
  30826. // This can potentially have a divide by zero if the box
  30827. // has a size dimension of 0.
  30828. return target.set(
  30829. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30830. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30831. );
  30832. }
  30833. intersectsBox( box ) {
  30834. // using 4 splitting planes to rule out intersections
  30835. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  30836. box.max.y >= this.min.y && box.min.y <= this.max.y;
  30837. }
  30838. clampPoint( point, target ) {
  30839. return target.copy( point ).clamp( this.min, this.max );
  30840. }
  30841. distanceToPoint( point ) {
  30842. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30843. }
  30844. intersect( box ) {
  30845. this.min.max( box.min );
  30846. this.max.min( box.max );
  30847. if ( this.isEmpty() ) this.makeEmpty();
  30848. return this;
  30849. }
  30850. union( box ) {
  30851. this.min.min( box.min );
  30852. this.max.max( box.max );
  30853. return this;
  30854. }
  30855. translate( offset ) {
  30856. this.min.add( offset );
  30857. this.max.add( offset );
  30858. return this;
  30859. }
  30860. equals( box ) {
  30861. return box.min.equals( this.min ) && box.max.equals( this.max );
  30862. }
  30863. }
  30864. const _startP = /*@__PURE__*/ new Vector3();
  30865. const _startEnd = /*@__PURE__*/ new Vector3();
  30866. class Line3 {
  30867. constructor( start = new Vector3(), end = new Vector3() ) {
  30868. this.start = start;
  30869. this.end = end;
  30870. }
  30871. set( start, end ) {
  30872. this.start.copy( start );
  30873. this.end.copy( end );
  30874. return this;
  30875. }
  30876. copy( line ) {
  30877. this.start.copy( line.start );
  30878. this.end.copy( line.end );
  30879. return this;
  30880. }
  30881. getCenter( target ) {
  30882. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30883. }
  30884. delta( target ) {
  30885. return target.subVectors( this.end, this.start );
  30886. }
  30887. distanceSq() {
  30888. return this.start.distanceToSquared( this.end );
  30889. }
  30890. distance() {
  30891. return this.start.distanceTo( this.end );
  30892. }
  30893. at( t, target ) {
  30894. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30895. }
  30896. closestPointToPointParameter( point, clampToLine ) {
  30897. _startP.subVectors( point, this.start );
  30898. _startEnd.subVectors( this.end, this.start );
  30899. const startEnd2 = _startEnd.dot( _startEnd );
  30900. const startEnd_startP = _startEnd.dot( _startP );
  30901. let t = startEnd_startP / startEnd2;
  30902. if ( clampToLine ) {
  30903. t = clamp( t, 0, 1 );
  30904. }
  30905. return t;
  30906. }
  30907. closestPointToPoint( point, clampToLine, target ) {
  30908. const t = this.closestPointToPointParameter( point, clampToLine );
  30909. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30910. }
  30911. applyMatrix4( matrix ) {
  30912. this.start.applyMatrix4( matrix );
  30913. this.end.applyMatrix4( matrix );
  30914. return this;
  30915. }
  30916. equals( line ) {
  30917. return line.start.equals( this.start ) && line.end.equals( this.end );
  30918. }
  30919. clone() {
  30920. return new this.constructor().copy( this );
  30921. }
  30922. }
  30923. const _vector$3 = /*@__PURE__*/ new Vector3();
  30924. class SpotLightHelper extends Object3D {
  30925. constructor( light, color ) {
  30926. super();
  30927. this.light = light;
  30928. this.matrixAutoUpdate = false;
  30929. this.color = color;
  30930. this.type = 'SpotLightHelper';
  30931. const geometry = new BufferGeometry();
  30932. const positions = [
  30933. 0, 0, 0, 0, 0, 1,
  30934. 0, 0, 0, 1, 0, 1,
  30935. 0, 0, 0, - 1, 0, 1,
  30936. 0, 0, 0, 0, 1, 1,
  30937. 0, 0, 0, 0, - 1, 1
  30938. ];
  30939. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30940. const p1 = ( i / l ) * Math.PI * 2;
  30941. const p2 = ( j / l ) * Math.PI * 2;
  30942. positions.push(
  30943. Math.cos( p1 ), Math.sin( p1 ), 1,
  30944. Math.cos( p2 ), Math.sin( p2 ), 1
  30945. );
  30946. }
  30947. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30948. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30949. this.cone = new LineSegments( geometry, material );
  30950. this.add( this.cone );
  30951. this.update();
  30952. }
  30953. dispose() {
  30954. this.cone.geometry.dispose();
  30955. this.cone.material.dispose();
  30956. }
  30957. update() {
  30958. this.light.updateWorldMatrix( true, false );
  30959. this.light.target.updateWorldMatrix( true, false );
  30960. // update the local matrix based on the parent and light target transforms
  30961. if ( this.parent ) {
  30962. this.parent.updateWorldMatrix( true );
  30963. this.matrix
  30964. .copy( this.parent.matrixWorld )
  30965. .invert()
  30966. .multiply( this.light.matrixWorld );
  30967. } else {
  30968. this.matrix.copy( this.light.matrixWorld );
  30969. }
  30970. this.matrixWorld.copy( this.light.matrixWorld );
  30971. const coneLength = this.light.distance ? this.light.distance : 1000;
  30972. const coneWidth = coneLength * Math.tan( this.light.angle );
  30973. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30974. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  30975. this.cone.lookAt( _vector$3 );
  30976. if ( this.color !== undefined ) {
  30977. this.cone.material.color.set( this.color );
  30978. } else {
  30979. this.cone.material.color.copy( this.light.color );
  30980. }
  30981. }
  30982. }
  30983. const _vector$2 = /*@__PURE__*/ new Vector3();
  30984. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  30985. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  30986. class SkeletonHelper extends LineSegments {
  30987. constructor( object ) {
  30988. const bones = getBoneList( object );
  30989. const geometry = new BufferGeometry();
  30990. const vertices = [];
  30991. const colors = [];
  30992. const color1 = new Color( 0, 0, 1 );
  30993. const color2 = new Color( 0, 1, 0 );
  30994. for ( let i = 0; i < bones.length; i ++ ) {
  30995. const bone = bones[ i ];
  30996. if ( bone.parent && bone.parent.isBone ) {
  30997. vertices.push( 0, 0, 0 );
  30998. vertices.push( 0, 0, 0 );
  30999. colors.push( color1.r, color1.g, color1.b );
  31000. colors.push( color2.r, color2.g, color2.b );
  31001. }
  31002. }
  31003. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31004. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31005. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  31006. super( geometry, material );
  31007. this.isSkeletonHelper = true;
  31008. this.type = 'SkeletonHelper';
  31009. this.root = object;
  31010. this.bones = bones;
  31011. this.matrix = object.matrixWorld;
  31012. this.matrixAutoUpdate = false;
  31013. }
  31014. updateMatrixWorld( force ) {
  31015. const bones = this.bones;
  31016. const geometry = this.geometry;
  31017. const position = geometry.getAttribute( 'position' );
  31018. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  31019. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  31020. const bone = bones[ i ];
  31021. if ( bone.parent && bone.parent.isBone ) {
  31022. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  31023. _vector$2.setFromMatrixPosition( _boneMatrix );
  31024. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  31025. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  31026. _vector$2.setFromMatrixPosition( _boneMatrix );
  31027. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  31028. j += 2;
  31029. }
  31030. }
  31031. geometry.getAttribute( 'position' ).needsUpdate = true;
  31032. super.updateMatrixWorld( force );
  31033. }
  31034. dispose() {
  31035. this.geometry.dispose();
  31036. this.material.dispose();
  31037. }
  31038. }
  31039. function getBoneList( object ) {
  31040. const boneList = [];
  31041. if ( object.isBone === true ) {
  31042. boneList.push( object );
  31043. }
  31044. for ( let i = 0; i < object.children.length; i ++ ) {
  31045. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  31046. }
  31047. return boneList;
  31048. }
  31049. class PointLightHelper extends Mesh {
  31050. constructor( light, sphereSize, color ) {
  31051. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  31052. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31053. super( geometry, material );
  31054. this.light = light;
  31055. this.color = color;
  31056. this.type = 'PointLightHelper';
  31057. this.matrix = this.light.matrixWorld;
  31058. this.matrixAutoUpdate = false;
  31059. this.update();
  31060. /*
  31061. // TODO: delete this comment?
  31062. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  31063. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  31064. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  31065. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  31066. const d = light.distance;
  31067. if ( d === 0.0 ) {
  31068. this.lightDistance.visible = false;
  31069. } else {
  31070. this.lightDistance.scale.set( d, d, d );
  31071. }
  31072. this.add( this.lightDistance );
  31073. */
  31074. }
  31075. dispose() {
  31076. this.geometry.dispose();
  31077. this.material.dispose();
  31078. }
  31079. update() {
  31080. this.light.updateWorldMatrix( true, false );
  31081. if ( this.color !== undefined ) {
  31082. this.material.color.set( this.color );
  31083. } else {
  31084. this.material.color.copy( this.light.color );
  31085. }
  31086. /*
  31087. const d = this.light.distance;
  31088. if ( d === 0.0 ) {
  31089. this.lightDistance.visible = false;
  31090. } else {
  31091. this.lightDistance.visible = true;
  31092. this.lightDistance.scale.set( d, d, d );
  31093. }
  31094. */
  31095. }
  31096. }
  31097. const _vector$1 = /*@__PURE__*/ new Vector3();
  31098. const _color1 = /*@__PURE__*/ new Color();
  31099. const _color2 = /*@__PURE__*/ new Color();
  31100. class HemisphereLightHelper extends Object3D {
  31101. constructor( light, size, color ) {
  31102. super();
  31103. this.light = light;
  31104. this.matrix = light.matrixWorld;
  31105. this.matrixAutoUpdate = false;
  31106. this.color = color;
  31107. this.type = 'HemisphereLightHelper';
  31108. const geometry = new OctahedronGeometry( size );
  31109. geometry.rotateY( Math.PI * 0.5 );
  31110. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31111. if ( this.color === undefined ) this.material.vertexColors = true;
  31112. const position = geometry.getAttribute( 'position' );
  31113. const colors = new Float32Array( position.count * 3 );
  31114. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  31115. this.add( new Mesh( geometry, this.material ) );
  31116. this.update();
  31117. }
  31118. dispose() {
  31119. this.children[ 0 ].geometry.dispose();
  31120. this.children[ 0 ].material.dispose();
  31121. }
  31122. update() {
  31123. const mesh = this.children[ 0 ];
  31124. if ( this.color !== undefined ) {
  31125. this.material.color.set( this.color );
  31126. } else {
  31127. const colors = mesh.geometry.getAttribute( 'color' );
  31128. _color1.copy( this.light.color );
  31129. _color2.copy( this.light.groundColor );
  31130. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  31131. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  31132. colors.setXYZ( i, color.r, color.g, color.b );
  31133. }
  31134. colors.needsUpdate = true;
  31135. }
  31136. this.light.updateWorldMatrix( true, false );
  31137. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  31138. }
  31139. }
  31140. class GridHelper extends LineSegments {
  31141. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  31142. color1 = new Color( color1 );
  31143. color2 = new Color( color2 );
  31144. const center = divisions / 2;
  31145. const step = size / divisions;
  31146. const halfSize = size / 2;
  31147. const vertices = [], colors = [];
  31148. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  31149. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  31150. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  31151. const color = i === center ? color1 : color2;
  31152. color.toArray( colors, j ); j += 3;
  31153. color.toArray( colors, j ); j += 3;
  31154. color.toArray( colors, j ); j += 3;
  31155. color.toArray( colors, j ); j += 3;
  31156. }
  31157. const geometry = new BufferGeometry();
  31158. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31159. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31160. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31161. super( geometry, material );
  31162. this.type = 'GridHelper';
  31163. }
  31164. dispose() {
  31165. this.geometry.dispose();
  31166. this.material.dispose();
  31167. }
  31168. }
  31169. class PolarGridHelper extends LineSegments {
  31170. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  31171. color1 = new Color( color1 );
  31172. color2 = new Color( color2 );
  31173. const vertices = [];
  31174. const colors = [];
  31175. // create the sectors
  31176. if ( sectors > 1 ) {
  31177. for ( let i = 0; i < sectors; i ++ ) {
  31178. const v = ( i / sectors ) * ( Math.PI * 2 );
  31179. const x = Math.sin( v ) * radius;
  31180. const z = Math.cos( v ) * radius;
  31181. vertices.push( 0, 0, 0 );
  31182. vertices.push( x, 0, z );
  31183. const color = ( i & 1 ) ? color1 : color2;
  31184. colors.push( color.r, color.g, color.b );
  31185. colors.push( color.r, color.g, color.b );
  31186. }
  31187. }
  31188. // create the rings
  31189. for ( let i = 0; i < rings; i ++ ) {
  31190. const color = ( i & 1 ) ? color1 : color2;
  31191. const r = radius - ( radius / rings * i );
  31192. for ( let j = 0; j < divisions; j ++ ) {
  31193. // first vertex
  31194. let v = ( j / divisions ) * ( Math.PI * 2 );
  31195. let x = Math.sin( v ) * r;
  31196. let z = Math.cos( v ) * r;
  31197. vertices.push( x, 0, z );
  31198. colors.push( color.r, color.g, color.b );
  31199. // second vertex
  31200. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  31201. x = Math.sin( v ) * r;
  31202. z = Math.cos( v ) * r;
  31203. vertices.push( x, 0, z );
  31204. colors.push( color.r, color.g, color.b );
  31205. }
  31206. }
  31207. const geometry = new BufferGeometry();
  31208. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31209. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31210. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31211. super( geometry, material );
  31212. this.type = 'PolarGridHelper';
  31213. }
  31214. dispose() {
  31215. this.geometry.dispose();
  31216. this.material.dispose();
  31217. }
  31218. }
  31219. const _v1 = /*@__PURE__*/ new Vector3();
  31220. const _v2 = /*@__PURE__*/ new Vector3();
  31221. const _v3 = /*@__PURE__*/ new Vector3();
  31222. class DirectionalLightHelper extends Object3D {
  31223. constructor( light, size, color ) {
  31224. super();
  31225. this.light = light;
  31226. this.matrix = light.matrixWorld;
  31227. this.matrixAutoUpdate = false;
  31228. this.color = color;
  31229. this.type = 'DirectionalLightHelper';
  31230. if ( size === undefined ) size = 1;
  31231. let geometry = new BufferGeometry();
  31232. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  31233. - size, size, 0,
  31234. size, size, 0,
  31235. size, - size, 0,
  31236. - size, - size, 0,
  31237. - size, size, 0
  31238. ], 3 ) );
  31239. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  31240. this.lightPlane = new Line( geometry, material );
  31241. this.add( this.lightPlane );
  31242. geometry = new BufferGeometry();
  31243. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  31244. this.targetLine = new Line( geometry, material );
  31245. this.add( this.targetLine );
  31246. this.update();
  31247. }
  31248. dispose() {
  31249. this.lightPlane.geometry.dispose();
  31250. this.lightPlane.material.dispose();
  31251. this.targetLine.geometry.dispose();
  31252. this.targetLine.material.dispose();
  31253. }
  31254. update() {
  31255. this.light.updateWorldMatrix( true, false );
  31256. this.light.target.updateWorldMatrix( true, false );
  31257. _v1.setFromMatrixPosition( this.light.matrixWorld );
  31258. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  31259. _v3.subVectors( _v2, _v1 );
  31260. this.lightPlane.lookAt( _v2 );
  31261. if ( this.color !== undefined ) {
  31262. this.lightPlane.material.color.set( this.color );
  31263. this.targetLine.material.color.set( this.color );
  31264. } else {
  31265. this.lightPlane.material.color.copy( this.light.color );
  31266. this.targetLine.material.color.copy( this.light.color );
  31267. }
  31268. this.targetLine.lookAt( _v2 );
  31269. this.targetLine.scale.z = _v3.length();
  31270. }
  31271. }
  31272. const _vector = /*@__PURE__*/ new Vector3();
  31273. const _camera = /*@__PURE__*/ new Camera();
  31274. /**
  31275. * - shows frustum, line of sight and up of the camera
  31276. * - suitable for fast updates
  31277. * - based on frustum visualization in lightgl.js shadowmap example
  31278. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  31279. */
  31280. class CameraHelper extends LineSegments {
  31281. constructor( camera ) {
  31282. const geometry = new BufferGeometry();
  31283. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  31284. const vertices = [];
  31285. const colors = [];
  31286. const pointMap = {};
  31287. // near
  31288. addLine( 'n1', 'n2' );
  31289. addLine( 'n2', 'n4' );
  31290. addLine( 'n4', 'n3' );
  31291. addLine( 'n3', 'n1' );
  31292. // far
  31293. addLine( 'f1', 'f2' );
  31294. addLine( 'f2', 'f4' );
  31295. addLine( 'f4', 'f3' );
  31296. addLine( 'f3', 'f1' );
  31297. // sides
  31298. addLine( 'n1', 'f1' );
  31299. addLine( 'n2', 'f2' );
  31300. addLine( 'n3', 'f3' );
  31301. addLine( 'n4', 'f4' );
  31302. // cone
  31303. addLine( 'p', 'n1' );
  31304. addLine( 'p', 'n2' );
  31305. addLine( 'p', 'n3' );
  31306. addLine( 'p', 'n4' );
  31307. // up
  31308. addLine( 'u1', 'u2' );
  31309. addLine( 'u2', 'u3' );
  31310. addLine( 'u3', 'u1' );
  31311. // target
  31312. addLine( 'c', 't' );
  31313. addLine( 'p', 'c' );
  31314. // cross
  31315. addLine( 'cn1', 'cn2' );
  31316. addLine( 'cn3', 'cn4' );
  31317. addLine( 'cf1', 'cf2' );
  31318. addLine( 'cf3', 'cf4' );
  31319. function addLine( a, b ) {
  31320. addPoint( a );
  31321. addPoint( b );
  31322. }
  31323. function addPoint( id ) {
  31324. vertices.push( 0, 0, 0 );
  31325. colors.push( 0, 0, 0 );
  31326. if ( pointMap[ id ] === undefined ) {
  31327. pointMap[ id ] = [];
  31328. }
  31329. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  31330. }
  31331. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31332. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31333. super( geometry, material );
  31334. this.type = 'CameraHelper';
  31335. this.camera = camera;
  31336. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  31337. this.matrix = camera.matrixWorld;
  31338. this.matrixAutoUpdate = false;
  31339. this.pointMap = pointMap;
  31340. this.update();
  31341. // colors
  31342. const colorFrustum = new Color( 0xffaa00 );
  31343. const colorCone = new Color( 0xff0000 );
  31344. const colorUp = new Color( 0x00aaff );
  31345. const colorTarget = new Color( 0xffffff );
  31346. const colorCross = new Color( 0x333333 );
  31347. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  31348. }
  31349. setColors( frustum, cone, up, target, cross ) {
  31350. const geometry = this.geometry;
  31351. const colorAttribute = geometry.getAttribute( 'color' );
  31352. // near
  31353. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  31354. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  31355. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  31356. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  31357. // far
  31358. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  31359. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  31360. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  31361. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  31362. // sides
  31363. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  31364. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  31365. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  31366. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  31367. // cone
  31368. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  31369. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  31370. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  31371. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  31372. // up
  31373. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  31374. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  31375. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  31376. // target
  31377. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  31378. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  31379. // cross
  31380. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  31381. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  31382. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  31383. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  31384. colorAttribute.needsUpdate = true;
  31385. }
  31386. update() {
  31387. const geometry = this.geometry;
  31388. const pointMap = this.pointMap;
  31389. const w = 1, h = 1;
  31390. // we need just camera projection matrix inverse
  31391. // world matrix must be identity
  31392. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  31393. // center / target
  31394. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  31395. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  31396. // near
  31397. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  31398. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  31399. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  31400. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  31401. // far
  31402. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  31403. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  31404. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  31405. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  31406. // up
  31407. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  31408. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  31409. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  31410. // cross
  31411. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  31412. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  31413. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  31414. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  31415. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  31416. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  31417. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  31418. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  31419. geometry.getAttribute( 'position' ).needsUpdate = true;
  31420. }
  31421. dispose() {
  31422. this.geometry.dispose();
  31423. this.material.dispose();
  31424. }
  31425. }
  31426. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  31427. _vector.set( x, y, z ).unproject( camera );
  31428. const points = pointMap[ point ];
  31429. if ( points !== undefined ) {
  31430. const position = geometry.getAttribute( 'position' );
  31431. for ( let i = 0, l = points.length; i < l; i ++ ) {
  31432. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  31433. }
  31434. }
  31435. }
  31436. const _box = /*@__PURE__*/ new Box3();
  31437. class BoxHelper extends LineSegments {
  31438. constructor( object, color = 0xffff00 ) {
  31439. 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 ] );
  31440. const positions = new Float32Array( 8 * 3 );
  31441. const geometry = new BufferGeometry();
  31442. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31443. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31444. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31445. this.object = object;
  31446. this.type = 'BoxHelper';
  31447. this.matrixAutoUpdate = false;
  31448. this.update();
  31449. }
  31450. update( object ) {
  31451. if ( object !== undefined ) {
  31452. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  31453. }
  31454. if ( this.object !== undefined ) {
  31455. _box.setFromObject( this.object );
  31456. }
  31457. if ( _box.isEmpty() ) return;
  31458. const min = _box.min;
  31459. const max = _box.max;
  31460. /*
  31461. 5____4
  31462. 1/___0/|
  31463. | 6__|_7
  31464. 2/___3/
  31465. 0: max.x, max.y, max.z
  31466. 1: min.x, max.y, max.z
  31467. 2: min.x, min.y, max.z
  31468. 3: max.x, min.y, max.z
  31469. 4: max.x, max.y, min.z
  31470. 5: min.x, max.y, min.z
  31471. 6: min.x, min.y, min.z
  31472. 7: max.x, min.y, min.z
  31473. */
  31474. const position = this.geometry.attributes.position;
  31475. const array = position.array;
  31476. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  31477. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  31478. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  31479. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  31480. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  31481. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  31482. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  31483. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  31484. position.needsUpdate = true;
  31485. this.geometry.computeBoundingSphere();
  31486. }
  31487. setFromObject( object ) {
  31488. this.object = object;
  31489. this.update();
  31490. return this;
  31491. }
  31492. copy( source, recursive ) {
  31493. super.copy( source, recursive );
  31494. this.object = source.object;
  31495. return this;
  31496. }
  31497. dispose() {
  31498. this.geometry.dispose();
  31499. this.material.dispose();
  31500. }
  31501. }
  31502. class Box3Helper extends LineSegments {
  31503. constructor( box, color = 0xffff00 ) {
  31504. 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 ] );
  31505. 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 ];
  31506. const geometry = new BufferGeometry();
  31507. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31508. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31509. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31510. this.box = box;
  31511. this.type = 'Box3Helper';
  31512. this.geometry.computeBoundingSphere();
  31513. }
  31514. updateMatrixWorld( force ) {
  31515. const box = this.box;
  31516. if ( box.isEmpty() ) return;
  31517. box.getCenter( this.position );
  31518. box.getSize( this.scale );
  31519. this.scale.multiplyScalar( 0.5 );
  31520. super.updateMatrixWorld( force );
  31521. }
  31522. dispose() {
  31523. this.geometry.dispose();
  31524. this.material.dispose();
  31525. }
  31526. }
  31527. class PlaneHelper extends Line {
  31528. constructor( plane, size = 1, hex = 0xffff00 ) {
  31529. const color = hex;
  31530. 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 ];
  31531. const geometry = new BufferGeometry();
  31532. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31533. geometry.computeBoundingSphere();
  31534. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31535. this.type = 'PlaneHelper';
  31536. this.plane = plane;
  31537. this.size = size;
  31538. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31539. const geometry2 = new BufferGeometry();
  31540. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31541. geometry2.computeBoundingSphere();
  31542. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  31543. }
  31544. updateMatrixWorld( force ) {
  31545. this.position.set( 0, 0, 0 );
  31546. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  31547. this.lookAt( this.plane.normal );
  31548. this.translateZ( - this.plane.constant );
  31549. super.updateMatrixWorld( force );
  31550. }
  31551. dispose() {
  31552. this.geometry.dispose();
  31553. this.material.dispose();
  31554. this.children[ 0 ].geometry.dispose();
  31555. this.children[ 0 ].material.dispose();
  31556. }
  31557. }
  31558. const _axis = /*@__PURE__*/ new Vector3();
  31559. let _lineGeometry, _coneGeometry;
  31560. class ArrowHelper extends Object3D {
  31561. // dir is assumed to be normalized
  31562. 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 ) {
  31563. super();
  31564. this.type = 'ArrowHelper';
  31565. if ( _lineGeometry === undefined ) {
  31566. _lineGeometry = new BufferGeometry();
  31567. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  31568. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  31569. _coneGeometry.translate( 0, - 0.5, 0 );
  31570. }
  31571. this.position.copy( origin );
  31572. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31573. this.line.matrixAutoUpdate = false;
  31574. this.add( this.line );
  31575. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  31576. this.cone.matrixAutoUpdate = false;
  31577. this.add( this.cone );
  31578. this.setDirection( dir );
  31579. this.setLength( length, headLength, headWidth );
  31580. }
  31581. setDirection( dir ) {
  31582. // dir is assumed to be normalized
  31583. if ( dir.y > 0.99999 ) {
  31584. this.quaternion.set( 0, 0, 0, 1 );
  31585. } else if ( dir.y < - 0.99999 ) {
  31586. this.quaternion.set( 1, 0, 0, 0 );
  31587. } else {
  31588. _axis.set( dir.z, 0, - dir.x ).normalize();
  31589. const radians = Math.acos( dir.y );
  31590. this.quaternion.setFromAxisAngle( _axis, radians );
  31591. }
  31592. }
  31593. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  31594. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  31595. this.line.updateMatrix();
  31596. this.cone.scale.set( headWidth, headLength, headWidth );
  31597. this.cone.position.y = length;
  31598. this.cone.updateMatrix();
  31599. }
  31600. setColor( color ) {
  31601. this.line.material.color.set( color );
  31602. this.cone.material.color.set( color );
  31603. }
  31604. copy( source ) {
  31605. super.copy( source, false );
  31606. this.line.copy( source.line );
  31607. this.cone.copy( source.cone );
  31608. return this;
  31609. }
  31610. dispose() {
  31611. this.line.geometry.dispose();
  31612. this.line.material.dispose();
  31613. this.cone.geometry.dispose();
  31614. this.cone.material.dispose();
  31615. }
  31616. }
  31617. class AxesHelper extends LineSegments {
  31618. constructor( size = 1 ) {
  31619. const vertices = [
  31620. 0, 0, 0, size, 0, 0,
  31621. 0, 0, 0, 0, size, 0,
  31622. 0, 0, 0, 0, 0, size
  31623. ];
  31624. const colors = [
  31625. 1, 0, 0, 1, 0.6, 0,
  31626. 0, 1, 0, 0.6, 1, 0,
  31627. 0, 0, 1, 0, 0.6, 1
  31628. ];
  31629. const geometry = new BufferGeometry();
  31630. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31631. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31632. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31633. super( geometry, material );
  31634. this.type = 'AxesHelper';
  31635. }
  31636. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  31637. const color = new Color();
  31638. const array = this.geometry.attributes.color.array;
  31639. color.set( xAxisColor );
  31640. color.toArray( array, 0 );
  31641. color.toArray( array, 3 );
  31642. color.set( yAxisColor );
  31643. color.toArray( array, 6 );
  31644. color.toArray( array, 9 );
  31645. color.set( zAxisColor );
  31646. color.toArray( array, 12 );
  31647. color.toArray( array, 15 );
  31648. this.geometry.attributes.color.needsUpdate = true;
  31649. return this;
  31650. }
  31651. dispose() {
  31652. this.geometry.dispose();
  31653. this.material.dispose();
  31654. }
  31655. }
  31656. class ShapePath {
  31657. constructor() {
  31658. this.type = 'ShapePath';
  31659. this.color = new Color();
  31660. this.subPaths = [];
  31661. this.currentPath = null;
  31662. }
  31663. moveTo( x, y ) {
  31664. this.currentPath = new Path();
  31665. this.subPaths.push( this.currentPath );
  31666. this.currentPath.moveTo( x, y );
  31667. return this;
  31668. }
  31669. lineTo( x, y ) {
  31670. this.currentPath.lineTo( x, y );
  31671. return this;
  31672. }
  31673. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31674. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31675. return this;
  31676. }
  31677. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31678. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31679. return this;
  31680. }
  31681. splineThru( pts ) {
  31682. this.currentPath.splineThru( pts );
  31683. return this;
  31684. }
  31685. toShapes( isCCW ) {
  31686. function toShapesNoHoles( inSubpaths ) {
  31687. const shapes = [];
  31688. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31689. const tmpPath = inSubpaths[ i ];
  31690. const tmpShape = new Shape();
  31691. tmpShape.curves = tmpPath.curves;
  31692. shapes.push( tmpShape );
  31693. }
  31694. return shapes;
  31695. }
  31696. function isPointInsidePolygon( inPt, inPolygon ) {
  31697. const polyLen = inPolygon.length;
  31698. // inPt on polygon contour => immediate success or
  31699. // toggling of inside/outside at every single! intersection point of an edge
  31700. // with the horizontal line through inPt, left of inPt
  31701. // not counting lowerY endpoints of edges and whole edges on that line
  31702. let inside = false;
  31703. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31704. let edgeLowPt = inPolygon[ p ];
  31705. let edgeHighPt = inPolygon[ q ];
  31706. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31707. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31708. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31709. // not parallel
  31710. if ( edgeDy < 0 ) {
  31711. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31712. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31713. }
  31714. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31715. if ( inPt.y === edgeLowPt.y ) {
  31716. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31717. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31718. } else {
  31719. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31720. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31721. if ( perpEdge < 0 ) continue;
  31722. inside = ! inside; // true intersection left of inPt
  31723. }
  31724. } else {
  31725. // parallel or collinear
  31726. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31727. // edge lies on the same horizontal line as inPt
  31728. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31729. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31730. // continue;
  31731. }
  31732. }
  31733. return inside;
  31734. }
  31735. const isClockWise = ShapeUtils.isClockWise;
  31736. const subPaths = this.subPaths;
  31737. if ( subPaths.length === 0 ) return [];
  31738. let solid, tmpPath, tmpShape;
  31739. const shapes = [];
  31740. if ( subPaths.length === 1 ) {
  31741. tmpPath = subPaths[ 0 ];
  31742. tmpShape = new Shape();
  31743. tmpShape.curves = tmpPath.curves;
  31744. shapes.push( tmpShape );
  31745. return shapes;
  31746. }
  31747. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31748. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31749. // console.log("Holes first", holesFirst);
  31750. const betterShapeHoles = [];
  31751. const newShapes = [];
  31752. let newShapeHoles = [];
  31753. let mainIdx = 0;
  31754. let tmpPoints;
  31755. newShapes[ mainIdx ] = undefined;
  31756. newShapeHoles[ mainIdx ] = [];
  31757. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31758. tmpPath = subPaths[ i ];
  31759. tmpPoints = tmpPath.getPoints();
  31760. solid = isClockWise( tmpPoints );
  31761. solid = isCCW ? ! solid : solid;
  31762. if ( solid ) {
  31763. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31764. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31765. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31766. if ( holesFirst ) mainIdx ++;
  31767. newShapeHoles[ mainIdx ] = [];
  31768. //console.log('cw', i);
  31769. } else {
  31770. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31771. //console.log('ccw', i);
  31772. }
  31773. }
  31774. // only Holes? -> probably all Shapes with wrong orientation
  31775. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31776. if ( newShapes.length > 1 ) {
  31777. let ambiguous = false;
  31778. let toChange = 0;
  31779. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31780. betterShapeHoles[ sIdx ] = [];
  31781. }
  31782. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31783. const sho = newShapeHoles[ sIdx ];
  31784. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31785. const ho = sho[ hIdx ];
  31786. let hole_unassigned = true;
  31787. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31788. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31789. if ( sIdx !== s2Idx ) toChange ++;
  31790. if ( hole_unassigned ) {
  31791. hole_unassigned = false;
  31792. betterShapeHoles[ s2Idx ].push( ho );
  31793. } else {
  31794. ambiguous = true;
  31795. }
  31796. }
  31797. }
  31798. if ( hole_unassigned ) {
  31799. betterShapeHoles[ sIdx ].push( ho );
  31800. }
  31801. }
  31802. }
  31803. if ( toChange > 0 && ambiguous === false ) {
  31804. newShapeHoles = betterShapeHoles;
  31805. }
  31806. }
  31807. let tmpHoles;
  31808. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31809. tmpShape = newShapes[ i ].s;
  31810. shapes.push( tmpShape );
  31811. tmpHoles = newShapeHoles[ i ];
  31812. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31813. tmpShape.holes.push( tmpHoles[ j ].h );
  31814. }
  31815. }
  31816. //console.log("shape", shapes);
  31817. return shapes;
  31818. }
  31819. }
  31820. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  31821. constructor( width = 1, height = 1, count = 1, options = {} ) {
  31822. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  31823. super( width, height, { ...options, count } );
  31824. this.isWebGLMultipleRenderTargets = true;
  31825. }
  31826. get texture() {
  31827. return this.textures;
  31828. }
  31829. }
  31830. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31831. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31832. revision: REVISION,
  31833. } } ) );
  31834. }
  31835. if ( typeof window !== 'undefined' ) {
  31836. if ( window.__THREE__ ) {
  31837. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31838. } else {
  31839. window.__THREE__ = REVISION;
  31840. }
  31841. }
  31842. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, createCanvasElement };