three.cjs 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '149';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const TwoPassDoubleSide = 2; // r149
  22. const NoBlending = 0;
  23. const NormalBlending = 1;
  24. const AdditiveBlending = 2;
  25. const SubtractiveBlending = 3;
  26. const MultiplyBlending = 4;
  27. const CustomBlending = 5;
  28. const AddEquation = 100;
  29. const SubtractEquation = 101;
  30. const ReverseSubtractEquation = 102;
  31. const MinEquation = 103;
  32. const MaxEquation = 104;
  33. const ZeroFactor = 200;
  34. const OneFactor = 201;
  35. const SrcColorFactor = 202;
  36. const OneMinusSrcColorFactor = 203;
  37. const SrcAlphaFactor = 204;
  38. const OneMinusSrcAlphaFactor = 205;
  39. const DstAlphaFactor = 206;
  40. const OneMinusDstAlphaFactor = 207;
  41. const DstColorFactor = 208;
  42. const OneMinusDstColorFactor = 209;
  43. const SrcAlphaSaturateFactor = 210;
  44. const NeverDepth = 0;
  45. const AlwaysDepth = 1;
  46. const LessDepth = 2;
  47. const LessEqualDepth = 3;
  48. const EqualDepth = 4;
  49. const GreaterEqualDepth = 5;
  50. const GreaterDepth = 6;
  51. const NotEqualDepth = 7;
  52. const MultiplyOperation = 0;
  53. const MixOperation = 1;
  54. const AddOperation = 2;
  55. const NoToneMapping = 0;
  56. const LinearToneMapping = 1;
  57. const ReinhardToneMapping = 2;
  58. const CineonToneMapping = 3;
  59. const ACESFilmicToneMapping = 4;
  60. const CustomToneMapping = 5;
  61. const UVMapping = 300;
  62. const CubeReflectionMapping = 301;
  63. const CubeRefractionMapping = 302;
  64. const EquirectangularReflectionMapping = 303;
  65. const EquirectangularRefractionMapping = 304;
  66. const CubeUVReflectionMapping = 306;
  67. const RepeatWrapping = 1000;
  68. const ClampToEdgeWrapping = 1001;
  69. const MirroredRepeatWrapping = 1002;
  70. const NearestFilter = 1003;
  71. const NearestMipmapNearestFilter = 1004;
  72. const NearestMipMapNearestFilter = 1004;
  73. const NearestMipmapLinearFilter = 1005;
  74. const NearestMipMapLinearFilter = 1005;
  75. const LinearFilter = 1006;
  76. const LinearMipmapNearestFilter = 1007;
  77. const LinearMipMapNearestFilter = 1007;
  78. const LinearMipmapLinearFilter = 1008;
  79. const LinearMipMapLinearFilter = 1008;
  80. const UnsignedByteType = 1009;
  81. const ByteType = 1010;
  82. const ShortType = 1011;
  83. const UnsignedShortType = 1012;
  84. const IntType = 1013;
  85. const UnsignedIntType = 1014;
  86. const FloatType = 1015;
  87. const HalfFloatType = 1016;
  88. const UnsignedShort4444Type = 1017;
  89. const UnsignedShort5551Type = 1018;
  90. const UnsignedInt248Type = 1020;
  91. const AlphaFormat = 1021;
  92. const RGBAFormat = 1023;
  93. const LuminanceFormat = 1024;
  94. const LuminanceAlphaFormat = 1025;
  95. const DepthFormat = 1026;
  96. const DepthStencilFormat = 1027;
  97. const RedFormat = 1028;
  98. const RedIntegerFormat = 1029;
  99. const RGFormat = 1030;
  100. const RGIntegerFormat = 1031;
  101. const RGBAIntegerFormat = 1033;
  102. const RGB_S3TC_DXT1_Format = 33776;
  103. const RGBA_S3TC_DXT1_Format = 33777;
  104. const RGBA_S3TC_DXT3_Format = 33778;
  105. const RGBA_S3TC_DXT5_Format = 33779;
  106. const RGB_PVRTC_4BPPV1_Format = 35840;
  107. const RGB_PVRTC_2BPPV1_Format = 35841;
  108. const RGBA_PVRTC_4BPPV1_Format = 35842;
  109. const RGBA_PVRTC_2BPPV1_Format = 35843;
  110. const RGB_ETC1_Format = 36196;
  111. const RGB_ETC2_Format = 37492;
  112. const RGBA_ETC2_EAC_Format = 37496;
  113. const RGBA_ASTC_4x4_Format = 37808;
  114. const RGBA_ASTC_5x4_Format = 37809;
  115. const RGBA_ASTC_5x5_Format = 37810;
  116. const RGBA_ASTC_6x5_Format = 37811;
  117. const RGBA_ASTC_6x6_Format = 37812;
  118. const RGBA_ASTC_8x5_Format = 37813;
  119. const RGBA_ASTC_8x6_Format = 37814;
  120. const RGBA_ASTC_8x8_Format = 37815;
  121. const RGBA_ASTC_10x5_Format = 37816;
  122. const RGBA_ASTC_10x6_Format = 37817;
  123. const RGBA_ASTC_10x8_Format = 37818;
  124. const RGBA_ASTC_10x10_Format = 37819;
  125. const RGBA_ASTC_12x10_Format = 37820;
  126. const RGBA_ASTC_12x12_Format = 37821;
  127. const RGBA_BPTC_Format = 36492;
  128. const RED_RGTC1_Format = 36283;
  129. const SIGNED_RED_RGTC1_Format = 36284;
  130. const RED_GREEN_RGTC2_Format = 36285;
  131. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  132. const LoopOnce = 2200;
  133. const LoopRepeat = 2201;
  134. const LoopPingPong = 2202;
  135. const InterpolateDiscrete = 2300;
  136. const InterpolateLinear = 2301;
  137. const InterpolateSmooth = 2302;
  138. const ZeroCurvatureEnding = 2400;
  139. const ZeroSlopeEnding = 2401;
  140. const WrapAroundEnding = 2402;
  141. const NormalAnimationBlendMode = 2500;
  142. const AdditiveAnimationBlendMode = 2501;
  143. const TrianglesDrawMode = 0;
  144. const TriangleStripDrawMode = 1;
  145. const TriangleFanDrawMode = 2;
  146. const LinearEncoding = 3000;
  147. const sRGBEncoding = 3001;
  148. const BasicDepthPacking = 3200;
  149. const RGBADepthPacking = 3201;
  150. const TangentSpaceNormalMap = 0;
  151. const ObjectSpaceNormalMap = 1;
  152. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  153. const NoColorSpace = '';
  154. const SRGBColorSpace = 'srgb';
  155. const LinearSRGBColorSpace = 'srgb-linear';
  156. const ZeroStencilOp = 0;
  157. const KeepStencilOp = 7680;
  158. const ReplaceStencilOp = 7681;
  159. const IncrementStencilOp = 7682;
  160. const DecrementStencilOp = 7683;
  161. const IncrementWrapStencilOp = 34055;
  162. const DecrementWrapStencilOp = 34056;
  163. const InvertStencilOp = 5386;
  164. const NeverStencilFunc = 512;
  165. const LessStencilFunc = 513;
  166. const EqualStencilFunc = 514;
  167. const LessEqualStencilFunc = 515;
  168. const GreaterStencilFunc = 516;
  169. const NotEqualStencilFunc = 517;
  170. const GreaterEqualStencilFunc = 518;
  171. const AlwaysStencilFunc = 519;
  172. const StaticDrawUsage = 35044;
  173. const DynamicDrawUsage = 35048;
  174. const StreamDrawUsage = 35040;
  175. const StaticReadUsage = 35045;
  176. const DynamicReadUsage = 35049;
  177. const StreamReadUsage = 35041;
  178. const StaticCopyUsage = 35046;
  179. const DynamicCopyUsage = 35050;
  180. const StreamCopyUsage = 35042;
  181. const GLSL1 = '100';
  182. const GLSL3 = '300 es';
  183. const _SRGBAFormat = 1035; // fallback for WebGL 1
  184. /**
  185. * https://github.com/mrdoob/eventdispatcher.js/
  186. */
  187. class EventDispatcher {
  188. addEventListener( type, listener ) {
  189. if ( this._listeners === undefined ) this._listeners = {};
  190. const listeners = this._listeners;
  191. if ( listeners[ type ] === undefined ) {
  192. listeners[ type ] = [];
  193. }
  194. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  195. listeners[ type ].push( listener );
  196. }
  197. }
  198. hasEventListener( type, listener ) {
  199. if ( this._listeners === undefined ) return false;
  200. const listeners = this._listeners;
  201. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  202. }
  203. removeEventListener( type, listener ) {
  204. if ( this._listeners === undefined ) return;
  205. const listeners = this._listeners;
  206. const listenerArray = listeners[ type ];
  207. if ( listenerArray !== undefined ) {
  208. const index = listenerArray.indexOf( listener );
  209. if ( index !== - 1 ) {
  210. listenerArray.splice( index, 1 );
  211. }
  212. }
  213. }
  214. dispatchEvent( event ) {
  215. if ( this._listeners === undefined ) return;
  216. const listeners = this._listeners;
  217. const listenerArray = listeners[ event.type ];
  218. if ( listenerArray !== undefined ) {
  219. event.target = this;
  220. // Make a copy, in case listeners are removed while iterating.
  221. const array = listenerArray.slice( 0 );
  222. for ( let i = 0, l = array.length; i < l; i ++ ) {
  223. array[ i ].call( this, event );
  224. }
  225. event.target = null;
  226. }
  227. }
  228. }
  229. 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' ];
  230. let _seed = 1234567;
  231. const DEG2RAD = Math.PI / 180;
  232. const RAD2DEG = 180 / Math.PI;
  233. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  234. function generateUUID() {
  235. const d0 = Math.random() * 0xffffffff | 0;
  236. const d1 = Math.random() * 0xffffffff | 0;
  237. const d2 = Math.random() * 0xffffffff | 0;
  238. const d3 = Math.random() * 0xffffffff | 0;
  239. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  240. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  241. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  242. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  243. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  244. return uuid.toLowerCase();
  245. }
  246. function clamp( value, min, max ) {
  247. return Math.max( min, Math.min( max, value ) );
  248. }
  249. // compute euclidean modulo of m % n
  250. // https://en.wikipedia.org/wiki/Modulo_operation
  251. function euclideanModulo( n, m ) {
  252. return ( ( n % m ) + m ) % m;
  253. }
  254. // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear( x, a1, a2, b1, b2 ) {
  256. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  257. }
  258. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  259. function inverseLerp( x, y, value ) {
  260. if ( x !== y ) {
  261. return ( value - x ) / ( y - x );
  262. } else {
  263. return 0;
  264. }
  265. }
  266. // https://en.wikipedia.org/wiki/Linear_interpolation
  267. function lerp( x, y, t ) {
  268. return ( 1 - t ) * x + t * y;
  269. }
  270. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  271. function damp( x, y, lambda, dt ) {
  272. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  273. }
  274. // https://www.desmos.com/calculator/vcsjnyz7x4
  275. function pingpong( x, length = 1 ) {
  276. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  277. }
  278. // http://en.wikipedia.org/wiki/Smoothstep
  279. function smoothstep( x, min, max ) {
  280. if ( x <= min ) return 0;
  281. if ( x >= max ) return 1;
  282. x = ( x - min ) / ( max - min );
  283. return x * x * ( 3 - 2 * x );
  284. }
  285. function smootherstep( x, min, max ) {
  286. if ( x <= min ) return 0;
  287. if ( x >= max ) return 1;
  288. x = ( x - min ) / ( max - min );
  289. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  290. }
  291. // Random integer from <low, high> interval
  292. function randInt( low, high ) {
  293. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  294. }
  295. // Random float from <low, high> interval
  296. function randFloat( low, high ) {
  297. return low + Math.random() * ( high - low );
  298. }
  299. // Random float from <-range/2, range/2> interval
  300. function randFloatSpread( range ) {
  301. return range * ( 0.5 - Math.random() );
  302. }
  303. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  304. function seededRandom( s ) {
  305. if ( s !== undefined ) _seed = s;
  306. // Mulberry32 generator
  307. let t = _seed += 0x6D2B79F5;
  308. t = Math.imul( t ^ t >>> 15, t | 1 );
  309. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  310. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  311. }
  312. function degToRad( degrees ) {
  313. return degrees * DEG2RAD;
  314. }
  315. function radToDeg( radians ) {
  316. return radians * RAD2DEG;
  317. }
  318. function isPowerOfTwo( value ) {
  319. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  320. }
  321. function ceilPowerOfTwo( value ) {
  322. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  323. }
  324. function floorPowerOfTwo( value ) {
  325. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  326. }
  327. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  328. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  329. // rotations are applied to the axes in the order specified by 'order'
  330. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  331. // angles are in radians
  332. const cos = Math.cos;
  333. const sin = Math.sin;
  334. const c2 = cos( b / 2 );
  335. const s2 = sin( b / 2 );
  336. const c13 = cos( ( a + c ) / 2 );
  337. const s13 = sin( ( a + c ) / 2 );
  338. const c1_3 = cos( ( a - c ) / 2 );
  339. const s1_3 = sin( ( a - c ) / 2 );
  340. const c3_1 = cos( ( c - a ) / 2 );
  341. const s3_1 = sin( ( c - a ) / 2 );
  342. switch ( order ) {
  343. case 'XYX':
  344. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  345. break;
  346. case 'YZY':
  347. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  348. break;
  349. case 'ZXZ':
  350. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  351. break;
  352. case 'XZX':
  353. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  354. break;
  355. case 'YXY':
  356. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  357. break;
  358. case 'ZYZ':
  359. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  360. break;
  361. default:
  362. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  363. }
  364. }
  365. function denormalize( value, array ) {
  366. switch ( array.constructor ) {
  367. case Float32Array:
  368. return value;
  369. case Uint16Array:
  370. return value / 65535.0;
  371. case Uint8Array:
  372. return value / 255.0;
  373. case Int16Array:
  374. return Math.max( value / 32767.0, - 1.0 );
  375. case Int8Array:
  376. return Math.max( value / 127.0, - 1.0 );
  377. default:
  378. throw new Error( 'Invalid component type.' );
  379. }
  380. }
  381. function normalize( value, array ) {
  382. switch ( array.constructor ) {
  383. case Float32Array:
  384. return value;
  385. case Uint16Array:
  386. return Math.round( value * 65535.0 );
  387. case Uint8Array:
  388. return Math.round( value * 255.0 );
  389. case Int16Array:
  390. return Math.round( value * 32767.0 );
  391. case Int8Array:
  392. return Math.round( value * 127.0 );
  393. default:
  394. throw new Error( 'Invalid component type.' );
  395. }
  396. }
  397. var MathUtils = /*#__PURE__*/Object.freeze({
  398. __proto__: null,
  399. DEG2RAD: DEG2RAD,
  400. RAD2DEG: RAD2DEG,
  401. ceilPowerOfTwo: ceilPowerOfTwo,
  402. clamp: clamp,
  403. damp: damp,
  404. degToRad: degToRad,
  405. denormalize: denormalize,
  406. euclideanModulo: euclideanModulo,
  407. floorPowerOfTwo: floorPowerOfTwo,
  408. generateUUID: generateUUID,
  409. inverseLerp: inverseLerp,
  410. isPowerOfTwo: isPowerOfTwo,
  411. lerp: lerp,
  412. mapLinear: mapLinear,
  413. normalize: normalize,
  414. pingpong: pingpong,
  415. radToDeg: radToDeg,
  416. randFloat: randFloat,
  417. randFloatSpread: randFloatSpread,
  418. randInt: randInt,
  419. seededRandom: seededRandom,
  420. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  421. smootherstep: smootherstep,
  422. smoothstep: smoothstep
  423. });
  424. class Vector2 {
  425. constructor( x = 0, y = 0 ) {
  426. Vector2.prototype.isVector2 = true;
  427. this.x = x;
  428. this.y = y;
  429. }
  430. get width() {
  431. return this.x;
  432. }
  433. set width( value ) {
  434. this.x = value;
  435. }
  436. get height() {
  437. return this.y;
  438. }
  439. set height( value ) {
  440. this.y = value;
  441. }
  442. set( x, y ) {
  443. this.x = x;
  444. this.y = y;
  445. return this;
  446. }
  447. setScalar( scalar ) {
  448. this.x = scalar;
  449. this.y = scalar;
  450. return this;
  451. }
  452. setX( x ) {
  453. this.x = x;
  454. return this;
  455. }
  456. setY( y ) {
  457. this.y = y;
  458. return this;
  459. }
  460. setComponent( index, value ) {
  461. switch ( index ) {
  462. case 0: this.x = value; break;
  463. case 1: this.y = value; break;
  464. default: throw new Error( 'index is out of range: ' + index );
  465. }
  466. return this;
  467. }
  468. getComponent( index ) {
  469. switch ( index ) {
  470. case 0: return this.x;
  471. case 1: return this.y;
  472. default: throw new Error( 'index is out of range: ' + index );
  473. }
  474. }
  475. clone() {
  476. return new this.constructor( this.x, this.y );
  477. }
  478. copy( v ) {
  479. this.x = v.x;
  480. this.y = v.y;
  481. return this;
  482. }
  483. add( v ) {
  484. this.x += v.x;
  485. this.y += v.y;
  486. return this;
  487. }
  488. addScalar( s ) {
  489. this.x += s;
  490. this.y += s;
  491. return this;
  492. }
  493. addVectors( a, b ) {
  494. this.x = a.x + b.x;
  495. this.y = a.y + b.y;
  496. return this;
  497. }
  498. addScaledVector( v, s ) {
  499. this.x += v.x * s;
  500. this.y += v.y * s;
  501. return this;
  502. }
  503. sub( v ) {
  504. this.x -= v.x;
  505. this.y -= v.y;
  506. return this;
  507. }
  508. subScalar( s ) {
  509. this.x -= s;
  510. this.y -= s;
  511. return this;
  512. }
  513. subVectors( a, b ) {
  514. this.x = a.x - b.x;
  515. this.y = a.y - b.y;
  516. return this;
  517. }
  518. multiply( v ) {
  519. this.x *= v.x;
  520. this.y *= v.y;
  521. return this;
  522. }
  523. multiplyScalar( scalar ) {
  524. this.x *= scalar;
  525. this.y *= scalar;
  526. return this;
  527. }
  528. divide( v ) {
  529. this.x /= v.x;
  530. this.y /= v.y;
  531. return this;
  532. }
  533. divideScalar( scalar ) {
  534. return this.multiplyScalar( 1 / scalar );
  535. }
  536. applyMatrix3( m ) {
  537. const x = this.x, y = this.y;
  538. const e = m.elements;
  539. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  540. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  541. return this;
  542. }
  543. min( v ) {
  544. this.x = Math.min( this.x, v.x );
  545. this.y = Math.min( this.y, v.y );
  546. return this;
  547. }
  548. max( v ) {
  549. this.x = Math.max( this.x, v.x );
  550. this.y = Math.max( this.y, v.y );
  551. return this;
  552. }
  553. clamp( min, max ) {
  554. // assumes min < max, componentwise
  555. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  556. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  557. return this;
  558. }
  559. clampScalar( minVal, maxVal ) {
  560. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  561. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  562. return this;
  563. }
  564. clampLength( min, max ) {
  565. const length = this.length();
  566. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  567. }
  568. floor() {
  569. this.x = Math.floor( this.x );
  570. this.y = Math.floor( this.y );
  571. return this;
  572. }
  573. ceil() {
  574. this.x = Math.ceil( this.x );
  575. this.y = Math.ceil( this.y );
  576. return this;
  577. }
  578. round() {
  579. this.x = Math.round( this.x );
  580. this.y = Math.round( this.y );
  581. return this;
  582. }
  583. roundToZero() {
  584. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  585. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  586. return this;
  587. }
  588. negate() {
  589. this.x = - this.x;
  590. this.y = - this.y;
  591. return this;
  592. }
  593. dot( v ) {
  594. return this.x * v.x + this.y * v.y;
  595. }
  596. cross( v ) {
  597. return this.x * v.y - this.y * v.x;
  598. }
  599. lengthSq() {
  600. return this.x * this.x + this.y * this.y;
  601. }
  602. length() {
  603. return Math.sqrt( this.x * this.x + this.y * this.y );
  604. }
  605. manhattanLength() {
  606. return Math.abs( this.x ) + Math.abs( this.y );
  607. }
  608. normalize() {
  609. return this.divideScalar( this.length() || 1 );
  610. }
  611. angle() {
  612. // computes the angle in radians with respect to the positive x-axis
  613. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  614. return angle;
  615. }
  616. distanceTo( v ) {
  617. return Math.sqrt( this.distanceToSquared( v ) );
  618. }
  619. distanceToSquared( v ) {
  620. const dx = this.x - v.x, dy = this.y - v.y;
  621. return dx * dx + dy * dy;
  622. }
  623. manhattanDistanceTo( v ) {
  624. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  625. }
  626. setLength( length ) {
  627. return this.normalize().multiplyScalar( length );
  628. }
  629. lerp( v, alpha ) {
  630. this.x += ( v.x - this.x ) * alpha;
  631. this.y += ( v.y - this.y ) * alpha;
  632. return this;
  633. }
  634. lerpVectors( v1, v2, alpha ) {
  635. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  636. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  637. return this;
  638. }
  639. equals( v ) {
  640. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  641. }
  642. fromArray( array, offset = 0 ) {
  643. this.x = array[ offset ];
  644. this.y = array[ offset + 1 ];
  645. return this;
  646. }
  647. toArray( array = [], offset = 0 ) {
  648. array[ offset ] = this.x;
  649. array[ offset + 1 ] = this.y;
  650. return array;
  651. }
  652. fromBufferAttribute( attribute, index ) {
  653. this.x = attribute.getX( index );
  654. this.y = attribute.getY( index );
  655. return this;
  656. }
  657. rotateAround( center, angle ) {
  658. const c = Math.cos( angle ), s = Math.sin( angle );
  659. const x = this.x - center.x;
  660. const y = this.y - center.y;
  661. this.x = x * c - y * s + center.x;
  662. this.y = x * s + y * c + center.y;
  663. return this;
  664. }
  665. random() {
  666. this.x = Math.random();
  667. this.y = Math.random();
  668. return this;
  669. }
  670. *[ Symbol.iterator ]() {
  671. yield this.x;
  672. yield this.y;
  673. }
  674. }
  675. class Matrix3 {
  676. constructor() {
  677. Matrix3.prototype.isMatrix3 = true;
  678. this.elements = [
  679. 1, 0, 0,
  680. 0, 1, 0,
  681. 0, 0, 1
  682. ];
  683. }
  684. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  685. const te = this.elements;
  686. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  687. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  688. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  689. return this;
  690. }
  691. identity() {
  692. this.set(
  693. 1, 0, 0,
  694. 0, 1, 0,
  695. 0, 0, 1
  696. );
  697. return this;
  698. }
  699. copy( m ) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  703. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  704. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  705. return this;
  706. }
  707. extractBasis( xAxis, yAxis, zAxis ) {
  708. xAxis.setFromMatrix3Column( this, 0 );
  709. yAxis.setFromMatrix3Column( this, 1 );
  710. zAxis.setFromMatrix3Column( this, 2 );
  711. return this;
  712. }
  713. setFromMatrix4( m ) {
  714. const me = m.elements;
  715. this.set(
  716. me[ 0 ], me[ 4 ], me[ 8 ],
  717. me[ 1 ], me[ 5 ], me[ 9 ],
  718. me[ 2 ], me[ 6 ], me[ 10 ]
  719. );
  720. return this;
  721. }
  722. multiply( m ) {
  723. return this.multiplyMatrices( this, m );
  724. }
  725. premultiply( m ) {
  726. return this.multiplyMatrices( m, this );
  727. }
  728. multiplyMatrices( a, b ) {
  729. const ae = a.elements;
  730. const be = b.elements;
  731. const te = this.elements;
  732. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  733. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  734. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  735. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  736. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  737. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  738. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  739. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  740. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  741. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  742. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  743. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  744. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  745. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  746. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  747. return this;
  748. }
  749. multiplyScalar( s ) {
  750. const te = this.elements;
  751. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  752. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  753. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  754. return this;
  755. }
  756. determinant() {
  757. const te = this.elements;
  758. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  759. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  760. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  761. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  762. }
  763. invert() {
  764. const te = this.elements,
  765. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  766. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  767. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  768. t11 = n33 * n22 - n32 * n23,
  769. t12 = n32 * n13 - n33 * n12,
  770. t13 = n23 * n12 - n22 * n13,
  771. det = n11 * t11 + n21 * t12 + n31 * t13;
  772. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  773. const detInv = 1 / det;
  774. te[ 0 ] = t11 * detInv;
  775. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  776. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  777. te[ 3 ] = t12 * detInv;
  778. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  779. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  780. te[ 6 ] = t13 * detInv;
  781. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  782. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  783. return this;
  784. }
  785. transpose() {
  786. let tmp;
  787. const m = this.elements;
  788. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  789. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  790. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  791. return this;
  792. }
  793. getNormalMatrix( matrix4 ) {
  794. return this.setFromMatrix4( matrix4 ).invert().transpose();
  795. }
  796. transposeIntoArray( r ) {
  797. const m = this.elements;
  798. r[ 0 ] = m[ 0 ];
  799. r[ 1 ] = m[ 3 ];
  800. r[ 2 ] = m[ 6 ];
  801. r[ 3 ] = m[ 1 ];
  802. r[ 4 ] = m[ 4 ];
  803. r[ 5 ] = m[ 7 ];
  804. r[ 6 ] = m[ 2 ];
  805. r[ 7 ] = m[ 5 ];
  806. r[ 8 ] = m[ 8 ];
  807. return this;
  808. }
  809. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  810. const c = Math.cos( rotation );
  811. const s = Math.sin( rotation );
  812. this.set(
  813. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  814. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  815. 0, 0, 1
  816. );
  817. return this;
  818. }
  819. //
  820. scale( sx, sy ) {
  821. this.premultiply( _m3.makeScale( sx, sy ) );
  822. return this;
  823. }
  824. rotate( theta ) {
  825. this.premultiply( _m3.makeRotation( - theta ) );
  826. return this;
  827. }
  828. translate( tx, ty ) {
  829. this.premultiply( _m3.makeTranslation( tx, ty ) );
  830. return this;
  831. }
  832. // for 2D Transforms
  833. makeTranslation( x, y ) {
  834. this.set(
  835. 1, 0, x,
  836. 0, 1, y,
  837. 0, 0, 1
  838. );
  839. return this;
  840. }
  841. makeRotation( theta ) {
  842. // counterclockwise
  843. const c = Math.cos( theta );
  844. const s = Math.sin( theta );
  845. this.set(
  846. c, - s, 0,
  847. s, c, 0,
  848. 0, 0, 1
  849. );
  850. return this;
  851. }
  852. makeScale( x, y ) {
  853. this.set(
  854. x, 0, 0,
  855. 0, y, 0,
  856. 0, 0, 1
  857. );
  858. return this;
  859. }
  860. //
  861. equals( matrix ) {
  862. const te = this.elements;
  863. const me = matrix.elements;
  864. for ( let i = 0; i < 9; i ++ ) {
  865. if ( te[ i ] !== me[ i ] ) return false;
  866. }
  867. return true;
  868. }
  869. fromArray( array, offset = 0 ) {
  870. for ( let i = 0; i < 9; i ++ ) {
  871. this.elements[ i ] = array[ i + offset ];
  872. }
  873. return this;
  874. }
  875. toArray( array = [], offset = 0 ) {
  876. const te = this.elements;
  877. array[ offset ] = te[ 0 ];
  878. array[ offset + 1 ] = te[ 1 ];
  879. array[ offset + 2 ] = te[ 2 ];
  880. array[ offset + 3 ] = te[ 3 ];
  881. array[ offset + 4 ] = te[ 4 ];
  882. array[ offset + 5 ] = te[ 5 ];
  883. array[ offset + 6 ] = te[ 6 ];
  884. array[ offset + 7 ] = te[ 7 ];
  885. array[ offset + 8 ] = te[ 8 ];
  886. return array;
  887. }
  888. clone() {
  889. return new this.constructor().fromArray( this.elements );
  890. }
  891. }
  892. const _m3 = /*@__PURE__*/ new Matrix3();
  893. function arrayNeedsUint32( array ) {
  894. // assumes larger values usually on last
  895. for ( let i = array.length - 1; i >= 0; -- i ) {
  896. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  897. }
  898. return false;
  899. }
  900. const TYPED_ARRAYS = {
  901. Int8Array: Int8Array,
  902. Uint8Array: Uint8Array,
  903. Uint8ClampedArray: Uint8ClampedArray,
  904. Int16Array: Int16Array,
  905. Uint16Array: Uint16Array,
  906. Int32Array: Int32Array,
  907. Uint32Array: Uint32Array,
  908. Float32Array: Float32Array,
  909. Float64Array: Float64Array
  910. };
  911. function getTypedArray( type, buffer ) {
  912. return new TYPED_ARRAYS[ type ]( buffer );
  913. }
  914. function createElementNS( name ) {
  915. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  916. }
  917. function SRGBToLinear( c ) {
  918. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  919. }
  920. function LinearToSRGB( c ) {
  921. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  922. }
  923. // JavaScript RGB-to-RGB transforms, defined as
  924. // FN[InputColorSpace][OutputColorSpace] callback functions.
  925. const FN = {
  926. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  927. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  928. };
  929. const ColorManagement = {
  930. legacyMode: true,
  931. get workingColorSpace() {
  932. return LinearSRGBColorSpace;
  933. },
  934. set workingColorSpace( colorSpace ) {
  935. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  936. },
  937. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  938. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  939. return color;
  940. }
  941. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  942. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  943. color.r = fn( color.r );
  944. color.g = fn( color.g );
  945. color.b = fn( color.b );
  946. return color;
  947. }
  948. throw new Error( 'Unsupported color space conversion.' );
  949. },
  950. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  951. return this.convert( color, this.workingColorSpace, targetColorSpace );
  952. },
  953. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  954. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  955. },
  956. };
  957. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  958. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  959. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  960. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  961. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  962. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  963. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  964. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  965. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  966. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  967. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  968. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  969. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  970. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  971. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  972. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  973. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  974. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  975. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  976. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  977. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  978. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  979. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  980. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  981. const _rgb$1 = { r: 0, g: 0, b: 0 };
  982. const _hslA = { h: 0, s: 0, l: 0 };
  983. const _hslB = { h: 0, s: 0, l: 0 };
  984. function hue2rgb( p, q, t ) {
  985. if ( t < 0 ) t += 1;
  986. if ( t > 1 ) t -= 1;
  987. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  988. if ( t < 1 / 2 ) return q;
  989. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  990. return p;
  991. }
  992. function toComponents( source, target ) {
  993. target.r = source.r;
  994. target.g = source.g;
  995. target.b = source.b;
  996. return target;
  997. }
  998. class Color {
  999. constructor( r, g, b ) {
  1000. this.isColor = true;
  1001. this.r = 1;
  1002. this.g = 1;
  1003. this.b = 1;
  1004. if ( g === undefined && b === undefined ) {
  1005. // r is THREE.Color, hex or string
  1006. return this.set( r );
  1007. }
  1008. return this.setRGB( r, g, b );
  1009. }
  1010. set( value ) {
  1011. if ( value && value.isColor ) {
  1012. this.copy( value );
  1013. } else if ( typeof value === 'number' ) {
  1014. this.setHex( value );
  1015. } else if ( typeof value === 'string' ) {
  1016. this.setStyle( value );
  1017. }
  1018. return this;
  1019. }
  1020. setScalar( scalar ) {
  1021. this.r = scalar;
  1022. this.g = scalar;
  1023. this.b = scalar;
  1024. return this;
  1025. }
  1026. setHex( hex, colorSpace = SRGBColorSpace ) {
  1027. hex = Math.floor( hex );
  1028. this.r = ( hex >> 16 & 255 ) / 255;
  1029. this.g = ( hex >> 8 & 255 ) / 255;
  1030. this.b = ( hex & 255 ) / 255;
  1031. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1032. return this;
  1033. }
  1034. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  1035. this.r = r;
  1036. this.g = g;
  1037. this.b = b;
  1038. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1039. return this;
  1040. }
  1041. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  1042. // h,s,l ranges are in 0.0 - 1.0
  1043. h = euclideanModulo( h, 1 );
  1044. s = clamp( s, 0, 1 );
  1045. l = clamp( l, 0, 1 );
  1046. if ( s === 0 ) {
  1047. this.r = this.g = this.b = l;
  1048. } else {
  1049. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1050. const q = ( 2 * l ) - p;
  1051. this.r = hue2rgb( q, p, h + 1 / 3 );
  1052. this.g = hue2rgb( q, p, h );
  1053. this.b = hue2rgb( q, p, h - 1 / 3 );
  1054. }
  1055. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1056. return this;
  1057. }
  1058. setStyle( style, colorSpace = SRGBColorSpace ) {
  1059. function handleAlpha( string ) {
  1060. if ( string === undefined ) return;
  1061. if ( parseFloat( string ) < 1 ) {
  1062. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1063. }
  1064. }
  1065. let m;
  1066. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1067. // rgb / hsl
  1068. let color;
  1069. const name = m[ 1 ];
  1070. const components = m[ 2 ];
  1071. switch ( name ) {
  1072. case 'rgb':
  1073. case 'rgba':
  1074. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1075. // rgb(255,0,0) rgba(255,0,0,0.5)
  1076. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1077. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1078. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1079. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1080. handleAlpha( color[ 4 ] );
  1081. return this;
  1082. }
  1083. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1084. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1085. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1086. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1087. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1088. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1089. handleAlpha( color[ 4 ] );
  1090. return this;
  1091. }
  1092. break;
  1093. case 'hsl':
  1094. case 'hsla':
  1095. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1096. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1097. const h = parseFloat( color[ 1 ] ) / 360;
  1098. const s = parseFloat( color[ 2 ] ) / 100;
  1099. const l = parseFloat( color[ 3 ] ) / 100;
  1100. handleAlpha( color[ 4 ] );
  1101. return this.setHSL( h, s, l, colorSpace );
  1102. }
  1103. break;
  1104. }
  1105. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1106. // hex color
  1107. const hex = m[ 1 ];
  1108. const size = hex.length;
  1109. if ( size === 3 ) {
  1110. // #ff0
  1111. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1112. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1113. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1114. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1115. return this;
  1116. } else if ( size === 6 ) {
  1117. // #ff0000
  1118. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1119. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1120. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1121. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1122. return this;
  1123. }
  1124. }
  1125. if ( style && style.length > 0 ) {
  1126. return this.setColorName( style, colorSpace );
  1127. }
  1128. return this;
  1129. }
  1130. setColorName( style, colorSpace = SRGBColorSpace ) {
  1131. // color keywords
  1132. const hex = _colorKeywords[ style.toLowerCase() ];
  1133. if ( hex !== undefined ) {
  1134. // red
  1135. this.setHex( hex, colorSpace );
  1136. } else {
  1137. // unknown color
  1138. console.warn( 'THREE.Color: Unknown color ' + style );
  1139. }
  1140. return this;
  1141. }
  1142. clone() {
  1143. return new this.constructor( this.r, this.g, this.b );
  1144. }
  1145. copy( color ) {
  1146. this.r = color.r;
  1147. this.g = color.g;
  1148. this.b = color.b;
  1149. return this;
  1150. }
  1151. copySRGBToLinear( color ) {
  1152. this.r = SRGBToLinear( color.r );
  1153. this.g = SRGBToLinear( color.g );
  1154. this.b = SRGBToLinear( color.b );
  1155. return this;
  1156. }
  1157. copyLinearToSRGB( color ) {
  1158. this.r = LinearToSRGB( color.r );
  1159. this.g = LinearToSRGB( color.g );
  1160. this.b = LinearToSRGB( color.b );
  1161. return this;
  1162. }
  1163. convertSRGBToLinear() {
  1164. this.copySRGBToLinear( this );
  1165. return this;
  1166. }
  1167. convertLinearToSRGB() {
  1168. this.copyLinearToSRGB( this );
  1169. return this;
  1170. }
  1171. getHex( colorSpace = SRGBColorSpace ) {
  1172. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1173. return clamp( _rgb$1.r * 255, 0, 255 ) << 16 ^ clamp( _rgb$1.g * 255, 0, 255 ) << 8 ^ clamp( _rgb$1.b * 255, 0, 255 ) << 0;
  1174. }
  1175. getHexString( colorSpace = SRGBColorSpace ) {
  1176. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1177. }
  1178. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  1179. // h,s,l ranges are in 0.0 - 1.0
  1180. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1181. const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b;
  1182. const max = Math.max( r, g, b );
  1183. const min = Math.min( r, g, b );
  1184. let hue, saturation;
  1185. const lightness = ( min + max ) / 2.0;
  1186. if ( min === max ) {
  1187. hue = 0;
  1188. saturation = 0;
  1189. } else {
  1190. const delta = max - min;
  1191. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1192. switch ( max ) {
  1193. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1194. case g: hue = ( b - r ) / delta + 2; break;
  1195. case b: hue = ( r - g ) / delta + 4; break;
  1196. }
  1197. hue /= 6;
  1198. }
  1199. target.h = hue;
  1200. target.s = saturation;
  1201. target.l = lightness;
  1202. return target;
  1203. }
  1204. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  1205. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1206. target.r = _rgb$1.r;
  1207. target.g = _rgb$1.g;
  1208. target.b = _rgb$1.b;
  1209. return target;
  1210. }
  1211. getStyle( colorSpace = SRGBColorSpace ) {
  1212. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1213. if ( colorSpace !== SRGBColorSpace ) {
  1214. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1215. return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`;
  1216. }
  1217. return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`;
  1218. }
  1219. offsetHSL( h, s, l ) {
  1220. this.getHSL( _hslA );
  1221. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1222. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1223. return this;
  1224. }
  1225. add( color ) {
  1226. this.r += color.r;
  1227. this.g += color.g;
  1228. this.b += color.b;
  1229. return this;
  1230. }
  1231. addColors( color1, color2 ) {
  1232. this.r = color1.r + color2.r;
  1233. this.g = color1.g + color2.g;
  1234. this.b = color1.b + color2.b;
  1235. return this;
  1236. }
  1237. addScalar( s ) {
  1238. this.r += s;
  1239. this.g += s;
  1240. this.b += s;
  1241. return this;
  1242. }
  1243. sub( color ) {
  1244. this.r = Math.max( 0, this.r - color.r );
  1245. this.g = Math.max( 0, this.g - color.g );
  1246. this.b = Math.max( 0, this.b - color.b );
  1247. return this;
  1248. }
  1249. multiply( color ) {
  1250. this.r *= color.r;
  1251. this.g *= color.g;
  1252. this.b *= color.b;
  1253. return this;
  1254. }
  1255. multiplyScalar( s ) {
  1256. this.r *= s;
  1257. this.g *= s;
  1258. this.b *= s;
  1259. return this;
  1260. }
  1261. lerp( color, alpha ) {
  1262. this.r += ( color.r - this.r ) * alpha;
  1263. this.g += ( color.g - this.g ) * alpha;
  1264. this.b += ( color.b - this.b ) * alpha;
  1265. return this;
  1266. }
  1267. lerpColors( color1, color2, alpha ) {
  1268. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1269. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1270. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1271. return this;
  1272. }
  1273. lerpHSL( color, alpha ) {
  1274. this.getHSL( _hslA );
  1275. color.getHSL( _hslB );
  1276. const h = lerp( _hslA.h, _hslB.h, alpha );
  1277. const s = lerp( _hslA.s, _hslB.s, alpha );
  1278. const l = lerp( _hslA.l, _hslB.l, alpha );
  1279. this.setHSL( h, s, l );
  1280. return this;
  1281. }
  1282. equals( c ) {
  1283. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1284. }
  1285. fromArray( array, offset = 0 ) {
  1286. this.r = array[ offset ];
  1287. this.g = array[ offset + 1 ];
  1288. this.b = array[ offset + 2 ];
  1289. return this;
  1290. }
  1291. toArray( array = [], offset = 0 ) {
  1292. array[ offset ] = this.r;
  1293. array[ offset + 1 ] = this.g;
  1294. array[ offset + 2 ] = this.b;
  1295. return array;
  1296. }
  1297. fromBufferAttribute( attribute, index ) {
  1298. this.r = attribute.getX( index );
  1299. this.g = attribute.getY( index );
  1300. this.b = attribute.getZ( index );
  1301. return this;
  1302. }
  1303. toJSON() {
  1304. return this.getHex();
  1305. }
  1306. *[ Symbol.iterator ]() {
  1307. yield this.r;
  1308. yield this.g;
  1309. yield this.b;
  1310. }
  1311. }
  1312. Color.NAMES = _colorKeywords;
  1313. let _canvas;
  1314. class ImageUtils {
  1315. static getDataURL( image ) {
  1316. if ( /^data:/i.test( image.src ) ) {
  1317. return image.src;
  1318. }
  1319. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1320. return image.src;
  1321. }
  1322. let canvas;
  1323. if ( image instanceof HTMLCanvasElement ) {
  1324. canvas = image;
  1325. } else {
  1326. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1327. _canvas.width = image.width;
  1328. _canvas.height = image.height;
  1329. const context = _canvas.getContext( '2d' );
  1330. if ( image instanceof ImageData ) {
  1331. context.putImageData( image, 0, 0 );
  1332. } else {
  1333. context.drawImage( image, 0, 0, image.width, image.height );
  1334. }
  1335. canvas = _canvas;
  1336. }
  1337. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1338. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1339. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1340. } else {
  1341. return canvas.toDataURL( 'image/png' );
  1342. }
  1343. }
  1344. static sRGBToLinear( image ) {
  1345. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1346. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1347. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1348. const canvas = createElementNS( 'canvas' );
  1349. canvas.width = image.width;
  1350. canvas.height = image.height;
  1351. const context = canvas.getContext( '2d' );
  1352. context.drawImage( image, 0, 0, image.width, image.height );
  1353. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1354. const data = imageData.data;
  1355. for ( let i = 0; i < data.length; i ++ ) {
  1356. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1357. }
  1358. context.putImageData( imageData, 0, 0 );
  1359. return canvas;
  1360. } else if ( image.data ) {
  1361. const data = image.data.slice( 0 );
  1362. for ( let i = 0; i < data.length; i ++ ) {
  1363. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1364. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1365. } else {
  1366. // assuming float
  1367. data[ i ] = SRGBToLinear( data[ i ] );
  1368. }
  1369. }
  1370. return {
  1371. data: data,
  1372. width: image.width,
  1373. height: image.height
  1374. };
  1375. } else {
  1376. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1377. return image;
  1378. }
  1379. }
  1380. }
  1381. class Source {
  1382. constructor( data = null ) {
  1383. this.isSource = true;
  1384. this.uuid = generateUUID();
  1385. this.data = data;
  1386. this.version = 0;
  1387. }
  1388. set needsUpdate( value ) {
  1389. if ( value === true ) this.version ++;
  1390. }
  1391. toJSON( meta ) {
  1392. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1393. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1394. return meta.images[ this.uuid ];
  1395. }
  1396. const output = {
  1397. uuid: this.uuid,
  1398. url: ''
  1399. };
  1400. const data = this.data;
  1401. if ( data !== null ) {
  1402. let url;
  1403. if ( Array.isArray( data ) ) {
  1404. // cube texture
  1405. url = [];
  1406. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1407. if ( data[ i ].isDataTexture ) {
  1408. url.push( serializeImage( data[ i ].image ) );
  1409. } else {
  1410. url.push( serializeImage( data[ i ] ) );
  1411. }
  1412. }
  1413. } else {
  1414. // texture
  1415. url = serializeImage( data );
  1416. }
  1417. output.url = url;
  1418. }
  1419. if ( ! isRootObject ) {
  1420. meta.images[ this.uuid ] = output;
  1421. }
  1422. return output;
  1423. }
  1424. }
  1425. function serializeImage( image ) {
  1426. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1427. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1428. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1429. // default images
  1430. return ImageUtils.getDataURL( image );
  1431. } else {
  1432. if ( image.data ) {
  1433. // images of DataTexture
  1434. return {
  1435. data: Array.from( image.data ),
  1436. width: image.width,
  1437. height: image.height,
  1438. type: image.data.constructor.name
  1439. };
  1440. } else {
  1441. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1442. return {};
  1443. }
  1444. }
  1445. }
  1446. let textureId = 0;
  1447. class Texture extends EventDispatcher {
  1448. 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, encoding = LinearEncoding ) {
  1449. super();
  1450. this.isTexture = true;
  1451. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1452. this.uuid = generateUUID();
  1453. this.name = '';
  1454. this.source = new Source( image );
  1455. this.mipmaps = [];
  1456. this.mapping = mapping;
  1457. this.wrapS = wrapS;
  1458. this.wrapT = wrapT;
  1459. this.magFilter = magFilter;
  1460. this.minFilter = minFilter;
  1461. this.anisotropy = anisotropy;
  1462. this.format = format;
  1463. this.internalFormat = null;
  1464. this.type = type;
  1465. this.offset = new Vector2( 0, 0 );
  1466. this.repeat = new Vector2( 1, 1 );
  1467. this.center = new Vector2( 0, 0 );
  1468. this.rotation = 0;
  1469. this.matrixAutoUpdate = true;
  1470. this.matrix = new Matrix3();
  1471. this.generateMipmaps = true;
  1472. this.premultiplyAlpha = false;
  1473. this.flipY = true;
  1474. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1475. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1476. //
  1477. // Also changing the encoding after already used by a Material will not automatically make the Material
  1478. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1479. this.encoding = encoding;
  1480. this.userData = {};
  1481. this.version = 0;
  1482. this.onUpdate = null;
  1483. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1484. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1485. }
  1486. get image() {
  1487. return this.source.data;
  1488. }
  1489. set image( value ) {
  1490. this.source.data = value;
  1491. }
  1492. updateMatrix() {
  1493. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1494. }
  1495. clone() {
  1496. return new this.constructor().copy( this );
  1497. }
  1498. copy( source ) {
  1499. this.name = source.name;
  1500. this.source = source.source;
  1501. this.mipmaps = source.mipmaps.slice( 0 );
  1502. this.mapping = source.mapping;
  1503. this.wrapS = source.wrapS;
  1504. this.wrapT = source.wrapT;
  1505. this.magFilter = source.magFilter;
  1506. this.minFilter = source.minFilter;
  1507. this.anisotropy = source.anisotropy;
  1508. this.format = source.format;
  1509. this.internalFormat = source.internalFormat;
  1510. this.type = source.type;
  1511. this.offset.copy( source.offset );
  1512. this.repeat.copy( source.repeat );
  1513. this.center.copy( source.center );
  1514. this.rotation = source.rotation;
  1515. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1516. this.matrix.copy( source.matrix );
  1517. this.generateMipmaps = source.generateMipmaps;
  1518. this.premultiplyAlpha = source.premultiplyAlpha;
  1519. this.flipY = source.flipY;
  1520. this.unpackAlignment = source.unpackAlignment;
  1521. this.encoding = source.encoding;
  1522. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1523. this.needsUpdate = true;
  1524. return this;
  1525. }
  1526. toJSON( meta ) {
  1527. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1528. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1529. return meta.textures[ this.uuid ];
  1530. }
  1531. const output = {
  1532. metadata: {
  1533. version: 4.5,
  1534. type: 'Texture',
  1535. generator: 'Texture.toJSON'
  1536. },
  1537. uuid: this.uuid,
  1538. name: this.name,
  1539. image: this.source.toJSON( meta ).uuid,
  1540. mapping: this.mapping,
  1541. repeat: [ this.repeat.x, this.repeat.y ],
  1542. offset: [ this.offset.x, this.offset.y ],
  1543. center: [ this.center.x, this.center.y ],
  1544. rotation: this.rotation,
  1545. wrap: [ this.wrapS, this.wrapT ],
  1546. format: this.format,
  1547. type: this.type,
  1548. encoding: this.encoding,
  1549. minFilter: this.minFilter,
  1550. magFilter: this.magFilter,
  1551. anisotropy: this.anisotropy,
  1552. flipY: this.flipY,
  1553. generateMipmaps: this.generateMipmaps,
  1554. premultiplyAlpha: this.premultiplyAlpha,
  1555. unpackAlignment: this.unpackAlignment
  1556. };
  1557. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1558. if ( ! isRootObject ) {
  1559. meta.textures[ this.uuid ] = output;
  1560. }
  1561. return output;
  1562. }
  1563. dispose() {
  1564. this.dispatchEvent( { type: 'dispose' } );
  1565. }
  1566. transformUv( uv ) {
  1567. if ( this.mapping !== UVMapping ) return uv;
  1568. uv.applyMatrix3( this.matrix );
  1569. if ( uv.x < 0 || uv.x > 1 ) {
  1570. switch ( this.wrapS ) {
  1571. case RepeatWrapping:
  1572. uv.x = uv.x - Math.floor( uv.x );
  1573. break;
  1574. case ClampToEdgeWrapping:
  1575. uv.x = uv.x < 0 ? 0 : 1;
  1576. break;
  1577. case MirroredRepeatWrapping:
  1578. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1579. uv.x = Math.ceil( uv.x ) - uv.x;
  1580. } else {
  1581. uv.x = uv.x - Math.floor( uv.x );
  1582. }
  1583. break;
  1584. }
  1585. }
  1586. if ( uv.y < 0 || uv.y > 1 ) {
  1587. switch ( this.wrapT ) {
  1588. case RepeatWrapping:
  1589. uv.y = uv.y - Math.floor( uv.y );
  1590. break;
  1591. case ClampToEdgeWrapping:
  1592. uv.y = uv.y < 0 ? 0 : 1;
  1593. break;
  1594. case MirroredRepeatWrapping:
  1595. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1596. uv.y = Math.ceil( uv.y ) - uv.y;
  1597. } else {
  1598. uv.y = uv.y - Math.floor( uv.y );
  1599. }
  1600. break;
  1601. }
  1602. }
  1603. if ( this.flipY ) {
  1604. uv.y = 1 - uv.y;
  1605. }
  1606. return uv;
  1607. }
  1608. set needsUpdate( value ) {
  1609. if ( value === true ) {
  1610. this.version ++;
  1611. this.source.needsUpdate = true;
  1612. }
  1613. }
  1614. }
  1615. Texture.DEFAULT_IMAGE = null;
  1616. Texture.DEFAULT_MAPPING = UVMapping;
  1617. Texture.DEFAULT_ANISOTROPY = 1;
  1618. class Vector4 {
  1619. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1620. Vector4.prototype.isVector4 = true;
  1621. this.x = x;
  1622. this.y = y;
  1623. this.z = z;
  1624. this.w = w;
  1625. }
  1626. get width() {
  1627. return this.z;
  1628. }
  1629. set width( value ) {
  1630. this.z = value;
  1631. }
  1632. get height() {
  1633. return this.w;
  1634. }
  1635. set height( value ) {
  1636. this.w = value;
  1637. }
  1638. set( x, y, z, w ) {
  1639. this.x = x;
  1640. this.y = y;
  1641. this.z = z;
  1642. this.w = w;
  1643. return this;
  1644. }
  1645. setScalar( scalar ) {
  1646. this.x = scalar;
  1647. this.y = scalar;
  1648. this.z = scalar;
  1649. this.w = scalar;
  1650. return this;
  1651. }
  1652. setX( x ) {
  1653. this.x = x;
  1654. return this;
  1655. }
  1656. setY( y ) {
  1657. this.y = y;
  1658. return this;
  1659. }
  1660. setZ( z ) {
  1661. this.z = z;
  1662. return this;
  1663. }
  1664. setW( w ) {
  1665. this.w = w;
  1666. return this;
  1667. }
  1668. setComponent( index, value ) {
  1669. switch ( index ) {
  1670. case 0: this.x = value; break;
  1671. case 1: this.y = value; break;
  1672. case 2: this.z = value; break;
  1673. case 3: this.w = value; break;
  1674. default: throw new Error( 'index is out of range: ' + index );
  1675. }
  1676. return this;
  1677. }
  1678. getComponent( index ) {
  1679. switch ( index ) {
  1680. case 0: return this.x;
  1681. case 1: return this.y;
  1682. case 2: return this.z;
  1683. case 3: return this.w;
  1684. default: throw new Error( 'index is out of range: ' + index );
  1685. }
  1686. }
  1687. clone() {
  1688. return new this.constructor( this.x, this.y, this.z, this.w );
  1689. }
  1690. copy( v ) {
  1691. this.x = v.x;
  1692. this.y = v.y;
  1693. this.z = v.z;
  1694. this.w = ( v.w !== undefined ) ? v.w : 1;
  1695. return this;
  1696. }
  1697. add( v ) {
  1698. this.x += v.x;
  1699. this.y += v.y;
  1700. this.z += v.z;
  1701. this.w += v.w;
  1702. return this;
  1703. }
  1704. addScalar( s ) {
  1705. this.x += s;
  1706. this.y += s;
  1707. this.z += s;
  1708. this.w += s;
  1709. return this;
  1710. }
  1711. addVectors( a, b ) {
  1712. this.x = a.x + b.x;
  1713. this.y = a.y + b.y;
  1714. this.z = a.z + b.z;
  1715. this.w = a.w + b.w;
  1716. return this;
  1717. }
  1718. addScaledVector( v, s ) {
  1719. this.x += v.x * s;
  1720. this.y += v.y * s;
  1721. this.z += v.z * s;
  1722. this.w += v.w * s;
  1723. return this;
  1724. }
  1725. sub( v ) {
  1726. this.x -= v.x;
  1727. this.y -= v.y;
  1728. this.z -= v.z;
  1729. this.w -= v.w;
  1730. return this;
  1731. }
  1732. subScalar( s ) {
  1733. this.x -= s;
  1734. this.y -= s;
  1735. this.z -= s;
  1736. this.w -= s;
  1737. return this;
  1738. }
  1739. subVectors( a, b ) {
  1740. this.x = a.x - b.x;
  1741. this.y = a.y - b.y;
  1742. this.z = a.z - b.z;
  1743. this.w = a.w - b.w;
  1744. return this;
  1745. }
  1746. multiply( v ) {
  1747. this.x *= v.x;
  1748. this.y *= v.y;
  1749. this.z *= v.z;
  1750. this.w *= v.w;
  1751. return this;
  1752. }
  1753. multiplyScalar( scalar ) {
  1754. this.x *= scalar;
  1755. this.y *= scalar;
  1756. this.z *= scalar;
  1757. this.w *= scalar;
  1758. return this;
  1759. }
  1760. applyMatrix4( m ) {
  1761. const x = this.x, y = this.y, z = this.z, w = this.w;
  1762. const e = m.elements;
  1763. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1764. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1765. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1766. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1767. return this;
  1768. }
  1769. divideScalar( scalar ) {
  1770. return this.multiplyScalar( 1 / scalar );
  1771. }
  1772. setAxisAngleFromQuaternion( q ) {
  1773. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1774. // q is assumed to be normalized
  1775. this.w = 2 * Math.acos( q.w );
  1776. const s = Math.sqrt( 1 - q.w * q.w );
  1777. if ( s < 0.0001 ) {
  1778. this.x = 1;
  1779. this.y = 0;
  1780. this.z = 0;
  1781. } else {
  1782. this.x = q.x / s;
  1783. this.y = q.y / s;
  1784. this.z = q.z / s;
  1785. }
  1786. return this;
  1787. }
  1788. setAxisAngleFromRotationMatrix( m ) {
  1789. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1790. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1791. let angle, x, y, z; // variables for result
  1792. const epsilon = 0.01, // margin to allow for rounding errors
  1793. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1794. te = m.elements,
  1795. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1796. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1797. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1798. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1799. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1800. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1801. // singularity found
  1802. // first check for identity matrix which must have +1 for all terms
  1803. // in leading diagonal and zero in other terms
  1804. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1805. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1806. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1807. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1808. // this singularity is identity matrix so angle = 0
  1809. this.set( 1, 0, 0, 0 );
  1810. return this; // zero angle, arbitrary axis
  1811. }
  1812. // otherwise this singularity is angle = 180
  1813. angle = Math.PI;
  1814. const xx = ( m11 + 1 ) / 2;
  1815. const yy = ( m22 + 1 ) / 2;
  1816. const zz = ( m33 + 1 ) / 2;
  1817. const xy = ( m12 + m21 ) / 4;
  1818. const xz = ( m13 + m31 ) / 4;
  1819. const yz = ( m23 + m32 ) / 4;
  1820. if ( ( xx > yy ) && ( xx > zz ) ) {
  1821. // m11 is the largest diagonal term
  1822. if ( xx < epsilon ) {
  1823. x = 0;
  1824. y = 0.707106781;
  1825. z = 0.707106781;
  1826. } else {
  1827. x = Math.sqrt( xx );
  1828. y = xy / x;
  1829. z = xz / x;
  1830. }
  1831. } else if ( yy > zz ) {
  1832. // m22 is the largest diagonal term
  1833. if ( yy < epsilon ) {
  1834. x = 0.707106781;
  1835. y = 0;
  1836. z = 0.707106781;
  1837. } else {
  1838. y = Math.sqrt( yy );
  1839. x = xy / y;
  1840. z = yz / y;
  1841. }
  1842. } else {
  1843. // m33 is the largest diagonal term so base result on this
  1844. if ( zz < epsilon ) {
  1845. x = 0.707106781;
  1846. y = 0.707106781;
  1847. z = 0;
  1848. } else {
  1849. z = Math.sqrt( zz );
  1850. x = xz / z;
  1851. y = yz / z;
  1852. }
  1853. }
  1854. this.set( x, y, z, angle );
  1855. return this; // return 180 deg rotation
  1856. }
  1857. // as we have reached here there are no singularities so we can handle normally
  1858. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1859. ( m13 - m31 ) * ( m13 - m31 ) +
  1860. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1861. if ( Math.abs( s ) < 0.001 ) s = 1;
  1862. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1863. // caught by singularity test above, but I've left it in just in case
  1864. this.x = ( m32 - m23 ) / s;
  1865. this.y = ( m13 - m31 ) / s;
  1866. this.z = ( m21 - m12 ) / s;
  1867. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1868. return this;
  1869. }
  1870. min( v ) {
  1871. this.x = Math.min( this.x, v.x );
  1872. this.y = Math.min( this.y, v.y );
  1873. this.z = Math.min( this.z, v.z );
  1874. this.w = Math.min( this.w, v.w );
  1875. return this;
  1876. }
  1877. max( v ) {
  1878. this.x = Math.max( this.x, v.x );
  1879. this.y = Math.max( this.y, v.y );
  1880. this.z = Math.max( this.z, v.z );
  1881. this.w = Math.max( this.w, v.w );
  1882. return this;
  1883. }
  1884. clamp( min, max ) {
  1885. // assumes min < max, componentwise
  1886. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1887. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1888. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1889. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1890. return this;
  1891. }
  1892. clampScalar( minVal, maxVal ) {
  1893. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1894. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1895. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1896. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1897. return this;
  1898. }
  1899. clampLength( min, max ) {
  1900. const length = this.length();
  1901. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1902. }
  1903. floor() {
  1904. this.x = Math.floor( this.x );
  1905. this.y = Math.floor( this.y );
  1906. this.z = Math.floor( this.z );
  1907. this.w = Math.floor( this.w );
  1908. return this;
  1909. }
  1910. ceil() {
  1911. this.x = Math.ceil( this.x );
  1912. this.y = Math.ceil( this.y );
  1913. this.z = Math.ceil( this.z );
  1914. this.w = Math.ceil( this.w );
  1915. return this;
  1916. }
  1917. round() {
  1918. this.x = Math.round( this.x );
  1919. this.y = Math.round( this.y );
  1920. this.z = Math.round( this.z );
  1921. this.w = Math.round( this.w );
  1922. return this;
  1923. }
  1924. roundToZero() {
  1925. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1926. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1927. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1928. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1929. return this;
  1930. }
  1931. negate() {
  1932. this.x = - this.x;
  1933. this.y = - this.y;
  1934. this.z = - this.z;
  1935. this.w = - this.w;
  1936. return this;
  1937. }
  1938. dot( v ) {
  1939. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1940. }
  1941. lengthSq() {
  1942. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1943. }
  1944. length() {
  1945. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1946. }
  1947. manhattanLength() {
  1948. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1949. }
  1950. normalize() {
  1951. return this.divideScalar( this.length() || 1 );
  1952. }
  1953. setLength( length ) {
  1954. return this.normalize().multiplyScalar( length );
  1955. }
  1956. lerp( v, alpha ) {
  1957. this.x += ( v.x - this.x ) * alpha;
  1958. this.y += ( v.y - this.y ) * alpha;
  1959. this.z += ( v.z - this.z ) * alpha;
  1960. this.w += ( v.w - this.w ) * alpha;
  1961. return this;
  1962. }
  1963. lerpVectors( v1, v2, alpha ) {
  1964. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1965. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1966. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1967. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1968. return this;
  1969. }
  1970. equals( v ) {
  1971. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1972. }
  1973. fromArray( array, offset = 0 ) {
  1974. this.x = array[ offset ];
  1975. this.y = array[ offset + 1 ];
  1976. this.z = array[ offset + 2 ];
  1977. this.w = array[ offset + 3 ];
  1978. return this;
  1979. }
  1980. toArray( array = [], offset = 0 ) {
  1981. array[ offset ] = this.x;
  1982. array[ offset + 1 ] = this.y;
  1983. array[ offset + 2 ] = this.z;
  1984. array[ offset + 3 ] = this.w;
  1985. return array;
  1986. }
  1987. fromBufferAttribute( attribute, index ) {
  1988. this.x = attribute.getX( index );
  1989. this.y = attribute.getY( index );
  1990. this.z = attribute.getZ( index );
  1991. this.w = attribute.getW( index );
  1992. return this;
  1993. }
  1994. random() {
  1995. this.x = Math.random();
  1996. this.y = Math.random();
  1997. this.z = Math.random();
  1998. this.w = Math.random();
  1999. return this;
  2000. }
  2001. *[ Symbol.iterator ]() {
  2002. yield this.x;
  2003. yield this.y;
  2004. yield this.z;
  2005. yield this.w;
  2006. }
  2007. }
  2008. /*
  2009. In options, we can specify:
  2010. * Texture parameters for an auto-generated target texture
  2011. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2012. */
  2013. class WebGLRenderTarget extends EventDispatcher {
  2014. constructor( width = 1, height = 1, options = {} ) {
  2015. super();
  2016. this.isWebGLRenderTarget = true;
  2017. this.width = width;
  2018. this.height = height;
  2019. this.depth = 1;
  2020. this.scissor = new Vector4( 0, 0, width, height );
  2021. this.scissorTest = false;
  2022. this.viewport = new Vector4( 0, 0, width, height );
  2023. const image = { width: width, height: height, depth: 1 };
  2024. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2025. this.texture.isRenderTargetTexture = true;
  2026. this.texture.flipY = false;
  2027. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2028. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2029. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2030. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2031. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2032. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2033. this.samples = options.samples !== undefined ? options.samples : 0;
  2034. }
  2035. setSize( width, height, depth = 1 ) {
  2036. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2037. this.width = width;
  2038. this.height = height;
  2039. this.depth = depth;
  2040. this.texture.image.width = width;
  2041. this.texture.image.height = height;
  2042. this.texture.image.depth = depth;
  2043. this.dispose();
  2044. }
  2045. this.viewport.set( 0, 0, width, height );
  2046. this.scissor.set( 0, 0, width, height );
  2047. }
  2048. clone() {
  2049. return new this.constructor().copy( this );
  2050. }
  2051. copy( source ) {
  2052. this.width = source.width;
  2053. this.height = source.height;
  2054. this.depth = source.depth;
  2055. this.viewport.copy( source.viewport );
  2056. this.texture = source.texture.clone();
  2057. this.texture.isRenderTargetTexture = true;
  2058. // ensure image object is not shared, see #20328
  2059. const image = Object.assign( {}, source.texture.image );
  2060. this.texture.source = new Source( image );
  2061. this.depthBuffer = source.depthBuffer;
  2062. this.stencilBuffer = source.stencilBuffer;
  2063. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2064. this.samples = source.samples;
  2065. return this;
  2066. }
  2067. dispose() {
  2068. this.dispatchEvent( { type: 'dispose' } );
  2069. }
  2070. }
  2071. class DataArrayTexture extends Texture {
  2072. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2073. super( null );
  2074. this.isDataArrayTexture = true;
  2075. this.image = { data, width, height, depth };
  2076. this.magFilter = NearestFilter;
  2077. this.minFilter = NearestFilter;
  2078. this.wrapR = ClampToEdgeWrapping;
  2079. this.generateMipmaps = false;
  2080. this.flipY = false;
  2081. this.unpackAlignment = 1;
  2082. }
  2083. }
  2084. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2085. constructor( width = 1, height = 1, depth = 1 ) {
  2086. super( width, height );
  2087. this.isWebGLArrayRenderTarget = true;
  2088. this.depth = depth;
  2089. this.texture = new DataArrayTexture( null, width, height, depth );
  2090. this.texture.isRenderTargetTexture = true;
  2091. }
  2092. }
  2093. class Data3DTexture extends Texture {
  2094. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2095. // We're going to add .setXXX() methods for setting properties later.
  2096. // Users can still set in DataTexture3D directly.
  2097. //
  2098. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2099. // texture.anisotropy = 16;
  2100. //
  2101. // See #14839
  2102. super( null );
  2103. this.isData3DTexture = true;
  2104. this.image = { data, width, height, depth };
  2105. this.magFilter = NearestFilter;
  2106. this.minFilter = NearestFilter;
  2107. this.wrapR = ClampToEdgeWrapping;
  2108. this.generateMipmaps = false;
  2109. this.flipY = false;
  2110. this.unpackAlignment = 1;
  2111. }
  2112. }
  2113. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2114. constructor( width = 1, height = 1, depth = 1 ) {
  2115. super( width, height );
  2116. this.isWebGL3DRenderTarget = true;
  2117. this.depth = depth;
  2118. this.texture = new Data3DTexture( null, width, height, depth );
  2119. this.texture.isRenderTargetTexture = true;
  2120. }
  2121. }
  2122. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2123. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2124. super( width, height, options );
  2125. this.isWebGLMultipleRenderTargets = true;
  2126. const texture = this.texture;
  2127. this.texture = [];
  2128. for ( let i = 0; i < count; i ++ ) {
  2129. this.texture[ i ] = texture.clone();
  2130. this.texture[ i ].isRenderTargetTexture = true;
  2131. }
  2132. }
  2133. setSize( width, height, depth = 1 ) {
  2134. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2135. this.width = width;
  2136. this.height = height;
  2137. this.depth = depth;
  2138. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2139. this.texture[ i ].image.width = width;
  2140. this.texture[ i ].image.height = height;
  2141. this.texture[ i ].image.depth = depth;
  2142. }
  2143. this.dispose();
  2144. }
  2145. this.viewport.set( 0, 0, width, height );
  2146. this.scissor.set( 0, 0, width, height );
  2147. return this;
  2148. }
  2149. copy( source ) {
  2150. this.dispose();
  2151. this.width = source.width;
  2152. this.height = source.height;
  2153. this.depth = source.depth;
  2154. this.viewport.set( 0, 0, this.width, this.height );
  2155. this.scissor.set( 0, 0, this.width, this.height );
  2156. this.depthBuffer = source.depthBuffer;
  2157. this.stencilBuffer = source.stencilBuffer;
  2158. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2159. this.texture.length = 0;
  2160. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2161. this.texture[ i ] = source.texture[ i ].clone();
  2162. this.texture[ i ].isRenderTargetTexture = true;
  2163. }
  2164. return this;
  2165. }
  2166. }
  2167. class Quaternion {
  2168. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2169. this.isQuaternion = true;
  2170. this._x = x;
  2171. this._y = y;
  2172. this._z = z;
  2173. this._w = w;
  2174. }
  2175. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2176. // fuzz-free, array-based Quaternion SLERP operation
  2177. let x0 = src0[ srcOffset0 + 0 ],
  2178. y0 = src0[ srcOffset0 + 1 ],
  2179. z0 = src0[ srcOffset0 + 2 ],
  2180. w0 = src0[ srcOffset0 + 3 ];
  2181. const x1 = src1[ srcOffset1 + 0 ],
  2182. y1 = src1[ srcOffset1 + 1 ],
  2183. z1 = src1[ srcOffset1 + 2 ],
  2184. w1 = src1[ srcOffset1 + 3 ];
  2185. if ( t === 0 ) {
  2186. dst[ dstOffset + 0 ] = x0;
  2187. dst[ dstOffset + 1 ] = y0;
  2188. dst[ dstOffset + 2 ] = z0;
  2189. dst[ dstOffset + 3 ] = w0;
  2190. return;
  2191. }
  2192. if ( t === 1 ) {
  2193. dst[ dstOffset + 0 ] = x1;
  2194. dst[ dstOffset + 1 ] = y1;
  2195. dst[ dstOffset + 2 ] = z1;
  2196. dst[ dstOffset + 3 ] = w1;
  2197. return;
  2198. }
  2199. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2200. let s = 1 - t;
  2201. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2202. dir = ( cos >= 0 ? 1 : - 1 ),
  2203. sqrSin = 1 - cos * cos;
  2204. // Skip the Slerp for tiny steps to avoid numeric problems:
  2205. if ( sqrSin > Number.EPSILON ) {
  2206. const sin = Math.sqrt( sqrSin ),
  2207. len = Math.atan2( sin, cos * dir );
  2208. s = Math.sin( s * len ) / sin;
  2209. t = Math.sin( t * len ) / sin;
  2210. }
  2211. const tDir = t * dir;
  2212. x0 = x0 * s + x1 * tDir;
  2213. y0 = y0 * s + y1 * tDir;
  2214. z0 = z0 * s + z1 * tDir;
  2215. w0 = w0 * s + w1 * tDir;
  2216. // Normalize in case we just did a lerp:
  2217. if ( s === 1 - t ) {
  2218. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2219. x0 *= f;
  2220. y0 *= f;
  2221. z0 *= f;
  2222. w0 *= f;
  2223. }
  2224. }
  2225. dst[ dstOffset ] = x0;
  2226. dst[ dstOffset + 1 ] = y0;
  2227. dst[ dstOffset + 2 ] = z0;
  2228. dst[ dstOffset + 3 ] = w0;
  2229. }
  2230. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2231. const x0 = src0[ srcOffset0 ];
  2232. const y0 = src0[ srcOffset0 + 1 ];
  2233. const z0 = src0[ srcOffset0 + 2 ];
  2234. const w0 = src0[ srcOffset0 + 3 ];
  2235. const x1 = src1[ srcOffset1 ];
  2236. const y1 = src1[ srcOffset1 + 1 ];
  2237. const z1 = src1[ srcOffset1 + 2 ];
  2238. const w1 = src1[ srcOffset1 + 3 ];
  2239. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2240. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2241. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2242. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2243. return dst;
  2244. }
  2245. get x() {
  2246. return this._x;
  2247. }
  2248. set x( value ) {
  2249. this._x = value;
  2250. this._onChangeCallback();
  2251. }
  2252. get y() {
  2253. return this._y;
  2254. }
  2255. set y( value ) {
  2256. this._y = value;
  2257. this._onChangeCallback();
  2258. }
  2259. get z() {
  2260. return this._z;
  2261. }
  2262. set z( value ) {
  2263. this._z = value;
  2264. this._onChangeCallback();
  2265. }
  2266. get w() {
  2267. return this._w;
  2268. }
  2269. set w( value ) {
  2270. this._w = value;
  2271. this._onChangeCallback();
  2272. }
  2273. set( x, y, z, w ) {
  2274. this._x = x;
  2275. this._y = y;
  2276. this._z = z;
  2277. this._w = w;
  2278. this._onChangeCallback();
  2279. return this;
  2280. }
  2281. clone() {
  2282. return new this.constructor( this._x, this._y, this._z, this._w );
  2283. }
  2284. copy( quaternion ) {
  2285. this._x = quaternion.x;
  2286. this._y = quaternion.y;
  2287. this._z = quaternion.z;
  2288. this._w = quaternion.w;
  2289. this._onChangeCallback();
  2290. return this;
  2291. }
  2292. setFromEuler( euler, update ) {
  2293. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2294. // http://www.mathworks.com/matlabcentral/fileexchange/
  2295. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2296. // content/SpinCalc.m
  2297. const cos = Math.cos;
  2298. const sin = Math.sin;
  2299. const c1 = cos( x / 2 );
  2300. const c2 = cos( y / 2 );
  2301. const c3 = cos( z / 2 );
  2302. const s1 = sin( x / 2 );
  2303. const s2 = sin( y / 2 );
  2304. const s3 = sin( z / 2 );
  2305. switch ( order ) {
  2306. case 'XYZ':
  2307. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2308. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2309. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2310. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2311. break;
  2312. case 'YXZ':
  2313. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2314. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2315. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2316. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2317. break;
  2318. case 'ZXY':
  2319. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2320. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2321. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2322. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2323. break;
  2324. case 'ZYX':
  2325. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2326. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2327. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2328. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2329. break;
  2330. case 'YZX':
  2331. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2332. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2333. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2334. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2335. break;
  2336. case 'XZY':
  2337. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2338. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2339. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2340. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2341. break;
  2342. default:
  2343. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2344. }
  2345. if ( update !== false ) this._onChangeCallback();
  2346. return this;
  2347. }
  2348. setFromAxisAngle( axis, angle ) {
  2349. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2350. // assumes axis is normalized
  2351. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2352. this._x = axis.x * s;
  2353. this._y = axis.y * s;
  2354. this._z = axis.z * s;
  2355. this._w = Math.cos( halfAngle );
  2356. this._onChangeCallback();
  2357. return this;
  2358. }
  2359. setFromRotationMatrix( m ) {
  2360. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2361. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2362. const te = m.elements,
  2363. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2364. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2365. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2366. trace = m11 + m22 + m33;
  2367. if ( trace > 0 ) {
  2368. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2369. this._w = 0.25 / s;
  2370. this._x = ( m32 - m23 ) * s;
  2371. this._y = ( m13 - m31 ) * s;
  2372. this._z = ( m21 - m12 ) * s;
  2373. } else if ( m11 > m22 && m11 > m33 ) {
  2374. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2375. this._w = ( m32 - m23 ) / s;
  2376. this._x = 0.25 * s;
  2377. this._y = ( m12 + m21 ) / s;
  2378. this._z = ( m13 + m31 ) / s;
  2379. } else if ( m22 > m33 ) {
  2380. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2381. this._w = ( m13 - m31 ) / s;
  2382. this._x = ( m12 + m21 ) / s;
  2383. this._y = 0.25 * s;
  2384. this._z = ( m23 + m32 ) / s;
  2385. } else {
  2386. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2387. this._w = ( m21 - m12 ) / s;
  2388. this._x = ( m13 + m31 ) / s;
  2389. this._y = ( m23 + m32 ) / s;
  2390. this._z = 0.25 * s;
  2391. }
  2392. this._onChangeCallback();
  2393. return this;
  2394. }
  2395. setFromUnitVectors( vFrom, vTo ) {
  2396. // assumes direction vectors vFrom and vTo are normalized
  2397. let r = vFrom.dot( vTo ) + 1;
  2398. if ( r < Number.EPSILON ) {
  2399. // vFrom and vTo point in opposite directions
  2400. r = 0;
  2401. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2402. this._x = - vFrom.y;
  2403. this._y = vFrom.x;
  2404. this._z = 0;
  2405. this._w = r;
  2406. } else {
  2407. this._x = 0;
  2408. this._y = - vFrom.z;
  2409. this._z = vFrom.y;
  2410. this._w = r;
  2411. }
  2412. } else {
  2413. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2414. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2415. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2416. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2417. this._w = r;
  2418. }
  2419. return this.normalize();
  2420. }
  2421. angleTo( q ) {
  2422. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2423. }
  2424. rotateTowards( q, step ) {
  2425. const angle = this.angleTo( q );
  2426. if ( angle === 0 ) return this;
  2427. const t = Math.min( 1, step / angle );
  2428. this.slerp( q, t );
  2429. return this;
  2430. }
  2431. identity() {
  2432. return this.set( 0, 0, 0, 1 );
  2433. }
  2434. invert() {
  2435. // quaternion is assumed to have unit length
  2436. return this.conjugate();
  2437. }
  2438. conjugate() {
  2439. this._x *= - 1;
  2440. this._y *= - 1;
  2441. this._z *= - 1;
  2442. this._onChangeCallback();
  2443. return this;
  2444. }
  2445. dot( v ) {
  2446. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2447. }
  2448. lengthSq() {
  2449. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2450. }
  2451. length() {
  2452. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2453. }
  2454. normalize() {
  2455. let l = this.length();
  2456. if ( l === 0 ) {
  2457. this._x = 0;
  2458. this._y = 0;
  2459. this._z = 0;
  2460. this._w = 1;
  2461. } else {
  2462. l = 1 / l;
  2463. this._x = this._x * l;
  2464. this._y = this._y * l;
  2465. this._z = this._z * l;
  2466. this._w = this._w * l;
  2467. }
  2468. this._onChangeCallback();
  2469. return this;
  2470. }
  2471. multiply( q ) {
  2472. return this.multiplyQuaternions( this, q );
  2473. }
  2474. premultiply( q ) {
  2475. return this.multiplyQuaternions( q, this );
  2476. }
  2477. multiplyQuaternions( a, b ) {
  2478. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2479. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2480. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2481. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2482. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2483. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2484. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2485. this._onChangeCallback();
  2486. return this;
  2487. }
  2488. slerp( qb, t ) {
  2489. if ( t === 0 ) return this;
  2490. if ( t === 1 ) return this.copy( qb );
  2491. const x = this._x, y = this._y, z = this._z, w = this._w;
  2492. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2493. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2494. if ( cosHalfTheta < 0 ) {
  2495. this._w = - qb._w;
  2496. this._x = - qb._x;
  2497. this._y = - qb._y;
  2498. this._z = - qb._z;
  2499. cosHalfTheta = - cosHalfTheta;
  2500. } else {
  2501. this.copy( qb );
  2502. }
  2503. if ( cosHalfTheta >= 1.0 ) {
  2504. this._w = w;
  2505. this._x = x;
  2506. this._y = y;
  2507. this._z = z;
  2508. return this;
  2509. }
  2510. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2511. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2512. const s = 1 - t;
  2513. this._w = s * w + t * this._w;
  2514. this._x = s * x + t * this._x;
  2515. this._y = s * y + t * this._y;
  2516. this._z = s * z + t * this._z;
  2517. this.normalize();
  2518. this._onChangeCallback();
  2519. return this;
  2520. }
  2521. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2522. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2523. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2524. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2525. this._w = ( w * ratioA + this._w * ratioB );
  2526. this._x = ( x * ratioA + this._x * ratioB );
  2527. this._y = ( y * ratioA + this._y * ratioB );
  2528. this._z = ( z * ratioA + this._z * ratioB );
  2529. this._onChangeCallback();
  2530. return this;
  2531. }
  2532. slerpQuaternions( qa, qb, t ) {
  2533. return this.copy( qa ).slerp( qb, t );
  2534. }
  2535. random() {
  2536. // Derived from http://planning.cs.uiuc.edu/node198.html
  2537. // Note, this source uses w, x, y, z ordering,
  2538. // so we swap the order below.
  2539. const u1 = Math.random();
  2540. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2541. const sqrtu1 = Math.sqrt( u1 );
  2542. const u2 = 2 * Math.PI * Math.random();
  2543. const u3 = 2 * Math.PI * Math.random();
  2544. return this.set(
  2545. sqrt1u1 * Math.cos( u2 ),
  2546. sqrtu1 * Math.sin( u3 ),
  2547. sqrtu1 * Math.cos( u3 ),
  2548. sqrt1u1 * Math.sin( u2 ),
  2549. );
  2550. }
  2551. equals( quaternion ) {
  2552. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2553. }
  2554. fromArray( array, offset = 0 ) {
  2555. this._x = array[ offset ];
  2556. this._y = array[ offset + 1 ];
  2557. this._z = array[ offset + 2 ];
  2558. this._w = array[ offset + 3 ];
  2559. this._onChangeCallback();
  2560. return this;
  2561. }
  2562. toArray( array = [], offset = 0 ) {
  2563. array[ offset ] = this._x;
  2564. array[ offset + 1 ] = this._y;
  2565. array[ offset + 2 ] = this._z;
  2566. array[ offset + 3 ] = this._w;
  2567. return array;
  2568. }
  2569. fromBufferAttribute( attribute, index ) {
  2570. this._x = attribute.getX( index );
  2571. this._y = attribute.getY( index );
  2572. this._z = attribute.getZ( index );
  2573. this._w = attribute.getW( index );
  2574. return this;
  2575. }
  2576. _onChange( callback ) {
  2577. this._onChangeCallback = callback;
  2578. return this;
  2579. }
  2580. _onChangeCallback() {}
  2581. *[ Symbol.iterator ]() {
  2582. yield this._x;
  2583. yield this._y;
  2584. yield this._z;
  2585. yield this._w;
  2586. }
  2587. }
  2588. class Vector3 {
  2589. constructor( x = 0, y = 0, z = 0 ) {
  2590. Vector3.prototype.isVector3 = true;
  2591. this.x = x;
  2592. this.y = y;
  2593. this.z = z;
  2594. }
  2595. set( x, y, z ) {
  2596. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2597. this.x = x;
  2598. this.y = y;
  2599. this.z = z;
  2600. return this;
  2601. }
  2602. setScalar( scalar ) {
  2603. this.x = scalar;
  2604. this.y = scalar;
  2605. this.z = scalar;
  2606. return this;
  2607. }
  2608. setX( x ) {
  2609. this.x = x;
  2610. return this;
  2611. }
  2612. setY( y ) {
  2613. this.y = y;
  2614. return this;
  2615. }
  2616. setZ( z ) {
  2617. this.z = z;
  2618. return this;
  2619. }
  2620. setComponent( index, value ) {
  2621. switch ( index ) {
  2622. case 0: this.x = value; break;
  2623. case 1: this.y = value; break;
  2624. case 2: this.z = value; break;
  2625. default: throw new Error( 'index is out of range: ' + index );
  2626. }
  2627. return this;
  2628. }
  2629. getComponent( index ) {
  2630. switch ( index ) {
  2631. case 0: return this.x;
  2632. case 1: return this.y;
  2633. case 2: return this.z;
  2634. default: throw new Error( 'index is out of range: ' + index );
  2635. }
  2636. }
  2637. clone() {
  2638. return new this.constructor( this.x, this.y, this.z );
  2639. }
  2640. copy( v ) {
  2641. this.x = v.x;
  2642. this.y = v.y;
  2643. this.z = v.z;
  2644. return this;
  2645. }
  2646. add( v ) {
  2647. this.x += v.x;
  2648. this.y += v.y;
  2649. this.z += v.z;
  2650. return this;
  2651. }
  2652. addScalar( s ) {
  2653. this.x += s;
  2654. this.y += s;
  2655. this.z += s;
  2656. return this;
  2657. }
  2658. addVectors( a, b ) {
  2659. this.x = a.x + b.x;
  2660. this.y = a.y + b.y;
  2661. this.z = a.z + b.z;
  2662. return this;
  2663. }
  2664. addScaledVector( v, s ) {
  2665. this.x += v.x * s;
  2666. this.y += v.y * s;
  2667. this.z += v.z * s;
  2668. return this;
  2669. }
  2670. sub( v ) {
  2671. this.x -= v.x;
  2672. this.y -= v.y;
  2673. this.z -= v.z;
  2674. return this;
  2675. }
  2676. subScalar( s ) {
  2677. this.x -= s;
  2678. this.y -= s;
  2679. this.z -= s;
  2680. return this;
  2681. }
  2682. subVectors( a, b ) {
  2683. this.x = a.x - b.x;
  2684. this.y = a.y - b.y;
  2685. this.z = a.z - b.z;
  2686. return this;
  2687. }
  2688. multiply( v ) {
  2689. this.x *= v.x;
  2690. this.y *= v.y;
  2691. this.z *= v.z;
  2692. return this;
  2693. }
  2694. multiplyScalar( scalar ) {
  2695. this.x *= scalar;
  2696. this.y *= scalar;
  2697. this.z *= scalar;
  2698. return this;
  2699. }
  2700. multiplyVectors( a, b ) {
  2701. this.x = a.x * b.x;
  2702. this.y = a.y * b.y;
  2703. this.z = a.z * b.z;
  2704. return this;
  2705. }
  2706. applyEuler( euler ) {
  2707. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2708. }
  2709. applyAxisAngle( axis, angle ) {
  2710. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2711. }
  2712. applyMatrix3( m ) {
  2713. const x = this.x, y = this.y, z = this.z;
  2714. const e = m.elements;
  2715. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2716. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2717. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2718. return this;
  2719. }
  2720. applyNormalMatrix( m ) {
  2721. return this.applyMatrix3( m ).normalize();
  2722. }
  2723. applyMatrix4( m ) {
  2724. const x = this.x, y = this.y, z = this.z;
  2725. const e = m.elements;
  2726. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2727. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2728. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2729. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2730. return this;
  2731. }
  2732. applyQuaternion( q ) {
  2733. const x = this.x, y = this.y, z = this.z;
  2734. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2735. // calculate quat * vector
  2736. const ix = qw * x + qy * z - qz * y;
  2737. const iy = qw * y + qz * x - qx * z;
  2738. const iz = qw * z + qx * y - qy * x;
  2739. const iw = - qx * x - qy * y - qz * z;
  2740. // calculate result * inverse quat
  2741. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2742. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2743. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2744. return this;
  2745. }
  2746. project( camera ) {
  2747. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2748. }
  2749. unproject( camera ) {
  2750. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2751. }
  2752. transformDirection( m ) {
  2753. // input: THREE.Matrix4 affine matrix
  2754. // vector interpreted as a direction
  2755. const x = this.x, y = this.y, z = this.z;
  2756. const e = m.elements;
  2757. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2758. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2759. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2760. return this.normalize();
  2761. }
  2762. divide( v ) {
  2763. this.x /= v.x;
  2764. this.y /= v.y;
  2765. this.z /= v.z;
  2766. return this;
  2767. }
  2768. divideScalar( scalar ) {
  2769. return this.multiplyScalar( 1 / scalar );
  2770. }
  2771. min( v ) {
  2772. this.x = Math.min( this.x, v.x );
  2773. this.y = Math.min( this.y, v.y );
  2774. this.z = Math.min( this.z, v.z );
  2775. return this;
  2776. }
  2777. max( v ) {
  2778. this.x = Math.max( this.x, v.x );
  2779. this.y = Math.max( this.y, v.y );
  2780. this.z = Math.max( this.z, v.z );
  2781. return this;
  2782. }
  2783. clamp( min, max ) {
  2784. // assumes min < max, componentwise
  2785. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2786. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2787. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2788. return this;
  2789. }
  2790. clampScalar( minVal, maxVal ) {
  2791. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2792. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2793. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2794. return this;
  2795. }
  2796. clampLength( min, max ) {
  2797. const length = this.length();
  2798. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2799. }
  2800. floor() {
  2801. this.x = Math.floor( this.x );
  2802. this.y = Math.floor( this.y );
  2803. this.z = Math.floor( this.z );
  2804. return this;
  2805. }
  2806. ceil() {
  2807. this.x = Math.ceil( this.x );
  2808. this.y = Math.ceil( this.y );
  2809. this.z = Math.ceil( this.z );
  2810. return this;
  2811. }
  2812. round() {
  2813. this.x = Math.round( this.x );
  2814. this.y = Math.round( this.y );
  2815. this.z = Math.round( this.z );
  2816. return this;
  2817. }
  2818. roundToZero() {
  2819. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2820. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2821. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2822. return this;
  2823. }
  2824. negate() {
  2825. this.x = - this.x;
  2826. this.y = - this.y;
  2827. this.z = - this.z;
  2828. return this;
  2829. }
  2830. dot( v ) {
  2831. return this.x * v.x + this.y * v.y + this.z * v.z;
  2832. }
  2833. // TODO lengthSquared?
  2834. lengthSq() {
  2835. return this.x * this.x + this.y * this.y + this.z * this.z;
  2836. }
  2837. length() {
  2838. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2839. }
  2840. manhattanLength() {
  2841. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2842. }
  2843. normalize() {
  2844. return this.divideScalar( this.length() || 1 );
  2845. }
  2846. setLength( length ) {
  2847. return this.normalize().multiplyScalar( length );
  2848. }
  2849. lerp( v, alpha ) {
  2850. this.x += ( v.x - this.x ) * alpha;
  2851. this.y += ( v.y - this.y ) * alpha;
  2852. this.z += ( v.z - this.z ) * alpha;
  2853. return this;
  2854. }
  2855. lerpVectors( v1, v2, alpha ) {
  2856. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2857. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2858. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2859. return this;
  2860. }
  2861. cross( v ) {
  2862. return this.crossVectors( this, v );
  2863. }
  2864. crossVectors( a, b ) {
  2865. const ax = a.x, ay = a.y, az = a.z;
  2866. const bx = b.x, by = b.y, bz = b.z;
  2867. this.x = ay * bz - az * by;
  2868. this.y = az * bx - ax * bz;
  2869. this.z = ax * by - ay * bx;
  2870. return this;
  2871. }
  2872. projectOnVector( v ) {
  2873. const denominator = v.lengthSq();
  2874. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2875. const scalar = v.dot( this ) / denominator;
  2876. return this.copy( v ).multiplyScalar( scalar );
  2877. }
  2878. projectOnPlane( planeNormal ) {
  2879. _vector$c.copy( this ).projectOnVector( planeNormal );
  2880. return this.sub( _vector$c );
  2881. }
  2882. reflect( normal ) {
  2883. // reflect incident vector off plane orthogonal to normal
  2884. // normal is assumed to have unit length
  2885. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2886. }
  2887. angleTo( v ) {
  2888. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2889. if ( denominator === 0 ) return Math.PI / 2;
  2890. const theta = this.dot( v ) / denominator;
  2891. // clamp, to handle numerical problems
  2892. return Math.acos( clamp( theta, - 1, 1 ) );
  2893. }
  2894. distanceTo( v ) {
  2895. return Math.sqrt( this.distanceToSquared( v ) );
  2896. }
  2897. distanceToSquared( v ) {
  2898. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2899. return dx * dx + dy * dy + dz * dz;
  2900. }
  2901. manhattanDistanceTo( v ) {
  2902. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2903. }
  2904. setFromSpherical( s ) {
  2905. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2906. }
  2907. setFromSphericalCoords( radius, phi, theta ) {
  2908. const sinPhiRadius = Math.sin( phi ) * radius;
  2909. this.x = sinPhiRadius * Math.sin( theta );
  2910. this.y = Math.cos( phi ) * radius;
  2911. this.z = sinPhiRadius * Math.cos( theta );
  2912. return this;
  2913. }
  2914. setFromCylindrical( c ) {
  2915. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2916. }
  2917. setFromCylindricalCoords( radius, theta, y ) {
  2918. this.x = radius * Math.sin( theta );
  2919. this.y = y;
  2920. this.z = radius * Math.cos( theta );
  2921. return this;
  2922. }
  2923. setFromMatrixPosition( m ) {
  2924. const e = m.elements;
  2925. this.x = e[ 12 ];
  2926. this.y = e[ 13 ];
  2927. this.z = e[ 14 ];
  2928. return this;
  2929. }
  2930. setFromMatrixScale( m ) {
  2931. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2932. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2933. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2934. this.x = sx;
  2935. this.y = sy;
  2936. this.z = sz;
  2937. return this;
  2938. }
  2939. setFromMatrixColumn( m, index ) {
  2940. return this.fromArray( m.elements, index * 4 );
  2941. }
  2942. setFromMatrix3Column( m, index ) {
  2943. return this.fromArray( m.elements, index * 3 );
  2944. }
  2945. setFromEuler( e ) {
  2946. this.x = e._x;
  2947. this.y = e._y;
  2948. this.z = e._z;
  2949. return this;
  2950. }
  2951. equals( v ) {
  2952. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2953. }
  2954. fromArray( array, offset = 0 ) {
  2955. this.x = array[ offset ];
  2956. this.y = array[ offset + 1 ];
  2957. this.z = array[ offset + 2 ];
  2958. return this;
  2959. }
  2960. toArray( array = [], offset = 0 ) {
  2961. array[ offset ] = this.x;
  2962. array[ offset + 1 ] = this.y;
  2963. array[ offset + 2 ] = this.z;
  2964. return array;
  2965. }
  2966. fromBufferAttribute( attribute, index ) {
  2967. this.x = attribute.getX( index );
  2968. this.y = attribute.getY( index );
  2969. this.z = attribute.getZ( index );
  2970. return this;
  2971. }
  2972. random() {
  2973. this.x = Math.random();
  2974. this.y = Math.random();
  2975. this.z = Math.random();
  2976. return this;
  2977. }
  2978. randomDirection() {
  2979. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2980. const u = ( Math.random() - 0.5 ) * 2;
  2981. const t = Math.random() * Math.PI * 2;
  2982. const f = Math.sqrt( 1 - u ** 2 );
  2983. this.x = f * Math.cos( t );
  2984. this.y = f * Math.sin( t );
  2985. this.z = u;
  2986. return this;
  2987. }
  2988. *[ Symbol.iterator ]() {
  2989. yield this.x;
  2990. yield this.y;
  2991. yield this.z;
  2992. }
  2993. }
  2994. const _vector$c = /*@__PURE__*/ new Vector3();
  2995. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2996. class Box3 {
  2997. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2998. this.isBox3 = true;
  2999. this.min = min;
  3000. this.max = max;
  3001. }
  3002. set( min, max ) {
  3003. this.min.copy( min );
  3004. this.max.copy( max );
  3005. return this;
  3006. }
  3007. setFromArray( array ) {
  3008. let minX = + Infinity;
  3009. let minY = + Infinity;
  3010. let minZ = + Infinity;
  3011. let maxX = - Infinity;
  3012. let maxY = - Infinity;
  3013. let maxZ = - Infinity;
  3014. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3015. const x = array[ i ];
  3016. const y = array[ i + 1 ];
  3017. const z = array[ i + 2 ];
  3018. if ( x < minX ) minX = x;
  3019. if ( y < minY ) minY = y;
  3020. if ( z < minZ ) minZ = z;
  3021. if ( x > maxX ) maxX = x;
  3022. if ( y > maxY ) maxY = y;
  3023. if ( z > maxZ ) maxZ = z;
  3024. }
  3025. this.min.set( minX, minY, minZ );
  3026. this.max.set( maxX, maxY, maxZ );
  3027. return this;
  3028. }
  3029. setFromBufferAttribute( attribute ) {
  3030. let minX = + Infinity;
  3031. let minY = + Infinity;
  3032. let minZ = + Infinity;
  3033. let maxX = - Infinity;
  3034. let maxY = - Infinity;
  3035. let maxZ = - Infinity;
  3036. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3037. const x = attribute.getX( i );
  3038. const y = attribute.getY( i );
  3039. const z = attribute.getZ( i );
  3040. if ( x < minX ) minX = x;
  3041. if ( y < minY ) minY = y;
  3042. if ( z < minZ ) minZ = z;
  3043. if ( x > maxX ) maxX = x;
  3044. if ( y > maxY ) maxY = y;
  3045. if ( z > maxZ ) maxZ = z;
  3046. }
  3047. this.min.set( minX, minY, minZ );
  3048. this.max.set( maxX, maxY, maxZ );
  3049. return this;
  3050. }
  3051. setFromPoints( points ) {
  3052. this.makeEmpty();
  3053. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3054. this.expandByPoint( points[ i ] );
  3055. }
  3056. return this;
  3057. }
  3058. setFromCenterAndSize( center, size ) {
  3059. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3060. this.min.copy( center ).sub( halfSize );
  3061. this.max.copy( center ).add( halfSize );
  3062. return this;
  3063. }
  3064. setFromObject( object, precise = false ) {
  3065. this.makeEmpty();
  3066. return this.expandByObject( object, precise );
  3067. }
  3068. clone() {
  3069. return new this.constructor().copy( this );
  3070. }
  3071. copy( box ) {
  3072. this.min.copy( box.min );
  3073. this.max.copy( box.max );
  3074. return this;
  3075. }
  3076. makeEmpty() {
  3077. this.min.x = this.min.y = this.min.z = + Infinity;
  3078. this.max.x = this.max.y = this.max.z = - Infinity;
  3079. return this;
  3080. }
  3081. isEmpty() {
  3082. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3083. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3084. }
  3085. getCenter( target ) {
  3086. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3087. }
  3088. getSize( target ) {
  3089. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3090. }
  3091. expandByPoint( point ) {
  3092. this.min.min( point );
  3093. this.max.max( point );
  3094. return this;
  3095. }
  3096. expandByVector( vector ) {
  3097. this.min.sub( vector );
  3098. this.max.add( vector );
  3099. return this;
  3100. }
  3101. expandByScalar( scalar ) {
  3102. this.min.addScalar( - scalar );
  3103. this.max.addScalar( scalar );
  3104. return this;
  3105. }
  3106. expandByObject( object, precise = false ) {
  3107. // Computes the world-axis-aligned bounding box of an object (including its children),
  3108. // accounting for both the object's, and children's, world transforms
  3109. object.updateWorldMatrix( false, false );
  3110. const geometry = object.geometry;
  3111. if ( geometry !== undefined ) {
  3112. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3113. const position = geometry.attributes.position;
  3114. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3115. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3116. this.expandByPoint( _vector$b );
  3117. }
  3118. } else {
  3119. if ( geometry.boundingBox === null ) {
  3120. geometry.computeBoundingBox();
  3121. }
  3122. _box$3.copy( geometry.boundingBox );
  3123. _box$3.applyMatrix4( object.matrixWorld );
  3124. this.union( _box$3 );
  3125. }
  3126. }
  3127. const children = object.children;
  3128. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3129. this.expandByObject( children[ i ], precise );
  3130. }
  3131. return this;
  3132. }
  3133. containsPoint( point ) {
  3134. return point.x < this.min.x || point.x > this.max.x ||
  3135. point.y < this.min.y || point.y > this.max.y ||
  3136. point.z < this.min.z || point.z > this.max.z ? false : true;
  3137. }
  3138. containsBox( box ) {
  3139. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3140. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3141. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3142. }
  3143. getParameter( point, target ) {
  3144. // This can potentially have a divide by zero if the box
  3145. // has a size dimension of 0.
  3146. return target.set(
  3147. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3148. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3149. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3150. );
  3151. }
  3152. intersectsBox( box ) {
  3153. // using 6 splitting planes to rule out intersections.
  3154. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3155. box.max.y < this.min.y || box.min.y > this.max.y ||
  3156. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3157. }
  3158. intersectsSphere( sphere ) {
  3159. // Find the point on the AABB closest to the sphere center.
  3160. this.clampPoint( sphere.center, _vector$b );
  3161. // If that point is inside the sphere, the AABB and sphere intersect.
  3162. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3163. }
  3164. intersectsPlane( plane ) {
  3165. // We compute the minimum and maximum dot product values. If those values
  3166. // are on the same side (back or front) of the plane, then there is no intersection.
  3167. let min, max;
  3168. if ( plane.normal.x > 0 ) {
  3169. min = plane.normal.x * this.min.x;
  3170. max = plane.normal.x * this.max.x;
  3171. } else {
  3172. min = plane.normal.x * this.max.x;
  3173. max = plane.normal.x * this.min.x;
  3174. }
  3175. if ( plane.normal.y > 0 ) {
  3176. min += plane.normal.y * this.min.y;
  3177. max += plane.normal.y * this.max.y;
  3178. } else {
  3179. min += plane.normal.y * this.max.y;
  3180. max += plane.normal.y * this.min.y;
  3181. }
  3182. if ( plane.normal.z > 0 ) {
  3183. min += plane.normal.z * this.min.z;
  3184. max += plane.normal.z * this.max.z;
  3185. } else {
  3186. min += plane.normal.z * this.max.z;
  3187. max += plane.normal.z * this.min.z;
  3188. }
  3189. return ( min <= - plane.constant && max >= - plane.constant );
  3190. }
  3191. intersectsTriangle( triangle ) {
  3192. if ( this.isEmpty() ) {
  3193. return false;
  3194. }
  3195. // compute box center and extents
  3196. this.getCenter( _center );
  3197. _extents.subVectors( this.max, _center );
  3198. // translate triangle to aabb origin
  3199. _v0$2.subVectors( triangle.a, _center );
  3200. _v1$7.subVectors( triangle.b, _center );
  3201. _v2$4.subVectors( triangle.c, _center );
  3202. // compute edge vectors for triangle
  3203. _f0.subVectors( _v1$7, _v0$2 );
  3204. _f1.subVectors( _v2$4, _v1$7 );
  3205. _f2.subVectors( _v0$2, _v2$4 );
  3206. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3207. // 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
  3208. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3209. let axes = [
  3210. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3211. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3212. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3213. ];
  3214. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3215. return false;
  3216. }
  3217. // test 3 face normals from the aabb
  3218. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3219. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3220. return false;
  3221. }
  3222. // finally testing the face normal of the triangle
  3223. // use already existing triangle edge vectors here
  3224. _triangleNormal.crossVectors( _f0, _f1 );
  3225. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3226. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3227. }
  3228. clampPoint( point, target ) {
  3229. return target.copy( point ).clamp( this.min, this.max );
  3230. }
  3231. distanceToPoint( point ) {
  3232. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3233. return clampedPoint.sub( point ).length();
  3234. }
  3235. getBoundingSphere( target ) {
  3236. this.getCenter( target.center );
  3237. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3238. return target;
  3239. }
  3240. intersect( box ) {
  3241. this.min.max( box.min );
  3242. this.max.min( box.max );
  3243. // 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.
  3244. if ( this.isEmpty() ) this.makeEmpty();
  3245. return this;
  3246. }
  3247. union( box ) {
  3248. this.min.min( box.min );
  3249. this.max.max( box.max );
  3250. return this;
  3251. }
  3252. applyMatrix4( matrix ) {
  3253. // transform of empty box is an empty box.
  3254. if ( this.isEmpty() ) return this;
  3255. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3256. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3257. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3258. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3259. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3260. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3261. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3262. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3263. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3264. this.setFromPoints( _points );
  3265. return this;
  3266. }
  3267. translate( offset ) {
  3268. this.min.add( offset );
  3269. this.max.add( offset );
  3270. return this;
  3271. }
  3272. equals( box ) {
  3273. return box.min.equals( this.min ) && box.max.equals( this.max );
  3274. }
  3275. }
  3276. const _points = [
  3277. /*@__PURE__*/ new Vector3(),
  3278. /*@__PURE__*/ new Vector3(),
  3279. /*@__PURE__*/ new Vector3(),
  3280. /*@__PURE__*/ new Vector3(),
  3281. /*@__PURE__*/ new Vector3(),
  3282. /*@__PURE__*/ new Vector3(),
  3283. /*@__PURE__*/ new Vector3(),
  3284. /*@__PURE__*/ new Vector3()
  3285. ];
  3286. const _vector$b = /*@__PURE__*/ new Vector3();
  3287. const _box$3 = /*@__PURE__*/ new Box3();
  3288. // triangle centered vertices
  3289. const _v0$2 = /*@__PURE__*/ new Vector3();
  3290. const _v1$7 = /*@__PURE__*/ new Vector3();
  3291. const _v2$4 = /*@__PURE__*/ new Vector3();
  3292. // triangle edge vectors
  3293. const _f0 = /*@__PURE__*/ new Vector3();
  3294. const _f1 = /*@__PURE__*/ new Vector3();
  3295. const _f2 = /*@__PURE__*/ new Vector3();
  3296. const _center = /*@__PURE__*/ new Vector3();
  3297. const _extents = /*@__PURE__*/ new Vector3();
  3298. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3299. const _testAxis = /*@__PURE__*/ new Vector3();
  3300. function satForAxes( axes, v0, v1, v2, extents ) {
  3301. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3302. _testAxis.fromArray( axes, i );
  3303. // project the aabb onto the separating axis
  3304. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3305. // project all 3 vertices of the triangle onto the separating axis
  3306. const p0 = v0.dot( _testAxis );
  3307. const p1 = v1.dot( _testAxis );
  3308. const p2 = v2.dot( _testAxis );
  3309. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3310. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3311. // points of the projected triangle are outside the projected half-length of the aabb
  3312. // the axis is separating and we can exit
  3313. return false;
  3314. }
  3315. }
  3316. return true;
  3317. }
  3318. const _box$2 = /*@__PURE__*/ new Box3();
  3319. const _v1$6 = /*@__PURE__*/ new Vector3();
  3320. const _v2$3 = /*@__PURE__*/ new Vector3();
  3321. class Sphere {
  3322. constructor( center = new Vector3(), radius = - 1 ) {
  3323. this.center = center;
  3324. this.radius = radius;
  3325. }
  3326. set( center, radius ) {
  3327. this.center.copy( center );
  3328. this.radius = radius;
  3329. return this;
  3330. }
  3331. setFromPoints( points, optionalCenter ) {
  3332. const center = this.center;
  3333. if ( optionalCenter !== undefined ) {
  3334. center.copy( optionalCenter );
  3335. } else {
  3336. _box$2.setFromPoints( points ).getCenter( center );
  3337. }
  3338. let maxRadiusSq = 0;
  3339. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3340. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3341. }
  3342. this.radius = Math.sqrt( maxRadiusSq );
  3343. return this;
  3344. }
  3345. copy( sphere ) {
  3346. this.center.copy( sphere.center );
  3347. this.radius = sphere.radius;
  3348. return this;
  3349. }
  3350. isEmpty() {
  3351. return ( this.radius < 0 );
  3352. }
  3353. makeEmpty() {
  3354. this.center.set( 0, 0, 0 );
  3355. this.radius = - 1;
  3356. return this;
  3357. }
  3358. containsPoint( point ) {
  3359. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3360. }
  3361. distanceToPoint( point ) {
  3362. return ( point.distanceTo( this.center ) - this.radius );
  3363. }
  3364. intersectsSphere( sphere ) {
  3365. const radiusSum = this.radius + sphere.radius;
  3366. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3367. }
  3368. intersectsBox( box ) {
  3369. return box.intersectsSphere( this );
  3370. }
  3371. intersectsPlane( plane ) {
  3372. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3373. }
  3374. clampPoint( point, target ) {
  3375. const deltaLengthSq = this.center.distanceToSquared( point );
  3376. target.copy( point );
  3377. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3378. target.sub( this.center ).normalize();
  3379. target.multiplyScalar( this.radius ).add( this.center );
  3380. }
  3381. return target;
  3382. }
  3383. getBoundingBox( target ) {
  3384. if ( this.isEmpty() ) {
  3385. // Empty sphere produces empty bounding box
  3386. target.makeEmpty();
  3387. return target;
  3388. }
  3389. target.set( this.center, this.center );
  3390. target.expandByScalar( this.radius );
  3391. return target;
  3392. }
  3393. applyMatrix4( matrix ) {
  3394. this.center.applyMatrix4( matrix );
  3395. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3396. return this;
  3397. }
  3398. translate( offset ) {
  3399. this.center.add( offset );
  3400. return this;
  3401. }
  3402. expandByPoint( point ) {
  3403. if ( this.isEmpty() ) {
  3404. this.center.copy( point );
  3405. this.radius = 0;
  3406. return this;
  3407. }
  3408. _v1$6.subVectors( point, this.center );
  3409. const lengthSq = _v1$6.lengthSq();
  3410. if ( lengthSq > ( this.radius * this.radius ) ) {
  3411. // calculate the minimal sphere
  3412. const length = Math.sqrt( lengthSq );
  3413. const delta = ( length - this.radius ) * 0.5;
  3414. this.center.addScaledVector( _v1$6, delta / length );
  3415. this.radius += delta;
  3416. }
  3417. return this;
  3418. }
  3419. union( sphere ) {
  3420. if ( sphere.isEmpty() ) {
  3421. return this;
  3422. }
  3423. if ( this.isEmpty() ) {
  3424. this.copy( sphere );
  3425. return this;
  3426. }
  3427. if ( this.center.equals( sphere.center ) === true ) {
  3428. this.radius = Math.max( this.radius, sphere.radius );
  3429. } else {
  3430. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3431. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3432. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3433. }
  3434. return this;
  3435. }
  3436. equals( sphere ) {
  3437. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3438. }
  3439. clone() {
  3440. return new this.constructor().copy( this );
  3441. }
  3442. }
  3443. const _vector$a = /*@__PURE__*/ new Vector3();
  3444. const _segCenter = /*@__PURE__*/ new Vector3();
  3445. const _segDir = /*@__PURE__*/ new Vector3();
  3446. const _diff = /*@__PURE__*/ new Vector3();
  3447. const _edge1 = /*@__PURE__*/ new Vector3();
  3448. const _edge2 = /*@__PURE__*/ new Vector3();
  3449. const _normal$1 = /*@__PURE__*/ new Vector3();
  3450. class Ray {
  3451. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3452. this.origin = origin;
  3453. this.direction = direction;
  3454. }
  3455. set( origin, direction ) {
  3456. this.origin.copy( origin );
  3457. this.direction.copy( direction );
  3458. return this;
  3459. }
  3460. copy( ray ) {
  3461. this.origin.copy( ray.origin );
  3462. this.direction.copy( ray.direction );
  3463. return this;
  3464. }
  3465. at( t, target ) {
  3466. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3467. }
  3468. lookAt( v ) {
  3469. this.direction.copy( v ).sub( this.origin ).normalize();
  3470. return this;
  3471. }
  3472. recast( t ) {
  3473. this.origin.copy( this.at( t, _vector$a ) );
  3474. return this;
  3475. }
  3476. closestPointToPoint( point, target ) {
  3477. target.subVectors( point, this.origin );
  3478. const directionDistance = target.dot( this.direction );
  3479. if ( directionDistance < 0 ) {
  3480. return target.copy( this.origin );
  3481. }
  3482. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3483. }
  3484. distanceToPoint( point ) {
  3485. return Math.sqrt( this.distanceSqToPoint( point ) );
  3486. }
  3487. distanceSqToPoint( point ) {
  3488. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3489. // point behind the ray
  3490. if ( directionDistance < 0 ) {
  3491. return this.origin.distanceToSquared( point );
  3492. }
  3493. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3494. return _vector$a.distanceToSquared( point );
  3495. }
  3496. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3497. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3498. // It returns the min distance between the ray and the segment
  3499. // defined by v0 and v1
  3500. // It can also set two optional targets :
  3501. // - The closest point on the ray
  3502. // - The closest point on the segment
  3503. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3504. _segDir.copy( v1 ).sub( v0 ).normalize();
  3505. _diff.copy( this.origin ).sub( _segCenter );
  3506. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3507. const a01 = - this.direction.dot( _segDir );
  3508. const b0 = _diff.dot( this.direction );
  3509. const b1 = - _diff.dot( _segDir );
  3510. const c = _diff.lengthSq();
  3511. const det = Math.abs( 1 - a01 * a01 );
  3512. let s0, s1, sqrDist, extDet;
  3513. if ( det > 0 ) {
  3514. // The ray and segment are not parallel.
  3515. s0 = a01 * b1 - b0;
  3516. s1 = a01 * b0 - b1;
  3517. extDet = segExtent * det;
  3518. if ( s0 >= 0 ) {
  3519. if ( s1 >= - extDet ) {
  3520. if ( s1 <= extDet ) {
  3521. // region 0
  3522. // Minimum at interior points of ray and segment.
  3523. const invDet = 1 / det;
  3524. s0 *= invDet;
  3525. s1 *= invDet;
  3526. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3527. } else {
  3528. // region 1
  3529. s1 = segExtent;
  3530. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3531. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3532. }
  3533. } else {
  3534. // region 5
  3535. s1 = - segExtent;
  3536. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3537. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3538. }
  3539. } else {
  3540. if ( s1 <= - extDet ) {
  3541. // region 4
  3542. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3543. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3544. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3545. } else if ( s1 <= extDet ) {
  3546. // region 3
  3547. s0 = 0;
  3548. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3549. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3550. } else {
  3551. // region 2
  3552. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3553. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3554. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3555. }
  3556. }
  3557. } else {
  3558. // Ray and segment are parallel.
  3559. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3560. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3561. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3562. }
  3563. if ( optionalPointOnRay ) {
  3564. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3565. }
  3566. if ( optionalPointOnSegment ) {
  3567. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3568. }
  3569. return sqrDist;
  3570. }
  3571. intersectSphere( sphere, target ) {
  3572. _vector$a.subVectors( sphere.center, this.origin );
  3573. const tca = _vector$a.dot( this.direction );
  3574. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3575. const radius2 = sphere.radius * sphere.radius;
  3576. if ( d2 > radius2 ) return null;
  3577. const thc = Math.sqrt( radius2 - d2 );
  3578. // t0 = first intersect point - entrance on front of sphere
  3579. const t0 = tca - thc;
  3580. // t1 = second intersect point - exit point on back of sphere
  3581. const t1 = tca + thc;
  3582. // test to see if both t0 and t1 are behind the ray - if so, return null
  3583. if ( t0 < 0 && t1 < 0 ) return null;
  3584. // test to see if t0 is behind the ray:
  3585. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3586. // in order to always return an intersect point that is in front of the ray.
  3587. if ( t0 < 0 ) return this.at( t1, target );
  3588. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3589. return this.at( t0, target );
  3590. }
  3591. intersectsSphere( sphere ) {
  3592. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3593. }
  3594. distanceToPlane( plane ) {
  3595. const denominator = plane.normal.dot( this.direction );
  3596. if ( denominator === 0 ) {
  3597. // line is coplanar, return origin
  3598. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3599. return 0;
  3600. }
  3601. // Null is preferable to undefined since undefined means.... it is undefined
  3602. return null;
  3603. }
  3604. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3605. // Return if the ray never intersects the plane
  3606. return t >= 0 ? t : null;
  3607. }
  3608. intersectPlane( plane, target ) {
  3609. const t = this.distanceToPlane( plane );
  3610. if ( t === null ) {
  3611. return null;
  3612. }
  3613. return this.at( t, target );
  3614. }
  3615. intersectsPlane( plane ) {
  3616. // check if the ray lies on the plane first
  3617. const distToPoint = plane.distanceToPoint( this.origin );
  3618. if ( distToPoint === 0 ) {
  3619. return true;
  3620. }
  3621. const denominator = plane.normal.dot( this.direction );
  3622. if ( denominator * distToPoint < 0 ) {
  3623. return true;
  3624. }
  3625. // ray origin is behind the plane (and is pointing behind it)
  3626. return false;
  3627. }
  3628. intersectBox( box, target ) {
  3629. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3630. const invdirx = 1 / this.direction.x,
  3631. invdiry = 1 / this.direction.y,
  3632. invdirz = 1 / this.direction.z;
  3633. const origin = this.origin;
  3634. if ( invdirx >= 0 ) {
  3635. tmin = ( box.min.x - origin.x ) * invdirx;
  3636. tmax = ( box.max.x - origin.x ) * invdirx;
  3637. } else {
  3638. tmin = ( box.max.x - origin.x ) * invdirx;
  3639. tmax = ( box.min.x - origin.x ) * invdirx;
  3640. }
  3641. if ( invdiry >= 0 ) {
  3642. tymin = ( box.min.y - origin.y ) * invdiry;
  3643. tymax = ( box.max.y - origin.y ) * invdiry;
  3644. } else {
  3645. tymin = ( box.max.y - origin.y ) * invdiry;
  3646. tymax = ( box.min.y - origin.y ) * invdiry;
  3647. }
  3648. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3649. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3650. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3651. if ( invdirz >= 0 ) {
  3652. tzmin = ( box.min.z - origin.z ) * invdirz;
  3653. tzmax = ( box.max.z - origin.z ) * invdirz;
  3654. } else {
  3655. tzmin = ( box.max.z - origin.z ) * invdirz;
  3656. tzmax = ( box.min.z - origin.z ) * invdirz;
  3657. }
  3658. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3659. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3660. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3661. //return point closest to the ray (positive side)
  3662. if ( tmax < 0 ) return null;
  3663. return this.at( tmin >= 0 ? tmin : tmax, target );
  3664. }
  3665. intersectsBox( box ) {
  3666. return this.intersectBox( box, _vector$a ) !== null;
  3667. }
  3668. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3669. // Compute the offset origin, edges, and normal.
  3670. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3671. _edge1.subVectors( b, a );
  3672. _edge2.subVectors( c, a );
  3673. _normal$1.crossVectors( _edge1, _edge2 );
  3674. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3675. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3676. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3677. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3678. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3679. let DdN = this.direction.dot( _normal$1 );
  3680. let sign;
  3681. if ( DdN > 0 ) {
  3682. if ( backfaceCulling ) return null;
  3683. sign = 1;
  3684. } else if ( DdN < 0 ) {
  3685. sign = - 1;
  3686. DdN = - DdN;
  3687. } else {
  3688. return null;
  3689. }
  3690. _diff.subVectors( this.origin, a );
  3691. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3692. // b1 < 0, no intersection
  3693. if ( DdQxE2 < 0 ) {
  3694. return null;
  3695. }
  3696. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3697. // b2 < 0, no intersection
  3698. if ( DdE1xQ < 0 ) {
  3699. return null;
  3700. }
  3701. // b1+b2 > 1, no intersection
  3702. if ( DdQxE2 + DdE1xQ > DdN ) {
  3703. return null;
  3704. }
  3705. // Line intersects triangle, check if ray does.
  3706. const QdN = - sign * _diff.dot( _normal$1 );
  3707. // t < 0, no intersection
  3708. if ( QdN < 0 ) {
  3709. return null;
  3710. }
  3711. // Ray intersects triangle.
  3712. return this.at( QdN / DdN, target );
  3713. }
  3714. applyMatrix4( matrix4 ) {
  3715. this.origin.applyMatrix4( matrix4 );
  3716. this.direction.transformDirection( matrix4 );
  3717. return this;
  3718. }
  3719. equals( ray ) {
  3720. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3721. }
  3722. clone() {
  3723. return new this.constructor().copy( this );
  3724. }
  3725. }
  3726. class Matrix4 {
  3727. constructor() {
  3728. Matrix4.prototype.isMatrix4 = true;
  3729. this.elements = [
  3730. 1, 0, 0, 0,
  3731. 0, 1, 0, 0,
  3732. 0, 0, 1, 0,
  3733. 0, 0, 0, 1
  3734. ];
  3735. }
  3736. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3737. const te = this.elements;
  3738. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3739. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3740. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3741. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3742. return this;
  3743. }
  3744. identity() {
  3745. this.set(
  3746. 1, 0, 0, 0,
  3747. 0, 1, 0, 0,
  3748. 0, 0, 1, 0,
  3749. 0, 0, 0, 1
  3750. );
  3751. return this;
  3752. }
  3753. clone() {
  3754. return new Matrix4().fromArray( this.elements );
  3755. }
  3756. copy( m ) {
  3757. const te = this.elements;
  3758. const me = m.elements;
  3759. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3760. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3761. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3762. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3763. return this;
  3764. }
  3765. copyPosition( m ) {
  3766. const te = this.elements, me = m.elements;
  3767. te[ 12 ] = me[ 12 ];
  3768. te[ 13 ] = me[ 13 ];
  3769. te[ 14 ] = me[ 14 ];
  3770. return this;
  3771. }
  3772. setFromMatrix3( m ) {
  3773. const me = m.elements;
  3774. this.set(
  3775. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3776. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3777. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3778. 0, 0, 0, 1
  3779. );
  3780. return this;
  3781. }
  3782. extractBasis( xAxis, yAxis, zAxis ) {
  3783. xAxis.setFromMatrixColumn( this, 0 );
  3784. yAxis.setFromMatrixColumn( this, 1 );
  3785. zAxis.setFromMatrixColumn( this, 2 );
  3786. return this;
  3787. }
  3788. makeBasis( xAxis, yAxis, zAxis ) {
  3789. this.set(
  3790. xAxis.x, yAxis.x, zAxis.x, 0,
  3791. xAxis.y, yAxis.y, zAxis.y, 0,
  3792. xAxis.z, yAxis.z, zAxis.z, 0,
  3793. 0, 0, 0, 1
  3794. );
  3795. return this;
  3796. }
  3797. extractRotation( m ) {
  3798. // this method does not support reflection matrices
  3799. const te = this.elements;
  3800. const me = m.elements;
  3801. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3802. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3803. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3804. te[ 0 ] = me[ 0 ] * scaleX;
  3805. te[ 1 ] = me[ 1 ] * scaleX;
  3806. te[ 2 ] = me[ 2 ] * scaleX;
  3807. te[ 3 ] = 0;
  3808. te[ 4 ] = me[ 4 ] * scaleY;
  3809. te[ 5 ] = me[ 5 ] * scaleY;
  3810. te[ 6 ] = me[ 6 ] * scaleY;
  3811. te[ 7 ] = 0;
  3812. te[ 8 ] = me[ 8 ] * scaleZ;
  3813. te[ 9 ] = me[ 9 ] * scaleZ;
  3814. te[ 10 ] = me[ 10 ] * scaleZ;
  3815. te[ 11 ] = 0;
  3816. te[ 12 ] = 0;
  3817. te[ 13 ] = 0;
  3818. te[ 14 ] = 0;
  3819. te[ 15 ] = 1;
  3820. return this;
  3821. }
  3822. makeRotationFromEuler( euler ) {
  3823. const te = this.elements;
  3824. const x = euler.x, y = euler.y, z = euler.z;
  3825. const a = Math.cos( x ), b = Math.sin( x );
  3826. const c = Math.cos( y ), d = Math.sin( y );
  3827. const e = Math.cos( z ), f = Math.sin( z );
  3828. if ( euler.order === 'XYZ' ) {
  3829. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3830. te[ 0 ] = c * e;
  3831. te[ 4 ] = - c * f;
  3832. te[ 8 ] = d;
  3833. te[ 1 ] = af + be * d;
  3834. te[ 5 ] = ae - bf * d;
  3835. te[ 9 ] = - b * c;
  3836. te[ 2 ] = bf - ae * d;
  3837. te[ 6 ] = be + af * d;
  3838. te[ 10 ] = a * c;
  3839. } else if ( euler.order === 'YXZ' ) {
  3840. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3841. te[ 0 ] = ce + df * b;
  3842. te[ 4 ] = de * b - cf;
  3843. te[ 8 ] = a * d;
  3844. te[ 1 ] = a * f;
  3845. te[ 5 ] = a * e;
  3846. te[ 9 ] = - b;
  3847. te[ 2 ] = cf * b - de;
  3848. te[ 6 ] = df + ce * b;
  3849. te[ 10 ] = a * c;
  3850. } else if ( euler.order === 'ZXY' ) {
  3851. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3852. te[ 0 ] = ce - df * b;
  3853. te[ 4 ] = - a * f;
  3854. te[ 8 ] = de + cf * b;
  3855. te[ 1 ] = cf + de * b;
  3856. te[ 5 ] = a * e;
  3857. te[ 9 ] = df - ce * b;
  3858. te[ 2 ] = - a * d;
  3859. te[ 6 ] = b;
  3860. te[ 10 ] = a * c;
  3861. } else if ( euler.order === 'ZYX' ) {
  3862. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3863. te[ 0 ] = c * e;
  3864. te[ 4 ] = be * d - af;
  3865. te[ 8 ] = ae * d + bf;
  3866. te[ 1 ] = c * f;
  3867. te[ 5 ] = bf * d + ae;
  3868. te[ 9 ] = af * d - be;
  3869. te[ 2 ] = - d;
  3870. te[ 6 ] = b * c;
  3871. te[ 10 ] = a * c;
  3872. } else if ( euler.order === 'YZX' ) {
  3873. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3874. te[ 0 ] = c * e;
  3875. te[ 4 ] = bd - ac * f;
  3876. te[ 8 ] = bc * f + ad;
  3877. te[ 1 ] = f;
  3878. te[ 5 ] = a * e;
  3879. te[ 9 ] = - b * e;
  3880. te[ 2 ] = - d * e;
  3881. te[ 6 ] = ad * f + bc;
  3882. te[ 10 ] = ac - bd * f;
  3883. } else if ( euler.order === 'XZY' ) {
  3884. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3885. te[ 0 ] = c * e;
  3886. te[ 4 ] = - f;
  3887. te[ 8 ] = d * e;
  3888. te[ 1 ] = ac * f + bd;
  3889. te[ 5 ] = a * e;
  3890. te[ 9 ] = ad * f - bc;
  3891. te[ 2 ] = bc * f - ad;
  3892. te[ 6 ] = b * e;
  3893. te[ 10 ] = bd * f + ac;
  3894. }
  3895. // bottom row
  3896. te[ 3 ] = 0;
  3897. te[ 7 ] = 0;
  3898. te[ 11 ] = 0;
  3899. // last column
  3900. te[ 12 ] = 0;
  3901. te[ 13 ] = 0;
  3902. te[ 14 ] = 0;
  3903. te[ 15 ] = 1;
  3904. return this;
  3905. }
  3906. makeRotationFromQuaternion( q ) {
  3907. return this.compose( _zero, q, _one );
  3908. }
  3909. lookAt( eye, target, up ) {
  3910. const te = this.elements;
  3911. _z.subVectors( eye, target );
  3912. if ( _z.lengthSq() === 0 ) {
  3913. // eye and target are in the same position
  3914. _z.z = 1;
  3915. }
  3916. _z.normalize();
  3917. _x.crossVectors( up, _z );
  3918. if ( _x.lengthSq() === 0 ) {
  3919. // up and z are parallel
  3920. if ( Math.abs( up.z ) === 1 ) {
  3921. _z.x += 0.0001;
  3922. } else {
  3923. _z.z += 0.0001;
  3924. }
  3925. _z.normalize();
  3926. _x.crossVectors( up, _z );
  3927. }
  3928. _x.normalize();
  3929. _y.crossVectors( _z, _x );
  3930. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3931. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3932. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3933. return this;
  3934. }
  3935. multiply( m ) {
  3936. return this.multiplyMatrices( this, m );
  3937. }
  3938. premultiply( m ) {
  3939. return this.multiplyMatrices( m, this );
  3940. }
  3941. multiplyMatrices( a, b ) {
  3942. const ae = a.elements;
  3943. const be = b.elements;
  3944. const te = this.elements;
  3945. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3946. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3947. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3948. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3949. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3950. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3951. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3952. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3953. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3954. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3955. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3956. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3957. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3958. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3959. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3960. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3961. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3962. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3963. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3964. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3965. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3966. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3967. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3968. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3969. return this;
  3970. }
  3971. multiplyScalar( s ) {
  3972. const te = this.elements;
  3973. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3974. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3975. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3976. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3977. return this;
  3978. }
  3979. determinant() {
  3980. const te = this.elements;
  3981. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3982. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3983. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3984. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3985. //TODO: make this more efficient
  3986. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3987. return (
  3988. n41 * (
  3989. + n14 * n23 * n32
  3990. - n13 * n24 * n32
  3991. - n14 * n22 * n33
  3992. + n12 * n24 * n33
  3993. + n13 * n22 * n34
  3994. - n12 * n23 * n34
  3995. ) +
  3996. n42 * (
  3997. + n11 * n23 * n34
  3998. - n11 * n24 * n33
  3999. + n14 * n21 * n33
  4000. - n13 * n21 * n34
  4001. + n13 * n24 * n31
  4002. - n14 * n23 * n31
  4003. ) +
  4004. n43 * (
  4005. + n11 * n24 * n32
  4006. - n11 * n22 * n34
  4007. - n14 * n21 * n32
  4008. + n12 * n21 * n34
  4009. + n14 * n22 * n31
  4010. - n12 * n24 * n31
  4011. ) +
  4012. n44 * (
  4013. - n13 * n22 * n31
  4014. - n11 * n23 * n32
  4015. + n11 * n22 * n33
  4016. + n13 * n21 * n32
  4017. - n12 * n21 * n33
  4018. + n12 * n23 * n31
  4019. )
  4020. );
  4021. }
  4022. transpose() {
  4023. const te = this.elements;
  4024. let tmp;
  4025. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4026. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4027. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4028. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4029. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4030. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4031. return this;
  4032. }
  4033. setPosition( x, y, z ) {
  4034. const te = this.elements;
  4035. if ( x.isVector3 ) {
  4036. te[ 12 ] = x.x;
  4037. te[ 13 ] = x.y;
  4038. te[ 14 ] = x.z;
  4039. } else {
  4040. te[ 12 ] = x;
  4041. te[ 13 ] = y;
  4042. te[ 14 ] = z;
  4043. }
  4044. return this;
  4045. }
  4046. invert() {
  4047. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4048. const te = this.elements,
  4049. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4050. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4051. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4052. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4053. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4054. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4055. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4056. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4057. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4058. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4059. const detInv = 1 / det;
  4060. te[ 0 ] = t11 * detInv;
  4061. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4062. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4063. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4064. te[ 4 ] = t12 * detInv;
  4065. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4066. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4067. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4068. te[ 8 ] = t13 * detInv;
  4069. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4070. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4071. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4072. te[ 12 ] = t14 * detInv;
  4073. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4074. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4075. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4076. return this;
  4077. }
  4078. scale( v ) {
  4079. const te = this.elements;
  4080. const x = v.x, y = v.y, z = v.z;
  4081. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4082. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4083. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4084. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4085. return this;
  4086. }
  4087. getMaxScaleOnAxis() {
  4088. const te = this.elements;
  4089. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4090. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4091. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4092. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4093. }
  4094. makeTranslation( x, y, z ) {
  4095. this.set(
  4096. 1, 0, 0, x,
  4097. 0, 1, 0, y,
  4098. 0, 0, 1, z,
  4099. 0, 0, 0, 1
  4100. );
  4101. return this;
  4102. }
  4103. makeRotationX( theta ) {
  4104. const c = Math.cos( theta ), s = Math.sin( theta );
  4105. this.set(
  4106. 1, 0, 0, 0,
  4107. 0, c, - s, 0,
  4108. 0, s, c, 0,
  4109. 0, 0, 0, 1
  4110. );
  4111. return this;
  4112. }
  4113. makeRotationY( theta ) {
  4114. const c = Math.cos( theta ), s = Math.sin( theta );
  4115. this.set(
  4116. c, 0, s, 0,
  4117. 0, 1, 0, 0,
  4118. - s, 0, c, 0,
  4119. 0, 0, 0, 1
  4120. );
  4121. return this;
  4122. }
  4123. makeRotationZ( theta ) {
  4124. const c = Math.cos( theta ), s = Math.sin( theta );
  4125. this.set(
  4126. c, - s, 0, 0,
  4127. s, c, 0, 0,
  4128. 0, 0, 1, 0,
  4129. 0, 0, 0, 1
  4130. );
  4131. return this;
  4132. }
  4133. makeRotationAxis( axis, angle ) {
  4134. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4135. const c = Math.cos( angle );
  4136. const s = Math.sin( angle );
  4137. const t = 1 - c;
  4138. const x = axis.x, y = axis.y, z = axis.z;
  4139. const tx = t * x, ty = t * y;
  4140. this.set(
  4141. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4142. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4143. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4144. 0, 0, 0, 1
  4145. );
  4146. return this;
  4147. }
  4148. makeScale( x, y, z ) {
  4149. this.set(
  4150. x, 0, 0, 0,
  4151. 0, y, 0, 0,
  4152. 0, 0, z, 0,
  4153. 0, 0, 0, 1
  4154. );
  4155. return this;
  4156. }
  4157. makeShear( xy, xz, yx, yz, zx, zy ) {
  4158. this.set(
  4159. 1, yx, zx, 0,
  4160. xy, 1, zy, 0,
  4161. xz, yz, 1, 0,
  4162. 0, 0, 0, 1
  4163. );
  4164. return this;
  4165. }
  4166. compose( position, quaternion, scale ) {
  4167. const te = this.elements;
  4168. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4169. const x2 = x + x, y2 = y + y, z2 = z + z;
  4170. const xx = x * x2, xy = x * y2, xz = x * z2;
  4171. const yy = y * y2, yz = y * z2, zz = z * z2;
  4172. const wx = w * x2, wy = w * y2, wz = w * z2;
  4173. const sx = scale.x, sy = scale.y, sz = scale.z;
  4174. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4175. te[ 1 ] = ( xy + wz ) * sx;
  4176. te[ 2 ] = ( xz - wy ) * sx;
  4177. te[ 3 ] = 0;
  4178. te[ 4 ] = ( xy - wz ) * sy;
  4179. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4180. te[ 6 ] = ( yz + wx ) * sy;
  4181. te[ 7 ] = 0;
  4182. te[ 8 ] = ( xz + wy ) * sz;
  4183. te[ 9 ] = ( yz - wx ) * sz;
  4184. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4185. te[ 11 ] = 0;
  4186. te[ 12 ] = position.x;
  4187. te[ 13 ] = position.y;
  4188. te[ 14 ] = position.z;
  4189. te[ 15 ] = 1;
  4190. return this;
  4191. }
  4192. decompose( position, quaternion, scale ) {
  4193. const te = this.elements;
  4194. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4195. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4196. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4197. // if determine is negative, we need to invert one scale
  4198. const det = this.determinant();
  4199. if ( det < 0 ) sx = - sx;
  4200. position.x = te[ 12 ];
  4201. position.y = te[ 13 ];
  4202. position.z = te[ 14 ];
  4203. // scale the rotation part
  4204. _m1$2.copy( this );
  4205. const invSX = 1 / sx;
  4206. const invSY = 1 / sy;
  4207. const invSZ = 1 / sz;
  4208. _m1$2.elements[ 0 ] *= invSX;
  4209. _m1$2.elements[ 1 ] *= invSX;
  4210. _m1$2.elements[ 2 ] *= invSX;
  4211. _m1$2.elements[ 4 ] *= invSY;
  4212. _m1$2.elements[ 5 ] *= invSY;
  4213. _m1$2.elements[ 6 ] *= invSY;
  4214. _m1$2.elements[ 8 ] *= invSZ;
  4215. _m1$2.elements[ 9 ] *= invSZ;
  4216. _m1$2.elements[ 10 ] *= invSZ;
  4217. quaternion.setFromRotationMatrix( _m1$2 );
  4218. scale.x = sx;
  4219. scale.y = sy;
  4220. scale.z = sz;
  4221. return this;
  4222. }
  4223. makePerspective( left, right, top, bottom, near, far ) {
  4224. const te = this.elements;
  4225. const x = 2 * near / ( right - left );
  4226. const y = 2 * near / ( top - bottom );
  4227. const a = ( right + left ) / ( right - left );
  4228. const b = ( top + bottom ) / ( top - bottom );
  4229. const c = - ( far + near ) / ( far - near );
  4230. const d = - 2 * far * near / ( far - near );
  4231. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4232. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4233. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4234. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4235. return this;
  4236. }
  4237. makeOrthographic( left, right, top, bottom, near, far ) {
  4238. const te = this.elements;
  4239. const w = 1.0 / ( right - left );
  4240. const h = 1.0 / ( top - bottom );
  4241. const p = 1.0 / ( far - near );
  4242. const x = ( right + left ) * w;
  4243. const y = ( top + bottom ) * h;
  4244. const z = ( far + near ) * p;
  4245. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4246. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4247. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4248. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4249. return this;
  4250. }
  4251. equals( matrix ) {
  4252. const te = this.elements;
  4253. const me = matrix.elements;
  4254. for ( let i = 0; i < 16; i ++ ) {
  4255. if ( te[ i ] !== me[ i ] ) return false;
  4256. }
  4257. return true;
  4258. }
  4259. fromArray( array, offset = 0 ) {
  4260. for ( let i = 0; i < 16; i ++ ) {
  4261. this.elements[ i ] = array[ i + offset ];
  4262. }
  4263. return this;
  4264. }
  4265. toArray( array = [], offset = 0 ) {
  4266. const te = this.elements;
  4267. array[ offset ] = te[ 0 ];
  4268. array[ offset + 1 ] = te[ 1 ];
  4269. array[ offset + 2 ] = te[ 2 ];
  4270. array[ offset + 3 ] = te[ 3 ];
  4271. array[ offset + 4 ] = te[ 4 ];
  4272. array[ offset + 5 ] = te[ 5 ];
  4273. array[ offset + 6 ] = te[ 6 ];
  4274. array[ offset + 7 ] = te[ 7 ];
  4275. array[ offset + 8 ] = te[ 8 ];
  4276. array[ offset + 9 ] = te[ 9 ];
  4277. array[ offset + 10 ] = te[ 10 ];
  4278. array[ offset + 11 ] = te[ 11 ];
  4279. array[ offset + 12 ] = te[ 12 ];
  4280. array[ offset + 13 ] = te[ 13 ];
  4281. array[ offset + 14 ] = te[ 14 ];
  4282. array[ offset + 15 ] = te[ 15 ];
  4283. return array;
  4284. }
  4285. }
  4286. const _v1$5 = /*@__PURE__*/ new Vector3();
  4287. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4288. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4289. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4290. const _x = /*@__PURE__*/ new Vector3();
  4291. const _y = /*@__PURE__*/ new Vector3();
  4292. const _z = /*@__PURE__*/ new Vector3();
  4293. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4294. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4295. class Euler {
  4296. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4297. this.isEuler = true;
  4298. this._x = x;
  4299. this._y = y;
  4300. this._z = z;
  4301. this._order = order;
  4302. }
  4303. get x() {
  4304. return this._x;
  4305. }
  4306. set x( value ) {
  4307. this._x = value;
  4308. this._onChangeCallback();
  4309. }
  4310. get y() {
  4311. return this._y;
  4312. }
  4313. set y( value ) {
  4314. this._y = value;
  4315. this._onChangeCallback();
  4316. }
  4317. get z() {
  4318. return this._z;
  4319. }
  4320. set z( value ) {
  4321. this._z = value;
  4322. this._onChangeCallback();
  4323. }
  4324. get order() {
  4325. return this._order;
  4326. }
  4327. set order( value ) {
  4328. this._order = value;
  4329. this._onChangeCallback();
  4330. }
  4331. set( x, y, z, order = this._order ) {
  4332. this._x = x;
  4333. this._y = y;
  4334. this._z = z;
  4335. this._order = order;
  4336. this._onChangeCallback();
  4337. return this;
  4338. }
  4339. clone() {
  4340. return new this.constructor( this._x, this._y, this._z, this._order );
  4341. }
  4342. copy( euler ) {
  4343. this._x = euler._x;
  4344. this._y = euler._y;
  4345. this._z = euler._z;
  4346. this._order = euler._order;
  4347. this._onChangeCallback();
  4348. return this;
  4349. }
  4350. setFromRotationMatrix( m, order = this._order, update = true ) {
  4351. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4352. const te = m.elements;
  4353. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4354. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4355. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4356. switch ( order ) {
  4357. case 'XYZ':
  4358. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4359. if ( Math.abs( m13 ) < 0.9999999 ) {
  4360. this._x = Math.atan2( - m23, m33 );
  4361. this._z = Math.atan2( - m12, m11 );
  4362. } else {
  4363. this._x = Math.atan2( m32, m22 );
  4364. this._z = 0;
  4365. }
  4366. break;
  4367. case 'YXZ':
  4368. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4369. if ( Math.abs( m23 ) < 0.9999999 ) {
  4370. this._y = Math.atan2( m13, m33 );
  4371. this._z = Math.atan2( m21, m22 );
  4372. } else {
  4373. this._y = Math.atan2( - m31, m11 );
  4374. this._z = 0;
  4375. }
  4376. break;
  4377. case 'ZXY':
  4378. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4379. if ( Math.abs( m32 ) < 0.9999999 ) {
  4380. this._y = Math.atan2( - m31, m33 );
  4381. this._z = Math.atan2( - m12, m22 );
  4382. } else {
  4383. this._y = 0;
  4384. this._z = Math.atan2( m21, m11 );
  4385. }
  4386. break;
  4387. case 'ZYX':
  4388. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4389. if ( Math.abs( m31 ) < 0.9999999 ) {
  4390. this._x = Math.atan2( m32, m33 );
  4391. this._z = Math.atan2( m21, m11 );
  4392. } else {
  4393. this._x = 0;
  4394. this._z = Math.atan2( - m12, m22 );
  4395. }
  4396. break;
  4397. case 'YZX':
  4398. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4399. if ( Math.abs( m21 ) < 0.9999999 ) {
  4400. this._x = Math.atan2( - m23, m22 );
  4401. this._y = Math.atan2( - m31, m11 );
  4402. } else {
  4403. this._x = 0;
  4404. this._y = Math.atan2( m13, m33 );
  4405. }
  4406. break;
  4407. case 'XZY':
  4408. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4409. if ( Math.abs( m12 ) < 0.9999999 ) {
  4410. this._x = Math.atan2( m32, m22 );
  4411. this._y = Math.atan2( m13, m11 );
  4412. } else {
  4413. this._x = Math.atan2( - m23, m33 );
  4414. this._y = 0;
  4415. }
  4416. break;
  4417. default:
  4418. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4419. }
  4420. this._order = order;
  4421. if ( update === true ) this._onChangeCallback();
  4422. return this;
  4423. }
  4424. setFromQuaternion( q, order, update ) {
  4425. _matrix$1.makeRotationFromQuaternion( q );
  4426. return this.setFromRotationMatrix( _matrix$1, order, update );
  4427. }
  4428. setFromVector3( v, order = this._order ) {
  4429. return this.set( v.x, v.y, v.z, order );
  4430. }
  4431. reorder( newOrder ) {
  4432. // WARNING: this discards revolution information -bhouston
  4433. _quaternion$3.setFromEuler( this );
  4434. return this.setFromQuaternion( _quaternion$3, newOrder );
  4435. }
  4436. equals( euler ) {
  4437. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4438. }
  4439. fromArray( array ) {
  4440. this._x = array[ 0 ];
  4441. this._y = array[ 1 ];
  4442. this._z = array[ 2 ];
  4443. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4444. this._onChangeCallback();
  4445. return this;
  4446. }
  4447. toArray( array = [], offset = 0 ) {
  4448. array[ offset ] = this._x;
  4449. array[ offset + 1 ] = this._y;
  4450. array[ offset + 2 ] = this._z;
  4451. array[ offset + 3 ] = this._order;
  4452. return array;
  4453. }
  4454. _onChange( callback ) {
  4455. this._onChangeCallback = callback;
  4456. return this;
  4457. }
  4458. _onChangeCallback() {}
  4459. *[ Symbol.iterator ]() {
  4460. yield this._x;
  4461. yield this._y;
  4462. yield this._z;
  4463. yield this._order;
  4464. }
  4465. }
  4466. Euler.DEFAULT_ORDER = 'XYZ';
  4467. class Layers {
  4468. constructor() {
  4469. this.mask = 1 | 0;
  4470. }
  4471. set( channel ) {
  4472. this.mask = ( 1 << channel | 0 ) >>> 0;
  4473. }
  4474. enable( channel ) {
  4475. this.mask |= 1 << channel | 0;
  4476. }
  4477. enableAll() {
  4478. this.mask = 0xffffffff | 0;
  4479. }
  4480. toggle( channel ) {
  4481. this.mask ^= 1 << channel | 0;
  4482. }
  4483. disable( channel ) {
  4484. this.mask &= ~ ( 1 << channel | 0 );
  4485. }
  4486. disableAll() {
  4487. this.mask = 0;
  4488. }
  4489. test( layers ) {
  4490. return ( this.mask & layers.mask ) !== 0;
  4491. }
  4492. isEnabled( channel ) {
  4493. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4494. }
  4495. }
  4496. let _object3DId = 0;
  4497. const _v1$4 = /*@__PURE__*/ new Vector3();
  4498. const _q1 = /*@__PURE__*/ new Quaternion();
  4499. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4500. const _target = /*@__PURE__*/ new Vector3();
  4501. const _position$3 = /*@__PURE__*/ new Vector3();
  4502. const _scale$2 = /*@__PURE__*/ new Vector3();
  4503. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4504. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4505. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4506. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4507. const _addedEvent = { type: 'added' };
  4508. const _removedEvent = { type: 'removed' };
  4509. class Object3D extends EventDispatcher {
  4510. constructor() {
  4511. super();
  4512. this.isObject3D = true;
  4513. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4514. this.uuid = generateUUID();
  4515. this.name = '';
  4516. this.type = 'Object3D';
  4517. this.parent = null;
  4518. this.children = [];
  4519. this.up = Object3D.DEFAULT_UP.clone();
  4520. const position = new Vector3();
  4521. const rotation = new Euler();
  4522. const quaternion = new Quaternion();
  4523. const scale = new Vector3( 1, 1, 1 );
  4524. function onRotationChange() {
  4525. quaternion.setFromEuler( rotation, false );
  4526. }
  4527. function onQuaternionChange() {
  4528. rotation.setFromQuaternion( quaternion, undefined, false );
  4529. }
  4530. rotation._onChange( onRotationChange );
  4531. quaternion._onChange( onQuaternionChange );
  4532. Object.defineProperties( this, {
  4533. position: {
  4534. configurable: true,
  4535. enumerable: true,
  4536. value: position
  4537. },
  4538. rotation: {
  4539. configurable: true,
  4540. enumerable: true,
  4541. value: rotation
  4542. },
  4543. quaternion: {
  4544. configurable: true,
  4545. enumerable: true,
  4546. value: quaternion
  4547. },
  4548. scale: {
  4549. configurable: true,
  4550. enumerable: true,
  4551. value: scale
  4552. },
  4553. modelViewMatrix: {
  4554. value: new Matrix4()
  4555. },
  4556. normalMatrix: {
  4557. value: new Matrix3()
  4558. }
  4559. } );
  4560. this.matrix = new Matrix4();
  4561. this.matrixWorld = new Matrix4();
  4562. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4563. this.matrixWorldNeedsUpdate = false;
  4564. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4565. this.layers = new Layers();
  4566. this.visible = true;
  4567. this.castShadow = false;
  4568. this.receiveShadow = false;
  4569. this.frustumCulled = true;
  4570. this.renderOrder = 0;
  4571. this.animations = [];
  4572. this.userData = {};
  4573. }
  4574. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4575. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4576. applyMatrix4( matrix ) {
  4577. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4578. this.matrix.premultiply( matrix );
  4579. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4580. }
  4581. applyQuaternion( q ) {
  4582. this.quaternion.premultiply( q );
  4583. return this;
  4584. }
  4585. setRotationFromAxisAngle( axis, angle ) {
  4586. // assumes axis is normalized
  4587. this.quaternion.setFromAxisAngle( axis, angle );
  4588. }
  4589. setRotationFromEuler( euler ) {
  4590. this.quaternion.setFromEuler( euler, true );
  4591. }
  4592. setRotationFromMatrix( m ) {
  4593. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4594. this.quaternion.setFromRotationMatrix( m );
  4595. }
  4596. setRotationFromQuaternion( q ) {
  4597. // assumes q is normalized
  4598. this.quaternion.copy( q );
  4599. }
  4600. rotateOnAxis( axis, angle ) {
  4601. // rotate object on axis in object space
  4602. // axis is assumed to be normalized
  4603. _q1.setFromAxisAngle( axis, angle );
  4604. this.quaternion.multiply( _q1 );
  4605. return this;
  4606. }
  4607. rotateOnWorldAxis( axis, angle ) {
  4608. // rotate object on axis in world space
  4609. // axis is assumed to be normalized
  4610. // method assumes no rotated parent
  4611. _q1.setFromAxisAngle( axis, angle );
  4612. this.quaternion.premultiply( _q1 );
  4613. return this;
  4614. }
  4615. rotateX( angle ) {
  4616. return this.rotateOnAxis( _xAxis, angle );
  4617. }
  4618. rotateY( angle ) {
  4619. return this.rotateOnAxis( _yAxis, angle );
  4620. }
  4621. rotateZ( angle ) {
  4622. return this.rotateOnAxis( _zAxis, angle );
  4623. }
  4624. translateOnAxis( axis, distance ) {
  4625. // translate object by distance along axis in object space
  4626. // axis is assumed to be normalized
  4627. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4628. this.position.add( _v1$4.multiplyScalar( distance ) );
  4629. return this;
  4630. }
  4631. translateX( distance ) {
  4632. return this.translateOnAxis( _xAxis, distance );
  4633. }
  4634. translateY( distance ) {
  4635. return this.translateOnAxis( _yAxis, distance );
  4636. }
  4637. translateZ( distance ) {
  4638. return this.translateOnAxis( _zAxis, distance );
  4639. }
  4640. localToWorld( vector ) {
  4641. this.updateWorldMatrix( true, false );
  4642. return vector.applyMatrix4( this.matrixWorld );
  4643. }
  4644. worldToLocal( vector ) {
  4645. this.updateWorldMatrix( true, false );
  4646. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4647. }
  4648. lookAt( x, y, z ) {
  4649. // This method does not support objects having non-uniformly-scaled parent(s)
  4650. if ( x.isVector3 ) {
  4651. _target.copy( x );
  4652. } else {
  4653. _target.set( x, y, z );
  4654. }
  4655. const parent = this.parent;
  4656. this.updateWorldMatrix( true, false );
  4657. _position$3.setFromMatrixPosition( this.matrixWorld );
  4658. if ( this.isCamera || this.isLight ) {
  4659. _m1$1.lookAt( _position$3, _target, this.up );
  4660. } else {
  4661. _m1$1.lookAt( _target, _position$3, this.up );
  4662. }
  4663. this.quaternion.setFromRotationMatrix( _m1$1 );
  4664. if ( parent ) {
  4665. _m1$1.extractRotation( parent.matrixWorld );
  4666. _q1.setFromRotationMatrix( _m1$1 );
  4667. this.quaternion.premultiply( _q1.invert() );
  4668. }
  4669. }
  4670. add( object ) {
  4671. if ( arguments.length > 1 ) {
  4672. for ( let i = 0; i < arguments.length; i ++ ) {
  4673. this.add( arguments[ i ] );
  4674. }
  4675. return this;
  4676. }
  4677. if ( object === this ) {
  4678. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4679. return this;
  4680. }
  4681. if ( object && object.isObject3D ) {
  4682. if ( object.parent !== null ) {
  4683. object.parent.remove( object );
  4684. }
  4685. object.parent = this;
  4686. this.children.push( object );
  4687. object.dispatchEvent( _addedEvent );
  4688. } else {
  4689. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4690. }
  4691. return this;
  4692. }
  4693. remove( object ) {
  4694. if ( arguments.length > 1 ) {
  4695. for ( let i = 0; i < arguments.length; i ++ ) {
  4696. this.remove( arguments[ i ] );
  4697. }
  4698. return this;
  4699. }
  4700. const index = this.children.indexOf( object );
  4701. if ( index !== - 1 ) {
  4702. object.parent = null;
  4703. this.children.splice( index, 1 );
  4704. object.dispatchEvent( _removedEvent );
  4705. }
  4706. return this;
  4707. }
  4708. removeFromParent() {
  4709. const parent = this.parent;
  4710. if ( parent !== null ) {
  4711. parent.remove( this );
  4712. }
  4713. return this;
  4714. }
  4715. clear() {
  4716. for ( let i = 0; i < this.children.length; i ++ ) {
  4717. const object = this.children[ i ];
  4718. object.parent = null;
  4719. object.dispatchEvent( _removedEvent );
  4720. }
  4721. this.children.length = 0;
  4722. return this;
  4723. }
  4724. attach( object ) {
  4725. // adds object as a child of this, while maintaining the object's world transform
  4726. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4727. this.updateWorldMatrix( true, false );
  4728. _m1$1.copy( this.matrixWorld ).invert();
  4729. if ( object.parent !== null ) {
  4730. object.parent.updateWorldMatrix( true, false );
  4731. _m1$1.multiply( object.parent.matrixWorld );
  4732. }
  4733. object.applyMatrix4( _m1$1 );
  4734. this.add( object );
  4735. object.updateWorldMatrix( false, true );
  4736. return this;
  4737. }
  4738. getObjectById( id ) {
  4739. return this.getObjectByProperty( 'id', id );
  4740. }
  4741. getObjectByName( name ) {
  4742. return this.getObjectByProperty( 'name', name );
  4743. }
  4744. getObjectByProperty( name, value ) {
  4745. if ( this[ name ] === value ) return this;
  4746. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4747. const child = this.children[ i ];
  4748. const object = child.getObjectByProperty( name, value );
  4749. if ( object !== undefined ) {
  4750. return object;
  4751. }
  4752. }
  4753. return undefined;
  4754. }
  4755. getObjectsByProperty( name, value ) {
  4756. let result = [];
  4757. if ( this[ name ] === value ) result.push( this );
  4758. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4759. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4760. if ( childResult.length > 0 ) {
  4761. result = result.concat( childResult );
  4762. }
  4763. }
  4764. return result;
  4765. }
  4766. getWorldPosition( target ) {
  4767. this.updateWorldMatrix( true, false );
  4768. return target.setFromMatrixPosition( this.matrixWorld );
  4769. }
  4770. getWorldQuaternion( target ) {
  4771. this.updateWorldMatrix( true, false );
  4772. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4773. return target;
  4774. }
  4775. getWorldScale( target ) {
  4776. this.updateWorldMatrix( true, false );
  4777. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4778. return target;
  4779. }
  4780. getWorldDirection( target ) {
  4781. this.updateWorldMatrix( true, false );
  4782. const e = this.matrixWorld.elements;
  4783. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4784. }
  4785. raycast( /* raycaster, intersects */ ) {}
  4786. traverse( callback ) {
  4787. callback( this );
  4788. const children = this.children;
  4789. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4790. children[ i ].traverse( callback );
  4791. }
  4792. }
  4793. traverseVisible( callback ) {
  4794. if ( this.visible === false ) return;
  4795. callback( this );
  4796. const children = this.children;
  4797. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4798. children[ i ].traverseVisible( callback );
  4799. }
  4800. }
  4801. traverseAncestors( callback ) {
  4802. const parent = this.parent;
  4803. if ( parent !== null ) {
  4804. callback( parent );
  4805. parent.traverseAncestors( callback );
  4806. }
  4807. }
  4808. updateMatrix() {
  4809. this.matrix.compose( this.position, this.quaternion, this.scale );
  4810. this.matrixWorldNeedsUpdate = true;
  4811. }
  4812. updateMatrixWorld( force ) {
  4813. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4814. if ( this.matrixWorldNeedsUpdate || force ) {
  4815. if ( this.parent === null ) {
  4816. this.matrixWorld.copy( this.matrix );
  4817. } else {
  4818. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4819. }
  4820. this.matrixWorldNeedsUpdate = false;
  4821. force = true;
  4822. }
  4823. // update children
  4824. const children = this.children;
  4825. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4826. const child = children[ i ];
  4827. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4828. child.updateMatrixWorld( force );
  4829. }
  4830. }
  4831. }
  4832. updateWorldMatrix( updateParents, updateChildren ) {
  4833. const parent = this.parent;
  4834. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4835. parent.updateWorldMatrix( true, false );
  4836. }
  4837. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4838. if ( this.parent === null ) {
  4839. this.matrixWorld.copy( this.matrix );
  4840. } else {
  4841. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4842. }
  4843. // update children
  4844. if ( updateChildren === true ) {
  4845. const children = this.children;
  4846. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4847. const child = children[ i ];
  4848. if ( child.matrixWorldAutoUpdate === true ) {
  4849. child.updateWorldMatrix( false, true );
  4850. }
  4851. }
  4852. }
  4853. }
  4854. toJSON( meta ) {
  4855. // meta is a string when called from JSON.stringify
  4856. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4857. const output = {};
  4858. // meta is a hash used to collect geometries, materials.
  4859. // not providing it implies that this is the root object
  4860. // being serialized.
  4861. if ( isRootObject ) {
  4862. // initialize meta obj
  4863. meta = {
  4864. geometries: {},
  4865. materials: {},
  4866. textures: {},
  4867. images: {},
  4868. shapes: {},
  4869. skeletons: {},
  4870. animations: {},
  4871. nodes: {}
  4872. };
  4873. output.metadata = {
  4874. version: 4.5,
  4875. type: 'Object',
  4876. generator: 'Object3D.toJSON'
  4877. };
  4878. }
  4879. // standard Object3D serialization
  4880. const object = {};
  4881. object.uuid = this.uuid;
  4882. object.type = this.type;
  4883. if ( this.name !== '' ) object.name = this.name;
  4884. if ( this.castShadow === true ) object.castShadow = true;
  4885. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4886. if ( this.visible === false ) object.visible = false;
  4887. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4888. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4889. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4890. object.layers = this.layers.mask;
  4891. object.matrix = this.matrix.toArray();
  4892. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4893. // object specific properties
  4894. if ( this.isInstancedMesh ) {
  4895. object.type = 'InstancedMesh';
  4896. object.count = this.count;
  4897. object.instanceMatrix = this.instanceMatrix.toJSON();
  4898. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4899. }
  4900. //
  4901. function serialize( library, element ) {
  4902. if ( library[ element.uuid ] === undefined ) {
  4903. library[ element.uuid ] = element.toJSON( meta );
  4904. }
  4905. return element.uuid;
  4906. }
  4907. if ( this.isScene ) {
  4908. if ( this.background ) {
  4909. if ( this.background.isColor ) {
  4910. object.background = this.background.toJSON();
  4911. } else if ( this.background.isTexture ) {
  4912. object.background = this.background.toJSON( meta ).uuid;
  4913. }
  4914. }
  4915. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4916. object.environment = this.environment.toJSON( meta ).uuid;
  4917. }
  4918. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4919. object.geometry = serialize( meta.geometries, this.geometry );
  4920. const parameters = this.geometry.parameters;
  4921. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4922. const shapes = parameters.shapes;
  4923. if ( Array.isArray( shapes ) ) {
  4924. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4925. const shape = shapes[ i ];
  4926. serialize( meta.shapes, shape );
  4927. }
  4928. } else {
  4929. serialize( meta.shapes, shapes );
  4930. }
  4931. }
  4932. }
  4933. if ( this.isSkinnedMesh ) {
  4934. object.bindMode = this.bindMode;
  4935. object.bindMatrix = this.bindMatrix.toArray();
  4936. if ( this.skeleton !== undefined ) {
  4937. serialize( meta.skeletons, this.skeleton );
  4938. object.skeleton = this.skeleton.uuid;
  4939. }
  4940. }
  4941. if ( this.material !== undefined ) {
  4942. if ( Array.isArray( this.material ) ) {
  4943. const uuids = [];
  4944. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4945. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4946. }
  4947. object.material = uuids;
  4948. } else {
  4949. object.material = serialize( meta.materials, this.material );
  4950. }
  4951. }
  4952. //
  4953. if ( this.children.length > 0 ) {
  4954. object.children = [];
  4955. for ( let i = 0; i < this.children.length; i ++ ) {
  4956. object.children.push( this.children[ i ].toJSON( meta ).object );
  4957. }
  4958. }
  4959. //
  4960. if ( this.animations.length > 0 ) {
  4961. object.animations = [];
  4962. for ( let i = 0; i < this.animations.length; i ++ ) {
  4963. const animation = this.animations[ i ];
  4964. object.animations.push( serialize( meta.animations, animation ) );
  4965. }
  4966. }
  4967. if ( isRootObject ) {
  4968. const geometries = extractFromCache( meta.geometries );
  4969. const materials = extractFromCache( meta.materials );
  4970. const textures = extractFromCache( meta.textures );
  4971. const images = extractFromCache( meta.images );
  4972. const shapes = extractFromCache( meta.shapes );
  4973. const skeletons = extractFromCache( meta.skeletons );
  4974. const animations = extractFromCache( meta.animations );
  4975. const nodes = extractFromCache( meta.nodes );
  4976. if ( geometries.length > 0 ) output.geometries = geometries;
  4977. if ( materials.length > 0 ) output.materials = materials;
  4978. if ( textures.length > 0 ) output.textures = textures;
  4979. if ( images.length > 0 ) output.images = images;
  4980. if ( shapes.length > 0 ) output.shapes = shapes;
  4981. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4982. if ( animations.length > 0 ) output.animations = animations;
  4983. if ( nodes.length > 0 ) output.nodes = nodes;
  4984. }
  4985. output.object = object;
  4986. return output;
  4987. // extract data from the cache hash
  4988. // remove metadata on each item
  4989. // and return as array
  4990. function extractFromCache( cache ) {
  4991. const values = [];
  4992. for ( const key in cache ) {
  4993. const data = cache[ key ];
  4994. delete data.metadata;
  4995. values.push( data );
  4996. }
  4997. return values;
  4998. }
  4999. }
  5000. clone( recursive ) {
  5001. return new this.constructor().copy( this, recursive );
  5002. }
  5003. copy( source, recursive = true ) {
  5004. this.name = source.name;
  5005. this.up.copy( source.up );
  5006. this.position.copy( source.position );
  5007. this.rotation.order = source.rotation.order;
  5008. this.quaternion.copy( source.quaternion );
  5009. this.scale.copy( source.scale );
  5010. this.matrix.copy( source.matrix );
  5011. this.matrixWorld.copy( source.matrixWorld );
  5012. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5013. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5014. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5015. this.layers.mask = source.layers.mask;
  5016. this.visible = source.visible;
  5017. this.castShadow = source.castShadow;
  5018. this.receiveShadow = source.receiveShadow;
  5019. this.frustumCulled = source.frustumCulled;
  5020. this.renderOrder = source.renderOrder;
  5021. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5022. if ( recursive === true ) {
  5023. for ( let i = 0; i < source.children.length; i ++ ) {
  5024. const child = source.children[ i ];
  5025. this.add( child.clone() );
  5026. }
  5027. }
  5028. return this;
  5029. }
  5030. }
  5031. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5032. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  5033. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  5034. const _v0$1 = /*@__PURE__*/ new Vector3();
  5035. const _v1$3 = /*@__PURE__*/ new Vector3();
  5036. const _v2$2 = /*@__PURE__*/ new Vector3();
  5037. const _v3$1 = /*@__PURE__*/ new Vector3();
  5038. const _vab = /*@__PURE__*/ new Vector3();
  5039. const _vac = /*@__PURE__*/ new Vector3();
  5040. const _vbc = /*@__PURE__*/ new Vector3();
  5041. const _vap = /*@__PURE__*/ new Vector3();
  5042. const _vbp = /*@__PURE__*/ new Vector3();
  5043. const _vcp = /*@__PURE__*/ new Vector3();
  5044. class Triangle {
  5045. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5046. this.a = a;
  5047. this.b = b;
  5048. this.c = c;
  5049. }
  5050. static getNormal( a, b, c, target ) {
  5051. target.subVectors( c, b );
  5052. _v0$1.subVectors( a, b );
  5053. target.cross( _v0$1 );
  5054. const targetLengthSq = target.lengthSq();
  5055. if ( targetLengthSq > 0 ) {
  5056. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5057. }
  5058. return target.set( 0, 0, 0 );
  5059. }
  5060. // static/instance method to calculate barycentric coordinates
  5061. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5062. static getBarycoord( point, a, b, c, target ) {
  5063. _v0$1.subVectors( c, a );
  5064. _v1$3.subVectors( b, a );
  5065. _v2$2.subVectors( point, a );
  5066. const dot00 = _v0$1.dot( _v0$1 );
  5067. const dot01 = _v0$1.dot( _v1$3 );
  5068. const dot02 = _v0$1.dot( _v2$2 );
  5069. const dot11 = _v1$3.dot( _v1$3 );
  5070. const dot12 = _v1$3.dot( _v2$2 );
  5071. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5072. // collinear or singular triangle
  5073. if ( denom === 0 ) {
  5074. // arbitrary location outside of triangle?
  5075. // not sure if this is the best idea, maybe should be returning undefined
  5076. return target.set( - 2, - 1, - 1 );
  5077. }
  5078. const invDenom = 1 / denom;
  5079. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5080. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5081. // barycentric coordinates must always sum to 1
  5082. return target.set( 1 - u - v, v, u );
  5083. }
  5084. static containsPoint( point, a, b, c ) {
  5085. this.getBarycoord( point, a, b, c, _v3$1 );
  5086. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5087. }
  5088. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5089. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5090. target.set( 0, 0 );
  5091. target.addScaledVector( uv1, _v3$1.x );
  5092. target.addScaledVector( uv2, _v3$1.y );
  5093. target.addScaledVector( uv3, _v3$1.z );
  5094. return target;
  5095. }
  5096. static isFrontFacing( a, b, c, direction ) {
  5097. _v0$1.subVectors( c, b );
  5098. _v1$3.subVectors( a, b );
  5099. // strictly front facing
  5100. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5101. }
  5102. set( a, b, c ) {
  5103. this.a.copy( a );
  5104. this.b.copy( b );
  5105. this.c.copy( c );
  5106. return this;
  5107. }
  5108. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5109. this.a.copy( points[ i0 ] );
  5110. this.b.copy( points[ i1 ] );
  5111. this.c.copy( points[ i2 ] );
  5112. return this;
  5113. }
  5114. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5115. this.a.fromBufferAttribute( attribute, i0 );
  5116. this.b.fromBufferAttribute( attribute, i1 );
  5117. this.c.fromBufferAttribute( attribute, i2 );
  5118. return this;
  5119. }
  5120. clone() {
  5121. return new this.constructor().copy( this );
  5122. }
  5123. copy( triangle ) {
  5124. this.a.copy( triangle.a );
  5125. this.b.copy( triangle.b );
  5126. this.c.copy( triangle.c );
  5127. return this;
  5128. }
  5129. getArea() {
  5130. _v0$1.subVectors( this.c, this.b );
  5131. _v1$3.subVectors( this.a, this.b );
  5132. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5133. }
  5134. getMidpoint( target ) {
  5135. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5136. }
  5137. getNormal( target ) {
  5138. return Triangle.getNormal( this.a, this.b, this.c, target );
  5139. }
  5140. getPlane( target ) {
  5141. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5142. }
  5143. getBarycoord( point, target ) {
  5144. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5145. }
  5146. getUV( point, uv1, uv2, uv3, target ) {
  5147. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5148. }
  5149. containsPoint( point ) {
  5150. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5151. }
  5152. isFrontFacing( direction ) {
  5153. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5154. }
  5155. intersectsBox( box ) {
  5156. return box.intersectsTriangle( this );
  5157. }
  5158. closestPointToPoint( p, target ) {
  5159. const a = this.a, b = this.b, c = this.c;
  5160. let v, w;
  5161. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5162. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5163. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5164. // basically, we're distinguishing which of the voronoi regions of the triangle
  5165. // the point lies in with the minimum amount of redundant computation.
  5166. _vab.subVectors( b, a );
  5167. _vac.subVectors( c, a );
  5168. _vap.subVectors( p, a );
  5169. const d1 = _vab.dot( _vap );
  5170. const d2 = _vac.dot( _vap );
  5171. if ( d1 <= 0 && d2 <= 0 ) {
  5172. // vertex region of A; barycentric coords (1, 0, 0)
  5173. return target.copy( a );
  5174. }
  5175. _vbp.subVectors( p, b );
  5176. const d3 = _vab.dot( _vbp );
  5177. const d4 = _vac.dot( _vbp );
  5178. if ( d3 >= 0 && d4 <= d3 ) {
  5179. // vertex region of B; barycentric coords (0, 1, 0)
  5180. return target.copy( b );
  5181. }
  5182. const vc = d1 * d4 - d3 * d2;
  5183. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5184. v = d1 / ( d1 - d3 );
  5185. // edge region of AB; barycentric coords (1-v, v, 0)
  5186. return target.copy( a ).addScaledVector( _vab, v );
  5187. }
  5188. _vcp.subVectors( p, c );
  5189. const d5 = _vab.dot( _vcp );
  5190. const d6 = _vac.dot( _vcp );
  5191. if ( d6 >= 0 && d5 <= d6 ) {
  5192. // vertex region of C; barycentric coords (0, 0, 1)
  5193. return target.copy( c );
  5194. }
  5195. const vb = d5 * d2 - d1 * d6;
  5196. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5197. w = d2 / ( d2 - d6 );
  5198. // edge region of AC; barycentric coords (1-w, 0, w)
  5199. return target.copy( a ).addScaledVector( _vac, w );
  5200. }
  5201. const va = d3 * d6 - d5 * d4;
  5202. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5203. _vbc.subVectors( c, b );
  5204. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5205. // edge region of BC; barycentric coords (0, 1-w, w)
  5206. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5207. }
  5208. // face region
  5209. const denom = 1 / ( va + vb + vc );
  5210. // u = va * denom
  5211. v = vb * denom;
  5212. w = vc * denom;
  5213. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5214. }
  5215. equals( triangle ) {
  5216. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5217. }
  5218. }
  5219. let materialId = 0;
  5220. class Material extends EventDispatcher {
  5221. constructor() {
  5222. super();
  5223. this.isMaterial = true;
  5224. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5225. this.uuid = generateUUID();
  5226. this.name = '';
  5227. this.type = 'Material';
  5228. this.blending = NormalBlending;
  5229. this.side = FrontSide;
  5230. this.vertexColors = false;
  5231. this.opacity = 1;
  5232. this.transparent = false;
  5233. this.blendSrc = SrcAlphaFactor;
  5234. this.blendDst = OneMinusSrcAlphaFactor;
  5235. this.blendEquation = AddEquation;
  5236. this.blendSrcAlpha = null;
  5237. this.blendDstAlpha = null;
  5238. this.blendEquationAlpha = null;
  5239. this.depthFunc = LessEqualDepth;
  5240. this.depthTest = true;
  5241. this.depthWrite = true;
  5242. this.stencilWriteMask = 0xff;
  5243. this.stencilFunc = AlwaysStencilFunc;
  5244. this.stencilRef = 0;
  5245. this.stencilFuncMask = 0xff;
  5246. this.stencilFail = KeepStencilOp;
  5247. this.stencilZFail = KeepStencilOp;
  5248. this.stencilZPass = KeepStencilOp;
  5249. this.stencilWrite = false;
  5250. this.clippingPlanes = null;
  5251. this.clipIntersection = false;
  5252. this.clipShadows = false;
  5253. this.shadowSide = null;
  5254. this.colorWrite = true;
  5255. this.precision = null; // override the renderer's default precision for this material
  5256. this.polygonOffset = false;
  5257. this.polygonOffsetFactor = 0;
  5258. this.polygonOffsetUnits = 0;
  5259. this.dithering = false;
  5260. this.alphaToCoverage = false;
  5261. this.premultipliedAlpha = false;
  5262. this.forceSinglePass = false;
  5263. this.visible = true;
  5264. this.toneMapped = true;
  5265. this.userData = {};
  5266. this.version = 0;
  5267. this._alphaTest = 0;
  5268. }
  5269. get alphaTest() {
  5270. return this._alphaTest;
  5271. }
  5272. set alphaTest( value ) {
  5273. if ( this._alphaTest > 0 !== value > 0 ) {
  5274. this.version ++;
  5275. }
  5276. this._alphaTest = value;
  5277. }
  5278. onBuild( /* shaderobject, renderer */ ) {}
  5279. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5280. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5281. customProgramCacheKey() {
  5282. return this.onBeforeCompile.toString();
  5283. }
  5284. setValues( values ) {
  5285. if ( values === undefined ) return;
  5286. for ( const key in values ) {
  5287. const newValue = values[ key ];
  5288. if ( newValue === undefined ) {
  5289. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5290. continue;
  5291. }
  5292. const currentValue = this[ key ];
  5293. if ( currentValue === undefined ) {
  5294. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5295. continue;
  5296. }
  5297. if ( currentValue && currentValue.isColor ) {
  5298. currentValue.set( newValue );
  5299. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5300. currentValue.copy( newValue );
  5301. } else {
  5302. this[ key ] = newValue;
  5303. }
  5304. }
  5305. }
  5306. toJSON( meta ) {
  5307. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5308. if ( isRootObject ) {
  5309. meta = {
  5310. textures: {},
  5311. images: {}
  5312. };
  5313. }
  5314. const data = {
  5315. metadata: {
  5316. version: 4.5,
  5317. type: 'Material',
  5318. generator: 'Material.toJSON'
  5319. }
  5320. };
  5321. // standard Material serialization
  5322. data.uuid = this.uuid;
  5323. data.type = this.type;
  5324. if ( this.name !== '' ) data.name = this.name;
  5325. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5326. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5327. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5328. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5329. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5330. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5331. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5332. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5333. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5334. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5335. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5336. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5337. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5338. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5339. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5340. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5341. }
  5342. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5343. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5344. }
  5345. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5346. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5347. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5348. }
  5349. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5350. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5351. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5352. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5353. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5354. }
  5355. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5356. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5357. }
  5358. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5359. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5360. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5361. if ( this.lightMap && this.lightMap.isTexture ) {
  5362. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5363. data.lightMapIntensity = this.lightMapIntensity;
  5364. }
  5365. if ( this.aoMap && this.aoMap.isTexture ) {
  5366. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5367. data.aoMapIntensity = this.aoMapIntensity;
  5368. }
  5369. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5370. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5371. data.bumpScale = this.bumpScale;
  5372. }
  5373. if ( this.normalMap && this.normalMap.isTexture ) {
  5374. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5375. data.normalMapType = this.normalMapType;
  5376. data.normalScale = this.normalScale.toArray();
  5377. }
  5378. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5379. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5380. data.displacementScale = this.displacementScale;
  5381. data.displacementBias = this.displacementBias;
  5382. }
  5383. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5384. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5385. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5386. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5387. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5388. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5389. if ( this.envMap && this.envMap.isTexture ) {
  5390. data.envMap = this.envMap.toJSON( meta ).uuid;
  5391. if ( this.combine !== undefined ) data.combine = this.combine;
  5392. }
  5393. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5394. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5395. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5396. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5397. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5398. }
  5399. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5400. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5401. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5402. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5403. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5404. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5405. if ( this.size !== undefined ) data.size = this.size;
  5406. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5407. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5408. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5409. if ( this.side !== FrontSide ) data.side = this.side;
  5410. if ( this.vertexColors ) data.vertexColors = true;
  5411. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5412. if ( this.transparent === true ) data.transparent = this.transparent;
  5413. data.depthFunc = this.depthFunc;
  5414. data.depthTest = this.depthTest;
  5415. data.depthWrite = this.depthWrite;
  5416. data.colorWrite = this.colorWrite;
  5417. data.stencilWrite = this.stencilWrite;
  5418. data.stencilWriteMask = this.stencilWriteMask;
  5419. data.stencilFunc = this.stencilFunc;
  5420. data.stencilRef = this.stencilRef;
  5421. data.stencilFuncMask = this.stencilFuncMask;
  5422. data.stencilFail = this.stencilFail;
  5423. data.stencilZFail = this.stencilZFail;
  5424. data.stencilZPass = this.stencilZPass;
  5425. // rotation (SpriteMaterial)
  5426. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5427. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5428. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5429. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5430. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5431. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5432. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5433. if ( this.scale !== undefined ) data.scale = this.scale;
  5434. if ( this.dithering === true ) data.dithering = true;
  5435. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5436. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5437. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5438. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5439. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5440. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5441. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5442. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5443. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5444. if ( this.visible === false ) data.visible = false;
  5445. if ( this.toneMapped === false ) data.toneMapped = false;
  5446. if ( this.fog === false ) data.fog = false;
  5447. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5448. // TODO: Copied from Object3D.toJSON
  5449. function extractFromCache( cache ) {
  5450. const values = [];
  5451. for ( const key in cache ) {
  5452. const data = cache[ key ];
  5453. delete data.metadata;
  5454. values.push( data );
  5455. }
  5456. return values;
  5457. }
  5458. if ( isRootObject ) {
  5459. const textures = extractFromCache( meta.textures );
  5460. const images = extractFromCache( meta.images );
  5461. if ( textures.length > 0 ) data.textures = textures;
  5462. if ( images.length > 0 ) data.images = images;
  5463. }
  5464. return data;
  5465. }
  5466. clone() {
  5467. return new this.constructor().copy( this );
  5468. }
  5469. copy( source ) {
  5470. this.name = source.name;
  5471. this.blending = source.blending;
  5472. this.side = source.side;
  5473. this.vertexColors = source.vertexColors;
  5474. this.opacity = source.opacity;
  5475. this.transparent = source.transparent;
  5476. this.blendSrc = source.blendSrc;
  5477. this.blendDst = source.blendDst;
  5478. this.blendEquation = source.blendEquation;
  5479. this.blendSrcAlpha = source.blendSrcAlpha;
  5480. this.blendDstAlpha = source.blendDstAlpha;
  5481. this.blendEquationAlpha = source.blendEquationAlpha;
  5482. this.depthFunc = source.depthFunc;
  5483. this.depthTest = source.depthTest;
  5484. this.depthWrite = source.depthWrite;
  5485. this.stencilWriteMask = source.stencilWriteMask;
  5486. this.stencilFunc = source.stencilFunc;
  5487. this.stencilRef = source.stencilRef;
  5488. this.stencilFuncMask = source.stencilFuncMask;
  5489. this.stencilFail = source.stencilFail;
  5490. this.stencilZFail = source.stencilZFail;
  5491. this.stencilZPass = source.stencilZPass;
  5492. this.stencilWrite = source.stencilWrite;
  5493. const srcPlanes = source.clippingPlanes;
  5494. let dstPlanes = null;
  5495. if ( srcPlanes !== null ) {
  5496. const n = srcPlanes.length;
  5497. dstPlanes = new Array( n );
  5498. for ( let i = 0; i !== n; ++ i ) {
  5499. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5500. }
  5501. }
  5502. this.clippingPlanes = dstPlanes;
  5503. this.clipIntersection = source.clipIntersection;
  5504. this.clipShadows = source.clipShadows;
  5505. this.shadowSide = source.shadowSide;
  5506. this.colorWrite = source.colorWrite;
  5507. this.precision = source.precision;
  5508. this.polygonOffset = source.polygonOffset;
  5509. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5510. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5511. this.dithering = source.dithering;
  5512. this.alphaTest = source.alphaTest;
  5513. this.alphaToCoverage = source.alphaToCoverage;
  5514. this.premultipliedAlpha = source.premultipliedAlpha;
  5515. this.forceSinglePass = source.forceSinglePass;
  5516. this.visible = source.visible;
  5517. this.toneMapped = source.toneMapped;
  5518. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5519. return this;
  5520. }
  5521. dispose() {
  5522. this.dispatchEvent( { type: 'dispose' } );
  5523. }
  5524. set needsUpdate( value ) {
  5525. if ( value === true ) this.version ++;
  5526. }
  5527. }
  5528. class MeshBasicMaterial extends Material {
  5529. constructor( parameters ) {
  5530. super();
  5531. this.isMeshBasicMaterial = true;
  5532. this.type = 'MeshBasicMaterial';
  5533. this.color = new Color( 0xffffff ); // emissive
  5534. this.map = null;
  5535. this.lightMap = null;
  5536. this.lightMapIntensity = 1.0;
  5537. this.aoMap = null;
  5538. this.aoMapIntensity = 1.0;
  5539. this.specularMap = null;
  5540. this.alphaMap = null;
  5541. this.envMap = null;
  5542. this.combine = MultiplyOperation;
  5543. this.reflectivity = 1;
  5544. this.refractionRatio = 0.98;
  5545. this.wireframe = false;
  5546. this.wireframeLinewidth = 1;
  5547. this.wireframeLinecap = 'round';
  5548. this.wireframeLinejoin = 'round';
  5549. this.fog = true;
  5550. this.setValues( parameters );
  5551. }
  5552. copy( source ) {
  5553. super.copy( source );
  5554. this.color.copy( source.color );
  5555. this.map = source.map;
  5556. this.lightMap = source.lightMap;
  5557. this.lightMapIntensity = source.lightMapIntensity;
  5558. this.aoMap = source.aoMap;
  5559. this.aoMapIntensity = source.aoMapIntensity;
  5560. this.specularMap = source.specularMap;
  5561. this.alphaMap = source.alphaMap;
  5562. this.envMap = source.envMap;
  5563. this.combine = source.combine;
  5564. this.reflectivity = source.reflectivity;
  5565. this.refractionRatio = source.refractionRatio;
  5566. this.wireframe = source.wireframe;
  5567. this.wireframeLinewidth = source.wireframeLinewidth;
  5568. this.wireframeLinecap = source.wireframeLinecap;
  5569. this.wireframeLinejoin = source.wireframeLinejoin;
  5570. this.fog = source.fog;
  5571. return this;
  5572. }
  5573. }
  5574. const _vector$9 = /*@__PURE__*/ new Vector3();
  5575. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5576. class BufferAttribute {
  5577. constructor( array, itemSize, normalized = false ) {
  5578. if ( Array.isArray( array ) ) {
  5579. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5580. }
  5581. this.isBufferAttribute = true;
  5582. this.name = '';
  5583. this.array = array;
  5584. this.itemSize = itemSize;
  5585. this.count = array !== undefined ? array.length / itemSize : 0;
  5586. this.normalized = normalized;
  5587. this.usage = StaticDrawUsage;
  5588. this.updateRange = { offset: 0, count: - 1 };
  5589. this.version = 0;
  5590. }
  5591. onUploadCallback() {}
  5592. set needsUpdate( value ) {
  5593. if ( value === true ) this.version ++;
  5594. }
  5595. setUsage( value ) {
  5596. this.usage = value;
  5597. return this;
  5598. }
  5599. copy( source ) {
  5600. this.name = source.name;
  5601. this.array = new source.array.constructor( source.array );
  5602. this.itemSize = source.itemSize;
  5603. this.count = source.count;
  5604. this.normalized = source.normalized;
  5605. this.usage = source.usage;
  5606. return this;
  5607. }
  5608. copyAt( index1, attribute, index2 ) {
  5609. index1 *= this.itemSize;
  5610. index2 *= attribute.itemSize;
  5611. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5612. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5613. }
  5614. return this;
  5615. }
  5616. copyArray( array ) {
  5617. this.array.set( array );
  5618. return this;
  5619. }
  5620. applyMatrix3( m ) {
  5621. if ( this.itemSize === 2 ) {
  5622. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5623. _vector2$1.fromBufferAttribute( this, i );
  5624. _vector2$1.applyMatrix3( m );
  5625. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5626. }
  5627. } else if ( this.itemSize === 3 ) {
  5628. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5629. _vector$9.fromBufferAttribute( this, i );
  5630. _vector$9.applyMatrix3( m );
  5631. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5632. }
  5633. }
  5634. return this;
  5635. }
  5636. applyMatrix4( m ) {
  5637. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5638. _vector$9.fromBufferAttribute( this, i );
  5639. _vector$9.applyMatrix4( m );
  5640. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5641. }
  5642. return this;
  5643. }
  5644. applyNormalMatrix( m ) {
  5645. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5646. _vector$9.fromBufferAttribute( this, i );
  5647. _vector$9.applyNormalMatrix( m );
  5648. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5649. }
  5650. return this;
  5651. }
  5652. transformDirection( m ) {
  5653. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5654. _vector$9.fromBufferAttribute( this, i );
  5655. _vector$9.transformDirection( m );
  5656. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5657. }
  5658. return this;
  5659. }
  5660. set( value, offset = 0 ) {
  5661. // Matching BufferAttribute constructor, do not normalize the array.
  5662. this.array.set( value, offset );
  5663. return this;
  5664. }
  5665. getX( index ) {
  5666. let x = this.array[ index * this.itemSize ];
  5667. if ( this.normalized ) x = denormalize( x, this.array );
  5668. return x;
  5669. }
  5670. setX( index, x ) {
  5671. if ( this.normalized ) x = normalize( x, this.array );
  5672. this.array[ index * this.itemSize ] = x;
  5673. return this;
  5674. }
  5675. getY( index ) {
  5676. let y = this.array[ index * this.itemSize + 1 ];
  5677. if ( this.normalized ) y = denormalize( y, this.array );
  5678. return y;
  5679. }
  5680. setY( index, y ) {
  5681. if ( this.normalized ) y = normalize( y, this.array );
  5682. this.array[ index * this.itemSize + 1 ] = y;
  5683. return this;
  5684. }
  5685. getZ( index ) {
  5686. let z = this.array[ index * this.itemSize + 2 ];
  5687. if ( this.normalized ) z = denormalize( z, this.array );
  5688. return z;
  5689. }
  5690. setZ( index, z ) {
  5691. if ( this.normalized ) z = normalize( z, this.array );
  5692. this.array[ index * this.itemSize + 2 ] = z;
  5693. return this;
  5694. }
  5695. getW( index ) {
  5696. let w = this.array[ index * this.itemSize + 3 ];
  5697. if ( this.normalized ) w = denormalize( w, this.array );
  5698. return w;
  5699. }
  5700. setW( index, w ) {
  5701. if ( this.normalized ) w = normalize( w, this.array );
  5702. this.array[ index * this.itemSize + 3 ] = w;
  5703. return this;
  5704. }
  5705. setXY( index, x, y ) {
  5706. index *= this.itemSize;
  5707. if ( this.normalized ) {
  5708. x = normalize( x, this.array );
  5709. y = normalize( y, this.array );
  5710. }
  5711. this.array[ index + 0 ] = x;
  5712. this.array[ index + 1 ] = y;
  5713. return this;
  5714. }
  5715. setXYZ( index, x, y, z ) {
  5716. index *= this.itemSize;
  5717. if ( this.normalized ) {
  5718. x = normalize( x, this.array );
  5719. y = normalize( y, this.array );
  5720. z = normalize( z, this.array );
  5721. }
  5722. this.array[ index + 0 ] = x;
  5723. this.array[ index + 1 ] = y;
  5724. this.array[ index + 2 ] = z;
  5725. return this;
  5726. }
  5727. setXYZW( index, x, y, z, w ) {
  5728. index *= this.itemSize;
  5729. if ( this.normalized ) {
  5730. x = normalize( x, this.array );
  5731. y = normalize( y, this.array );
  5732. z = normalize( z, this.array );
  5733. w = normalize( w, this.array );
  5734. }
  5735. this.array[ index + 0 ] = x;
  5736. this.array[ index + 1 ] = y;
  5737. this.array[ index + 2 ] = z;
  5738. this.array[ index + 3 ] = w;
  5739. return this;
  5740. }
  5741. onUpload( callback ) {
  5742. this.onUploadCallback = callback;
  5743. return this;
  5744. }
  5745. clone() {
  5746. return new this.constructor( this.array, this.itemSize ).copy( this );
  5747. }
  5748. toJSON() {
  5749. const data = {
  5750. itemSize: this.itemSize,
  5751. type: this.array.constructor.name,
  5752. array: Array.from( this.array ),
  5753. normalized: this.normalized
  5754. };
  5755. if ( this.name !== '' ) data.name = this.name;
  5756. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5757. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5758. return data;
  5759. }
  5760. // @deprecated
  5761. copyColorsArray() {
  5762. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5763. }
  5764. copyVector2sArray() {
  5765. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5766. }
  5767. copyVector3sArray() {
  5768. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5769. }
  5770. copyVector4sArray() {
  5771. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5772. }
  5773. }
  5774. //
  5775. class Int8BufferAttribute extends BufferAttribute {
  5776. constructor( array, itemSize, normalized ) {
  5777. super( new Int8Array( array ), itemSize, normalized );
  5778. }
  5779. }
  5780. class Uint8BufferAttribute extends BufferAttribute {
  5781. constructor( array, itemSize, normalized ) {
  5782. super( new Uint8Array( array ), itemSize, normalized );
  5783. }
  5784. }
  5785. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5786. constructor( array, itemSize, normalized ) {
  5787. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5788. }
  5789. }
  5790. class Int16BufferAttribute extends BufferAttribute {
  5791. constructor( array, itemSize, normalized ) {
  5792. super( new Int16Array( array ), itemSize, normalized );
  5793. }
  5794. }
  5795. class Uint16BufferAttribute extends BufferAttribute {
  5796. constructor( array, itemSize, normalized ) {
  5797. super( new Uint16Array( array ), itemSize, normalized );
  5798. }
  5799. }
  5800. class Int32BufferAttribute extends BufferAttribute {
  5801. constructor( array, itemSize, normalized ) {
  5802. super( new Int32Array( array ), itemSize, normalized );
  5803. }
  5804. }
  5805. class Uint32BufferAttribute extends BufferAttribute {
  5806. constructor( array, itemSize, normalized ) {
  5807. super( new Uint32Array( array ), itemSize, normalized );
  5808. }
  5809. }
  5810. class Float16BufferAttribute extends BufferAttribute {
  5811. constructor( array, itemSize, normalized ) {
  5812. super( new Uint16Array( array ), itemSize, normalized );
  5813. this.isFloat16BufferAttribute = true;
  5814. }
  5815. }
  5816. class Float32BufferAttribute extends BufferAttribute {
  5817. constructor( array, itemSize, normalized ) {
  5818. super( new Float32Array( array ), itemSize, normalized );
  5819. }
  5820. }
  5821. class Float64BufferAttribute extends BufferAttribute {
  5822. constructor( array, itemSize, normalized ) {
  5823. super( new Float64Array( array ), itemSize, normalized );
  5824. }
  5825. }
  5826. let _id$1 = 0;
  5827. const _m1 = /*@__PURE__*/ new Matrix4();
  5828. const _obj = /*@__PURE__*/ new Object3D();
  5829. const _offset = /*@__PURE__*/ new Vector3();
  5830. const _box$1 = /*@__PURE__*/ new Box3();
  5831. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5832. const _vector$8 = /*@__PURE__*/ new Vector3();
  5833. class BufferGeometry extends EventDispatcher {
  5834. constructor() {
  5835. super();
  5836. this.isBufferGeometry = true;
  5837. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5838. this.uuid = generateUUID();
  5839. this.name = '';
  5840. this.type = 'BufferGeometry';
  5841. this.index = null;
  5842. this.attributes = {};
  5843. this.morphAttributes = {};
  5844. this.morphTargetsRelative = false;
  5845. this.groups = [];
  5846. this.boundingBox = null;
  5847. this.boundingSphere = null;
  5848. this.drawRange = { start: 0, count: Infinity };
  5849. this.userData = {};
  5850. }
  5851. getIndex() {
  5852. return this.index;
  5853. }
  5854. setIndex( index ) {
  5855. if ( Array.isArray( index ) ) {
  5856. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5857. } else {
  5858. this.index = index;
  5859. }
  5860. return this;
  5861. }
  5862. getAttribute( name ) {
  5863. return this.attributes[ name ];
  5864. }
  5865. setAttribute( name, attribute ) {
  5866. this.attributes[ name ] = attribute;
  5867. return this;
  5868. }
  5869. deleteAttribute( name ) {
  5870. delete this.attributes[ name ];
  5871. return this;
  5872. }
  5873. hasAttribute( name ) {
  5874. return this.attributes[ name ] !== undefined;
  5875. }
  5876. addGroup( start, count, materialIndex = 0 ) {
  5877. this.groups.push( {
  5878. start: start,
  5879. count: count,
  5880. materialIndex: materialIndex
  5881. } );
  5882. }
  5883. clearGroups() {
  5884. this.groups = [];
  5885. }
  5886. setDrawRange( start, count ) {
  5887. this.drawRange.start = start;
  5888. this.drawRange.count = count;
  5889. }
  5890. applyMatrix4( matrix ) {
  5891. const position = this.attributes.position;
  5892. if ( position !== undefined ) {
  5893. position.applyMatrix4( matrix );
  5894. position.needsUpdate = true;
  5895. }
  5896. const normal = this.attributes.normal;
  5897. if ( normal !== undefined ) {
  5898. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5899. normal.applyNormalMatrix( normalMatrix );
  5900. normal.needsUpdate = true;
  5901. }
  5902. const tangent = this.attributes.tangent;
  5903. if ( tangent !== undefined ) {
  5904. tangent.transformDirection( matrix );
  5905. tangent.needsUpdate = true;
  5906. }
  5907. if ( this.boundingBox !== null ) {
  5908. this.computeBoundingBox();
  5909. }
  5910. if ( this.boundingSphere !== null ) {
  5911. this.computeBoundingSphere();
  5912. }
  5913. return this;
  5914. }
  5915. applyQuaternion( q ) {
  5916. _m1.makeRotationFromQuaternion( q );
  5917. this.applyMatrix4( _m1 );
  5918. return this;
  5919. }
  5920. rotateX( angle ) {
  5921. // rotate geometry around world x-axis
  5922. _m1.makeRotationX( angle );
  5923. this.applyMatrix4( _m1 );
  5924. return this;
  5925. }
  5926. rotateY( angle ) {
  5927. // rotate geometry around world y-axis
  5928. _m1.makeRotationY( angle );
  5929. this.applyMatrix4( _m1 );
  5930. return this;
  5931. }
  5932. rotateZ( angle ) {
  5933. // rotate geometry around world z-axis
  5934. _m1.makeRotationZ( angle );
  5935. this.applyMatrix4( _m1 );
  5936. return this;
  5937. }
  5938. translate( x, y, z ) {
  5939. // translate geometry
  5940. _m1.makeTranslation( x, y, z );
  5941. this.applyMatrix4( _m1 );
  5942. return this;
  5943. }
  5944. scale( x, y, z ) {
  5945. // scale geometry
  5946. _m1.makeScale( x, y, z );
  5947. this.applyMatrix4( _m1 );
  5948. return this;
  5949. }
  5950. lookAt( vector ) {
  5951. _obj.lookAt( vector );
  5952. _obj.updateMatrix();
  5953. this.applyMatrix4( _obj.matrix );
  5954. return this;
  5955. }
  5956. center() {
  5957. this.computeBoundingBox();
  5958. this.boundingBox.getCenter( _offset ).negate();
  5959. this.translate( _offset.x, _offset.y, _offset.z );
  5960. return this;
  5961. }
  5962. setFromPoints( points ) {
  5963. const position = [];
  5964. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5965. const point = points[ i ];
  5966. position.push( point.x, point.y, point.z || 0 );
  5967. }
  5968. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5969. return this;
  5970. }
  5971. computeBoundingBox() {
  5972. if ( this.boundingBox === null ) {
  5973. this.boundingBox = new Box3();
  5974. }
  5975. const position = this.attributes.position;
  5976. const morphAttributesPosition = this.morphAttributes.position;
  5977. if ( position && position.isGLBufferAttribute ) {
  5978. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5979. this.boundingBox.set(
  5980. new Vector3( - Infinity, - Infinity, - Infinity ),
  5981. new Vector3( + Infinity, + Infinity, + Infinity )
  5982. );
  5983. return;
  5984. }
  5985. if ( position !== undefined ) {
  5986. this.boundingBox.setFromBufferAttribute( position );
  5987. // process morph attributes if present
  5988. if ( morphAttributesPosition ) {
  5989. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5990. const morphAttribute = morphAttributesPosition[ i ];
  5991. _box$1.setFromBufferAttribute( morphAttribute );
  5992. if ( this.morphTargetsRelative ) {
  5993. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5994. this.boundingBox.expandByPoint( _vector$8 );
  5995. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5996. this.boundingBox.expandByPoint( _vector$8 );
  5997. } else {
  5998. this.boundingBox.expandByPoint( _box$1.min );
  5999. this.boundingBox.expandByPoint( _box$1.max );
  6000. }
  6001. }
  6002. }
  6003. } else {
  6004. this.boundingBox.makeEmpty();
  6005. }
  6006. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6007. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6008. }
  6009. }
  6010. computeBoundingSphere() {
  6011. if ( this.boundingSphere === null ) {
  6012. this.boundingSphere = new Sphere();
  6013. }
  6014. const position = this.attributes.position;
  6015. const morphAttributesPosition = this.morphAttributes.position;
  6016. if ( position && position.isGLBufferAttribute ) {
  6017. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6018. this.boundingSphere.set( new Vector3(), Infinity );
  6019. return;
  6020. }
  6021. if ( position ) {
  6022. // first, find the center of the bounding sphere
  6023. const center = this.boundingSphere.center;
  6024. _box$1.setFromBufferAttribute( position );
  6025. // process morph attributes if present
  6026. if ( morphAttributesPosition ) {
  6027. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6028. const morphAttribute = morphAttributesPosition[ i ];
  6029. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6030. if ( this.morphTargetsRelative ) {
  6031. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6032. _box$1.expandByPoint( _vector$8 );
  6033. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6034. _box$1.expandByPoint( _vector$8 );
  6035. } else {
  6036. _box$1.expandByPoint( _boxMorphTargets.min );
  6037. _box$1.expandByPoint( _boxMorphTargets.max );
  6038. }
  6039. }
  6040. }
  6041. _box$1.getCenter( center );
  6042. // second, try to find a boundingSphere with a radius smaller than the
  6043. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6044. let maxRadiusSq = 0;
  6045. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6046. _vector$8.fromBufferAttribute( position, i );
  6047. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6048. }
  6049. // process morph attributes if present
  6050. if ( morphAttributesPosition ) {
  6051. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6052. const morphAttribute = morphAttributesPosition[ i ];
  6053. const morphTargetsRelative = this.morphTargetsRelative;
  6054. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6055. _vector$8.fromBufferAttribute( morphAttribute, j );
  6056. if ( morphTargetsRelative ) {
  6057. _offset.fromBufferAttribute( position, j );
  6058. _vector$8.add( _offset );
  6059. }
  6060. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6061. }
  6062. }
  6063. }
  6064. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6065. if ( isNaN( this.boundingSphere.radius ) ) {
  6066. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6067. }
  6068. }
  6069. }
  6070. computeTangents() {
  6071. const index = this.index;
  6072. const attributes = this.attributes;
  6073. // based on http://www.terathon.com/code/tangent.html
  6074. // (per vertex tangents)
  6075. if ( index === null ||
  6076. attributes.position === undefined ||
  6077. attributes.normal === undefined ||
  6078. attributes.uv === undefined ) {
  6079. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6080. return;
  6081. }
  6082. const indices = index.array;
  6083. const positions = attributes.position.array;
  6084. const normals = attributes.normal.array;
  6085. const uvs = attributes.uv.array;
  6086. const nVertices = positions.length / 3;
  6087. if ( this.hasAttribute( 'tangent' ) === false ) {
  6088. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6089. }
  6090. const tangents = this.getAttribute( 'tangent' ).array;
  6091. const tan1 = [], tan2 = [];
  6092. for ( let i = 0; i < nVertices; i ++ ) {
  6093. tan1[ i ] = new Vector3();
  6094. tan2[ i ] = new Vector3();
  6095. }
  6096. const vA = new Vector3(),
  6097. vB = new Vector3(),
  6098. vC = new Vector3(),
  6099. uvA = new Vector2(),
  6100. uvB = new Vector2(),
  6101. uvC = new Vector2(),
  6102. sdir = new Vector3(),
  6103. tdir = new Vector3();
  6104. function handleTriangle( a, b, c ) {
  6105. vA.fromArray( positions, a * 3 );
  6106. vB.fromArray( positions, b * 3 );
  6107. vC.fromArray( positions, c * 3 );
  6108. uvA.fromArray( uvs, a * 2 );
  6109. uvB.fromArray( uvs, b * 2 );
  6110. uvC.fromArray( uvs, c * 2 );
  6111. vB.sub( vA );
  6112. vC.sub( vA );
  6113. uvB.sub( uvA );
  6114. uvC.sub( uvA );
  6115. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6116. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6117. if ( ! isFinite( r ) ) return;
  6118. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6119. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6120. tan1[ a ].add( sdir );
  6121. tan1[ b ].add( sdir );
  6122. tan1[ c ].add( sdir );
  6123. tan2[ a ].add( tdir );
  6124. tan2[ b ].add( tdir );
  6125. tan2[ c ].add( tdir );
  6126. }
  6127. let groups = this.groups;
  6128. if ( groups.length === 0 ) {
  6129. groups = [ {
  6130. start: 0,
  6131. count: indices.length
  6132. } ];
  6133. }
  6134. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6135. const group = groups[ i ];
  6136. const start = group.start;
  6137. const count = group.count;
  6138. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6139. handleTriangle(
  6140. indices[ j + 0 ],
  6141. indices[ j + 1 ],
  6142. indices[ j + 2 ]
  6143. );
  6144. }
  6145. }
  6146. const tmp = new Vector3(), tmp2 = new Vector3();
  6147. const n = new Vector3(), n2 = new Vector3();
  6148. function handleVertex( v ) {
  6149. n.fromArray( normals, v * 3 );
  6150. n2.copy( n );
  6151. const t = tan1[ v ];
  6152. // Gram-Schmidt orthogonalize
  6153. tmp.copy( t );
  6154. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6155. // Calculate handedness
  6156. tmp2.crossVectors( n2, t );
  6157. const test = tmp2.dot( tan2[ v ] );
  6158. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6159. tangents[ v * 4 ] = tmp.x;
  6160. tangents[ v * 4 + 1 ] = tmp.y;
  6161. tangents[ v * 4 + 2 ] = tmp.z;
  6162. tangents[ v * 4 + 3 ] = w;
  6163. }
  6164. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6165. const group = groups[ i ];
  6166. const start = group.start;
  6167. const count = group.count;
  6168. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6169. handleVertex( indices[ j + 0 ] );
  6170. handleVertex( indices[ j + 1 ] );
  6171. handleVertex( indices[ j + 2 ] );
  6172. }
  6173. }
  6174. }
  6175. computeVertexNormals() {
  6176. const index = this.index;
  6177. const positionAttribute = this.getAttribute( 'position' );
  6178. if ( positionAttribute !== undefined ) {
  6179. let normalAttribute = this.getAttribute( 'normal' );
  6180. if ( normalAttribute === undefined ) {
  6181. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6182. this.setAttribute( 'normal', normalAttribute );
  6183. } else {
  6184. // reset existing normals to zero
  6185. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6186. normalAttribute.setXYZ( i, 0, 0, 0 );
  6187. }
  6188. }
  6189. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6190. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6191. const cb = new Vector3(), ab = new Vector3();
  6192. // indexed elements
  6193. if ( index ) {
  6194. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6195. const vA = index.getX( i + 0 );
  6196. const vB = index.getX( i + 1 );
  6197. const vC = index.getX( i + 2 );
  6198. pA.fromBufferAttribute( positionAttribute, vA );
  6199. pB.fromBufferAttribute( positionAttribute, vB );
  6200. pC.fromBufferAttribute( positionAttribute, vC );
  6201. cb.subVectors( pC, pB );
  6202. ab.subVectors( pA, pB );
  6203. cb.cross( ab );
  6204. nA.fromBufferAttribute( normalAttribute, vA );
  6205. nB.fromBufferAttribute( normalAttribute, vB );
  6206. nC.fromBufferAttribute( normalAttribute, vC );
  6207. nA.add( cb );
  6208. nB.add( cb );
  6209. nC.add( cb );
  6210. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6211. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6212. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6213. }
  6214. } else {
  6215. // non-indexed elements (unconnected triangle soup)
  6216. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6217. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6218. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6219. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6220. cb.subVectors( pC, pB );
  6221. ab.subVectors( pA, pB );
  6222. cb.cross( ab );
  6223. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6224. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6225. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6226. }
  6227. }
  6228. this.normalizeNormals();
  6229. normalAttribute.needsUpdate = true;
  6230. }
  6231. }
  6232. // @deprecated since r144
  6233. merge() {
  6234. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6235. return this;
  6236. }
  6237. normalizeNormals() {
  6238. const normals = this.attributes.normal;
  6239. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6240. _vector$8.fromBufferAttribute( normals, i );
  6241. _vector$8.normalize();
  6242. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6243. }
  6244. }
  6245. toNonIndexed() {
  6246. function convertBufferAttribute( attribute, indices ) {
  6247. const array = attribute.array;
  6248. const itemSize = attribute.itemSize;
  6249. const normalized = attribute.normalized;
  6250. const array2 = new array.constructor( indices.length * itemSize );
  6251. let index = 0, index2 = 0;
  6252. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6253. if ( attribute.isInterleavedBufferAttribute ) {
  6254. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6255. } else {
  6256. index = indices[ i ] * itemSize;
  6257. }
  6258. for ( let j = 0; j < itemSize; j ++ ) {
  6259. array2[ index2 ++ ] = array[ index ++ ];
  6260. }
  6261. }
  6262. return new BufferAttribute( array2, itemSize, normalized );
  6263. }
  6264. //
  6265. if ( this.index === null ) {
  6266. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6267. return this;
  6268. }
  6269. const geometry2 = new BufferGeometry();
  6270. const indices = this.index.array;
  6271. const attributes = this.attributes;
  6272. // attributes
  6273. for ( const name in attributes ) {
  6274. const attribute = attributes[ name ];
  6275. const newAttribute = convertBufferAttribute( attribute, indices );
  6276. geometry2.setAttribute( name, newAttribute );
  6277. }
  6278. // morph attributes
  6279. const morphAttributes = this.morphAttributes;
  6280. for ( const name in morphAttributes ) {
  6281. const morphArray = [];
  6282. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6283. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6284. const attribute = morphAttribute[ i ];
  6285. const newAttribute = convertBufferAttribute( attribute, indices );
  6286. morphArray.push( newAttribute );
  6287. }
  6288. geometry2.morphAttributes[ name ] = morphArray;
  6289. }
  6290. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6291. // groups
  6292. const groups = this.groups;
  6293. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6294. const group = groups[ i ];
  6295. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6296. }
  6297. return geometry2;
  6298. }
  6299. toJSON() {
  6300. const data = {
  6301. metadata: {
  6302. version: 4.5,
  6303. type: 'BufferGeometry',
  6304. generator: 'BufferGeometry.toJSON'
  6305. }
  6306. };
  6307. // standard BufferGeometry serialization
  6308. data.uuid = this.uuid;
  6309. data.type = this.type;
  6310. if ( this.name !== '' ) data.name = this.name;
  6311. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6312. if ( this.parameters !== undefined ) {
  6313. const parameters = this.parameters;
  6314. for ( const key in parameters ) {
  6315. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6316. }
  6317. return data;
  6318. }
  6319. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6320. data.data = { attributes: {} };
  6321. const index = this.index;
  6322. if ( index !== null ) {
  6323. data.data.index = {
  6324. type: index.array.constructor.name,
  6325. array: Array.prototype.slice.call( index.array )
  6326. };
  6327. }
  6328. const attributes = this.attributes;
  6329. for ( const key in attributes ) {
  6330. const attribute = attributes[ key ];
  6331. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6332. }
  6333. const morphAttributes = {};
  6334. let hasMorphAttributes = false;
  6335. for ( const key in this.morphAttributes ) {
  6336. const attributeArray = this.morphAttributes[ key ];
  6337. const array = [];
  6338. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6339. const attribute = attributeArray[ i ];
  6340. array.push( attribute.toJSON( data.data ) );
  6341. }
  6342. if ( array.length > 0 ) {
  6343. morphAttributes[ key ] = array;
  6344. hasMorphAttributes = true;
  6345. }
  6346. }
  6347. if ( hasMorphAttributes ) {
  6348. data.data.morphAttributes = morphAttributes;
  6349. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6350. }
  6351. const groups = this.groups;
  6352. if ( groups.length > 0 ) {
  6353. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6354. }
  6355. const boundingSphere = this.boundingSphere;
  6356. if ( boundingSphere !== null ) {
  6357. data.data.boundingSphere = {
  6358. center: boundingSphere.center.toArray(),
  6359. radius: boundingSphere.radius
  6360. };
  6361. }
  6362. return data;
  6363. }
  6364. clone() {
  6365. return new this.constructor().copy( this );
  6366. }
  6367. copy( source ) {
  6368. // reset
  6369. this.index = null;
  6370. this.attributes = {};
  6371. this.morphAttributes = {};
  6372. this.groups = [];
  6373. this.boundingBox = null;
  6374. this.boundingSphere = null;
  6375. // used for storing cloned, shared data
  6376. const data = {};
  6377. // name
  6378. this.name = source.name;
  6379. // index
  6380. const index = source.index;
  6381. if ( index !== null ) {
  6382. this.setIndex( index.clone( data ) );
  6383. }
  6384. // attributes
  6385. const attributes = source.attributes;
  6386. for ( const name in attributes ) {
  6387. const attribute = attributes[ name ];
  6388. this.setAttribute( name, attribute.clone( data ) );
  6389. }
  6390. // morph attributes
  6391. const morphAttributes = source.morphAttributes;
  6392. for ( const name in morphAttributes ) {
  6393. const array = [];
  6394. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6395. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6396. array.push( morphAttribute[ i ].clone( data ) );
  6397. }
  6398. this.morphAttributes[ name ] = array;
  6399. }
  6400. this.morphTargetsRelative = source.morphTargetsRelative;
  6401. // groups
  6402. const groups = source.groups;
  6403. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6404. const group = groups[ i ];
  6405. this.addGroup( group.start, group.count, group.materialIndex );
  6406. }
  6407. // bounding box
  6408. const boundingBox = source.boundingBox;
  6409. if ( boundingBox !== null ) {
  6410. this.boundingBox = boundingBox.clone();
  6411. }
  6412. // bounding sphere
  6413. const boundingSphere = source.boundingSphere;
  6414. if ( boundingSphere !== null ) {
  6415. this.boundingSphere = boundingSphere.clone();
  6416. }
  6417. // draw range
  6418. this.drawRange.start = source.drawRange.start;
  6419. this.drawRange.count = source.drawRange.count;
  6420. // user data
  6421. this.userData = source.userData;
  6422. // geometry generator parameters
  6423. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6424. return this;
  6425. }
  6426. dispose() {
  6427. this.dispatchEvent( { type: 'dispose' } );
  6428. }
  6429. }
  6430. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6431. const _ray$2 = /*@__PURE__*/ new Ray();
  6432. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6433. const _vA$1 = /*@__PURE__*/ new Vector3();
  6434. const _vB$1 = /*@__PURE__*/ new Vector3();
  6435. const _vC$1 = /*@__PURE__*/ new Vector3();
  6436. const _tempA = /*@__PURE__*/ new Vector3();
  6437. const _morphA = /*@__PURE__*/ new Vector3();
  6438. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6439. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6440. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6441. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6442. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6443. class Mesh extends Object3D {
  6444. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6445. super();
  6446. this.isMesh = true;
  6447. this.type = 'Mesh';
  6448. this.geometry = geometry;
  6449. this.material = material;
  6450. this.updateMorphTargets();
  6451. }
  6452. copy( source, recursive ) {
  6453. super.copy( source, recursive );
  6454. if ( source.morphTargetInfluences !== undefined ) {
  6455. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6456. }
  6457. if ( source.morphTargetDictionary !== undefined ) {
  6458. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6459. }
  6460. this.material = source.material;
  6461. this.geometry = source.geometry;
  6462. return this;
  6463. }
  6464. updateMorphTargets() {
  6465. const geometry = this.geometry;
  6466. const morphAttributes = geometry.morphAttributes;
  6467. const keys = Object.keys( morphAttributes );
  6468. if ( keys.length > 0 ) {
  6469. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6470. if ( morphAttribute !== undefined ) {
  6471. this.morphTargetInfluences = [];
  6472. this.morphTargetDictionary = {};
  6473. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6474. const name = morphAttribute[ m ].name || String( m );
  6475. this.morphTargetInfluences.push( 0 );
  6476. this.morphTargetDictionary[ name ] = m;
  6477. }
  6478. }
  6479. }
  6480. }
  6481. getVertexPosition( index, target ) {
  6482. const geometry = this.geometry;
  6483. const position = geometry.attributes.position;
  6484. const morphPosition = geometry.morphAttributes.position;
  6485. const morphTargetsRelative = geometry.morphTargetsRelative;
  6486. target.fromBufferAttribute( position, index );
  6487. const morphInfluences = this.morphTargetInfluences;
  6488. if ( morphPosition && morphInfluences ) {
  6489. _morphA.set( 0, 0, 0 );
  6490. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6491. const influence = morphInfluences[ i ];
  6492. const morphAttribute = morphPosition[ i ];
  6493. if ( influence === 0 ) continue;
  6494. _tempA.fromBufferAttribute( morphAttribute, index );
  6495. if ( morphTargetsRelative ) {
  6496. _morphA.addScaledVector( _tempA, influence );
  6497. } else {
  6498. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6499. }
  6500. }
  6501. target.add( _morphA );
  6502. }
  6503. if ( this.isSkinnedMesh ) {
  6504. this.boneTransform( index, target );
  6505. }
  6506. return target;
  6507. }
  6508. raycast( raycaster, intersects ) {
  6509. const geometry = this.geometry;
  6510. const material = this.material;
  6511. const matrixWorld = this.matrixWorld;
  6512. if ( material === undefined ) return;
  6513. // Checking boundingSphere distance to ray
  6514. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6515. _sphere$3.copy( geometry.boundingSphere );
  6516. _sphere$3.applyMatrix4( matrixWorld );
  6517. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6518. //
  6519. _inverseMatrix$2.copy( matrixWorld ).invert();
  6520. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6521. // Check boundingBox before continuing
  6522. if ( geometry.boundingBox !== null ) {
  6523. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6524. }
  6525. let intersection;
  6526. const index = geometry.index;
  6527. const position = geometry.attributes.position;
  6528. const uv = geometry.attributes.uv;
  6529. const uv2 = geometry.attributes.uv2;
  6530. const groups = geometry.groups;
  6531. const drawRange = geometry.drawRange;
  6532. if ( index !== null ) {
  6533. // indexed buffer geometry
  6534. if ( Array.isArray( material ) ) {
  6535. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6536. const group = groups[ i ];
  6537. const groupMaterial = material[ group.materialIndex ];
  6538. const start = Math.max( group.start, drawRange.start );
  6539. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6540. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6541. const a = index.getX( j );
  6542. const b = index.getX( j + 1 );
  6543. const c = index.getX( j + 2 );
  6544. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6545. if ( intersection ) {
  6546. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6547. intersection.face.materialIndex = group.materialIndex;
  6548. intersects.push( intersection );
  6549. }
  6550. }
  6551. }
  6552. } else {
  6553. const start = Math.max( 0, drawRange.start );
  6554. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6555. for ( let i = start, il = end; i < il; i += 3 ) {
  6556. const a = index.getX( i );
  6557. const b = index.getX( i + 1 );
  6558. const c = index.getX( i + 2 );
  6559. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6560. if ( intersection ) {
  6561. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6562. intersects.push( intersection );
  6563. }
  6564. }
  6565. }
  6566. } else if ( position !== undefined ) {
  6567. // non-indexed buffer geometry
  6568. if ( Array.isArray( material ) ) {
  6569. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6570. const group = groups[ i ];
  6571. const groupMaterial = material[ group.materialIndex ];
  6572. const start = Math.max( group.start, drawRange.start );
  6573. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6574. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6575. const a = j;
  6576. const b = j + 1;
  6577. const c = j + 2;
  6578. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6579. if ( intersection ) {
  6580. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6581. intersection.face.materialIndex = group.materialIndex;
  6582. intersects.push( intersection );
  6583. }
  6584. }
  6585. }
  6586. } else {
  6587. const start = Math.max( 0, drawRange.start );
  6588. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6589. for ( let i = start, il = end; i < il; i += 3 ) {
  6590. const a = i;
  6591. const b = i + 1;
  6592. const c = i + 2;
  6593. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6594. if ( intersection ) {
  6595. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6596. intersects.push( intersection );
  6597. }
  6598. }
  6599. }
  6600. }
  6601. }
  6602. }
  6603. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6604. let intersect;
  6605. if ( material.side === BackSide ) {
  6606. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6607. } else {
  6608. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6609. }
  6610. if ( intersect === null ) return null;
  6611. _intersectionPointWorld.copy( point );
  6612. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6613. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6614. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6615. return {
  6616. distance: distance,
  6617. point: _intersectionPointWorld.clone(),
  6618. object: object
  6619. };
  6620. }
  6621. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6622. object.getVertexPosition( a, _vA$1 );
  6623. object.getVertexPosition( b, _vB$1 );
  6624. object.getVertexPosition( c, _vC$1 );
  6625. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6626. if ( intersection ) {
  6627. if ( uv ) {
  6628. _uvA$1.fromBufferAttribute( uv, a );
  6629. _uvB$1.fromBufferAttribute( uv, b );
  6630. _uvC$1.fromBufferAttribute( uv, c );
  6631. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6632. }
  6633. if ( uv2 ) {
  6634. _uvA$1.fromBufferAttribute( uv2, a );
  6635. _uvB$1.fromBufferAttribute( uv2, b );
  6636. _uvC$1.fromBufferAttribute( uv2, c );
  6637. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6638. }
  6639. const face = {
  6640. a: a,
  6641. b: b,
  6642. c: c,
  6643. normal: new Vector3(),
  6644. materialIndex: 0
  6645. };
  6646. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6647. intersection.face = face;
  6648. }
  6649. return intersection;
  6650. }
  6651. class BoxGeometry extends BufferGeometry {
  6652. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6653. super();
  6654. this.type = 'BoxGeometry';
  6655. this.parameters = {
  6656. width: width,
  6657. height: height,
  6658. depth: depth,
  6659. widthSegments: widthSegments,
  6660. heightSegments: heightSegments,
  6661. depthSegments: depthSegments
  6662. };
  6663. const scope = this;
  6664. // segments
  6665. widthSegments = Math.floor( widthSegments );
  6666. heightSegments = Math.floor( heightSegments );
  6667. depthSegments = Math.floor( depthSegments );
  6668. // buffers
  6669. const indices = [];
  6670. const vertices = [];
  6671. const normals = [];
  6672. const uvs = [];
  6673. // helper variables
  6674. let numberOfVertices = 0;
  6675. let groupStart = 0;
  6676. // build each side of the box geometry
  6677. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6678. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6679. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6680. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6681. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6682. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6683. // build geometry
  6684. this.setIndex( indices );
  6685. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6686. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6687. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6688. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6689. const segmentWidth = width / gridX;
  6690. const segmentHeight = height / gridY;
  6691. const widthHalf = width / 2;
  6692. const heightHalf = height / 2;
  6693. const depthHalf = depth / 2;
  6694. const gridX1 = gridX + 1;
  6695. const gridY1 = gridY + 1;
  6696. let vertexCounter = 0;
  6697. let groupCount = 0;
  6698. const vector = new Vector3();
  6699. // generate vertices, normals and uvs
  6700. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6701. const y = iy * segmentHeight - heightHalf;
  6702. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6703. const x = ix * segmentWidth - widthHalf;
  6704. // set values to correct vector component
  6705. vector[ u ] = x * udir;
  6706. vector[ v ] = y * vdir;
  6707. vector[ w ] = depthHalf;
  6708. // now apply vector to vertex buffer
  6709. vertices.push( vector.x, vector.y, vector.z );
  6710. // set values to correct vector component
  6711. vector[ u ] = 0;
  6712. vector[ v ] = 0;
  6713. vector[ w ] = depth > 0 ? 1 : - 1;
  6714. // now apply vector to normal buffer
  6715. normals.push( vector.x, vector.y, vector.z );
  6716. // uvs
  6717. uvs.push( ix / gridX );
  6718. uvs.push( 1 - ( iy / gridY ) );
  6719. // counters
  6720. vertexCounter += 1;
  6721. }
  6722. }
  6723. // indices
  6724. // 1. you need three indices to draw a single face
  6725. // 2. a single segment consists of two faces
  6726. // 3. so we need to generate six (2*3) indices per segment
  6727. for ( let iy = 0; iy < gridY; iy ++ ) {
  6728. for ( let ix = 0; ix < gridX; ix ++ ) {
  6729. const a = numberOfVertices + ix + gridX1 * iy;
  6730. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6731. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6732. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6733. // faces
  6734. indices.push( a, b, d );
  6735. indices.push( b, c, d );
  6736. // increase counter
  6737. groupCount += 6;
  6738. }
  6739. }
  6740. // add a group to the geometry. this will ensure multi material support
  6741. scope.addGroup( groupStart, groupCount, materialIndex );
  6742. // calculate new start value for groups
  6743. groupStart += groupCount;
  6744. // update total number of vertices
  6745. numberOfVertices += vertexCounter;
  6746. }
  6747. }
  6748. static fromJSON( data ) {
  6749. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6750. }
  6751. }
  6752. /**
  6753. * Uniform Utilities
  6754. */
  6755. function cloneUniforms( src ) {
  6756. const dst = {};
  6757. for ( const u in src ) {
  6758. dst[ u ] = {};
  6759. for ( const p in src[ u ] ) {
  6760. const property = src[ u ][ p ];
  6761. if ( property && ( property.isColor ||
  6762. property.isMatrix3 || property.isMatrix4 ||
  6763. property.isVector2 || property.isVector3 || property.isVector4 ||
  6764. property.isTexture || property.isQuaternion ) ) {
  6765. dst[ u ][ p ] = property.clone();
  6766. } else if ( Array.isArray( property ) ) {
  6767. dst[ u ][ p ] = property.slice();
  6768. } else {
  6769. dst[ u ][ p ] = property;
  6770. }
  6771. }
  6772. }
  6773. return dst;
  6774. }
  6775. function mergeUniforms( uniforms ) {
  6776. const merged = {};
  6777. for ( let u = 0; u < uniforms.length; u ++ ) {
  6778. const tmp = cloneUniforms( uniforms[ u ] );
  6779. for ( const p in tmp ) {
  6780. merged[ p ] = tmp[ p ];
  6781. }
  6782. }
  6783. return merged;
  6784. }
  6785. function cloneUniformsGroups( src ) {
  6786. const dst = [];
  6787. for ( let u = 0; u < src.length; u ++ ) {
  6788. dst.push( src[ u ].clone() );
  6789. }
  6790. return dst;
  6791. }
  6792. function getUnlitUniformColorSpace( renderer ) {
  6793. if ( renderer.getRenderTarget() === null ) {
  6794. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  6795. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  6796. }
  6797. return LinearSRGBColorSpace;
  6798. }
  6799. // Legacy
  6800. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6801. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6802. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6803. class ShaderMaterial extends Material {
  6804. constructor( parameters ) {
  6805. super();
  6806. this.isShaderMaterial = true;
  6807. this.type = 'ShaderMaterial';
  6808. this.defines = {};
  6809. this.uniforms = {};
  6810. this.uniformsGroups = [];
  6811. this.vertexShader = default_vertex;
  6812. this.fragmentShader = default_fragment;
  6813. this.linewidth = 1;
  6814. this.wireframe = false;
  6815. this.wireframeLinewidth = 1;
  6816. this.fog = false; // set to use scene fog
  6817. this.lights = false; // set to use scene lights
  6818. this.clipping = false; // set to use user-defined clipping planes
  6819. this.extensions = {
  6820. derivatives: false, // set to use derivatives
  6821. fragDepth: false, // set to use fragment depth values
  6822. drawBuffers: false, // set to use draw buffers
  6823. shaderTextureLOD: false // set to use shader texture LOD
  6824. };
  6825. // When rendered geometry doesn't include these attributes but the material does,
  6826. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6827. this.defaultAttributeValues = {
  6828. 'color': [ 1, 1, 1 ],
  6829. 'uv': [ 0, 0 ],
  6830. 'uv2': [ 0, 0 ]
  6831. };
  6832. this.index0AttributeName = undefined;
  6833. this.uniformsNeedUpdate = false;
  6834. this.glslVersion = null;
  6835. if ( parameters !== undefined ) {
  6836. this.setValues( parameters );
  6837. }
  6838. }
  6839. copy( source ) {
  6840. super.copy( source );
  6841. this.fragmentShader = source.fragmentShader;
  6842. this.vertexShader = source.vertexShader;
  6843. this.uniforms = cloneUniforms( source.uniforms );
  6844. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6845. this.defines = Object.assign( {}, source.defines );
  6846. this.wireframe = source.wireframe;
  6847. this.wireframeLinewidth = source.wireframeLinewidth;
  6848. this.fog = source.fog;
  6849. this.lights = source.lights;
  6850. this.clipping = source.clipping;
  6851. this.extensions = Object.assign( {}, source.extensions );
  6852. this.glslVersion = source.glslVersion;
  6853. return this;
  6854. }
  6855. toJSON( meta ) {
  6856. const data = super.toJSON( meta );
  6857. data.glslVersion = this.glslVersion;
  6858. data.uniforms = {};
  6859. for ( const name in this.uniforms ) {
  6860. const uniform = this.uniforms[ name ];
  6861. const value = uniform.value;
  6862. if ( value && value.isTexture ) {
  6863. data.uniforms[ name ] = {
  6864. type: 't',
  6865. value: value.toJSON( meta ).uuid
  6866. };
  6867. } else if ( value && value.isColor ) {
  6868. data.uniforms[ name ] = {
  6869. type: 'c',
  6870. value: value.getHex()
  6871. };
  6872. } else if ( value && value.isVector2 ) {
  6873. data.uniforms[ name ] = {
  6874. type: 'v2',
  6875. value: value.toArray()
  6876. };
  6877. } else if ( value && value.isVector3 ) {
  6878. data.uniforms[ name ] = {
  6879. type: 'v3',
  6880. value: value.toArray()
  6881. };
  6882. } else if ( value && value.isVector4 ) {
  6883. data.uniforms[ name ] = {
  6884. type: 'v4',
  6885. value: value.toArray()
  6886. };
  6887. } else if ( value && value.isMatrix3 ) {
  6888. data.uniforms[ name ] = {
  6889. type: 'm3',
  6890. value: value.toArray()
  6891. };
  6892. } else if ( value && value.isMatrix4 ) {
  6893. data.uniforms[ name ] = {
  6894. type: 'm4',
  6895. value: value.toArray()
  6896. };
  6897. } else {
  6898. data.uniforms[ name ] = {
  6899. value: value
  6900. };
  6901. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6902. }
  6903. }
  6904. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6905. data.vertexShader = this.vertexShader;
  6906. data.fragmentShader = this.fragmentShader;
  6907. const extensions = {};
  6908. for ( const key in this.extensions ) {
  6909. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6910. }
  6911. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6912. return data;
  6913. }
  6914. }
  6915. class Camera extends Object3D {
  6916. constructor() {
  6917. super();
  6918. this.isCamera = true;
  6919. this.type = 'Camera';
  6920. this.matrixWorldInverse = new Matrix4();
  6921. this.projectionMatrix = new Matrix4();
  6922. this.projectionMatrixInverse = new Matrix4();
  6923. }
  6924. copy( source, recursive ) {
  6925. super.copy( source, recursive );
  6926. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6927. this.projectionMatrix.copy( source.projectionMatrix );
  6928. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6929. return this;
  6930. }
  6931. getWorldDirection( target ) {
  6932. this.updateWorldMatrix( true, false );
  6933. const e = this.matrixWorld.elements;
  6934. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6935. }
  6936. updateMatrixWorld( force ) {
  6937. super.updateMatrixWorld( force );
  6938. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6939. }
  6940. updateWorldMatrix( updateParents, updateChildren ) {
  6941. super.updateWorldMatrix( updateParents, updateChildren );
  6942. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6943. }
  6944. clone() {
  6945. return new this.constructor().copy( this );
  6946. }
  6947. }
  6948. class PerspectiveCamera extends Camera {
  6949. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6950. super();
  6951. this.isPerspectiveCamera = true;
  6952. this.type = 'PerspectiveCamera';
  6953. this.fov = fov;
  6954. this.zoom = 1;
  6955. this.near = near;
  6956. this.far = far;
  6957. this.focus = 10;
  6958. this.aspect = aspect;
  6959. this.view = null;
  6960. this.filmGauge = 35; // width of the film (default in millimeters)
  6961. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6962. this.updateProjectionMatrix();
  6963. }
  6964. copy( source, recursive ) {
  6965. super.copy( source, recursive );
  6966. this.fov = source.fov;
  6967. this.zoom = source.zoom;
  6968. this.near = source.near;
  6969. this.far = source.far;
  6970. this.focus = source.focus;
  6971. this.aspect = source.aspect;
  6972. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6973. this.filmGauge = source.filmGauge;
  6974. this.filmOffset = source.filmOffset;
  6975. return this;
  6976. }
  6977. /**
  6978. * Sets the FOV by focal length in respect to the current .filmGauge.
  6979. *
  6980. * The default film gauge is 35, so that the focal length can be specified for
  6981. * a 35mm (full frame) camera.
  6982. *
  6983. * Values for focal length and film gauge must have the same unit.
  6984. */
  6985. setFocalLength( focalLength ) {
  6986. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6987. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6988. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6989. this.updateProjectionMatrix();
  6990. }
  6991. /**
  6992. * Calculates the focal length from the current .fov and .filmGauge.
  6993. */
  6994. getFocalLength() {
  6995. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6996. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6997. }
  6998. getEffectiveFOV() {
  6999. return RAD2DEG * 2 * Math.atan(
  7000. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7001. }
  7002. getFilmWidth() {
  7003. // film not completely covered in portrait format (aspect < 1)
  7004. return this.filmGauge * Math.min( this.aspect, 1 );
  7005. }
  7006. getFilmHeight() {
  7007. // film not completely covered in landscape format (aspect > 1)
  7008. return this.filmGauge / Math.max( this.aspect, 1 );
  7009. }
  7010. /**
  7011. * Sets an offset in a larger frustum. This is useful for multi-window or
  7012. * multi-monitor/multi-machine setups.
  7013. *
  7014. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7015. * the monitors are in grid like this
  7016. *
  7017. * +---+---+---+
  7018. * | A | B | C |
  7019. * +---+---+---+
  7020. * | D | E | F |
  7021. * +---+---+---+
  7022. *
  7023. * then for each monitor you would call it like this
  7024. *
  7025. * const w = 1920;
  7026. * const h = 1080;
  7027. * const fullWidth = w * 3;
  7028. * const fullHeight = h * 2;
  7029. *
  7030. * --A--
  7031. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7032. * --B--
  7033. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7034. * --C--
  7035. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7036. * --D--
  7037. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7038. * --E--
  7039. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7040. * --F--
  7041. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7042. *
  7043. * Note there is no reason monitors have to be the same size or in a grid.
  7044. */
  7045. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7046. this.aspect = fullWidth / fullHeight;
  7047. if ( this.view === null ) {
  7048. this.view = {
  7049. enabled: true,
  7050. fullWidth: 1,
  7051. fullHeight: 1,
  7052. offsetX: 0,
  7053. offsetY: 0,
  7054. width: 1,
  7055. height: 1
  7056. };
  7057. }
  7058. this.view.enabled = true;
  7059. this.view.fullWidth = fullWidth;
  7060. this.view.fullHeight = fullHeight;
  7061. this.view.offsetX = x;
  7062. this.view.offsetY = y;
  7063. this.view.width = width;
  7064. this.view.height = height;
  7065. this.updateProjectionMatrix();
  7066. }
  7067. clearViewOffset() {
  7068. if ( this.view !== null ) {
  7069. this.view.enabled = false;
  7070. }
  7071. this.updateProjectionMatrix();
  7072. }
  7073. updateProjectionMatrix() {
  7074. const near = this.near;
  7075. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7076. let height = 2 * top;
  7077. let width = this.aspect * height;
  7078. let left = - 0.5 * width;
  7079. const view = this.view;
  7080. if ( this.view !== null && this.view.enabled ) {
  7081. const fullWidth = view.fullWidth,
  7082. fullHeight = view.fullHeight;
  7083. left += view.offsetX * width / fullWidth;
  7084. top -= view.offsetY * height / fullHeight;
  7085. width *= view.width / fullWidth;
  7086. height *= view.height / fullHeight;
  7087. }
  7088. const skew = this.filmOffset;
  7089. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7090. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7091. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7092. }
  7093. toJSON( meta ) {
  7094. const data = super.toJSON( meta );
  7095. data.object.fov = this.fov;
  7096. data.object.zoom = this.zoom;
  7097. data.object.near = this.near;
  7098. data.object.far = this.far;
  7099. data.object.focus = this.focus;
  7100. data.object.aspect = this.aspect;
  7101. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7102. data.object.filmGauge = this.filmGauge;
  7103. data.object.filmOffset = this.filmOffset;
  7104. return data;
  7105. }
  7106. }
  7107. const fov = - 90; // negative fov is not an error
  7108. const aspect = 1;
  7109. class CubeCamera extends Object3D {
  7110. constructor( near, far, renderTarget ) {
  7111. super();
  7112. this.type = 'CubeCamera';
  7113. this.renderTarget = renderTarget;
  7114. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7115. cameraPX.layers = this.layers;
  7116. cameraPX.up.set( 0, 1, 0 );
  7117. cameraPX.lookAt( 1, 0, 0 );
  7118. this.add( cameraPX );
  7119. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7120. cameraNX.layers = this.layers;
  7121. cameraNX.up.set( 0, 1, 0 );
  7122. cameraNX.lookAt( - 1, 0, 0 );
  7123. this.add( cameraNX );
  7124. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7125. cameraPY.layers = this.layers;
  7126. cameraPY.up.set( 0, 0, - 1 );
  7127. cameraPY.lookAt( 0, 1, 0 );
  7128. this.add( cameraPY );
  7129. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7130. cameraNY.layers = this.layers;
  7131. cameraNY.up.set( 0, 0, 1 );
  7132. cameraNY.lookAt( 0, - 1, 0 );
  7133. this.add( cameraNY );
  7134. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7135. cameraPZ.layers = this.layers;
  7136. cameraPZ.up.set( 0, 1, 0 );
  7137. cameraPZ.lookAt( 0, 0, 1 );
  7138. this.add( cameraPZ );
  7139. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7140. cameraNZ.layers = this.layers;
  7141. cameraNZ.up.set( 0, 1, 0 );
  7142. cameraNZ.lookAt( 0, 0, - 1 );
  7143. this.add( cameraNZ );
  7144. }
  7145. update( renderer, scene ) {
  7146. if ( this.parent === null ) this.updateMatrixWorld();
  7147. const renderTarget = this.renderTarget;
  7148. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7149. const currentRenderTarget = renderer.getRenderTarget();
  7150. const currentToneMapping = renderer.toneMapping;
  7151. const currentXrEnabled = renderer.xr.enabled;
  7152. renderer.toneMapping = NoToneMapping;
  7153. renderer.xr.enabled = false;
  7154. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7155. renderTarget.texture.generateMipmaps = false;
  7156. renderer.setRenderTarget( renderTarget, 0 );
  7157. renderer.render( scene, cameraPX );
  7158. renderer.setRenderTarget( renderTarget, 1 );
  7159. renderer.render( scene, cameraNX );
  7160. renderer.setRenderTarget( renderTarget, 2 );
  7161. renderer.render( scene, cameraPY );
  7162. renderer.setRenderTarget( renderTarget, 3 );
  7163. renderer.render( scene, cameraNY );
  7164. renderer.setRenderTarget( renderTarget, 4 );
  7165. renderer.render( scene, cameraPZ );
  7166. renderTarget.texture.generateMipmaps = generateMipmaps;
  7167. renderer.setRenderTarget( renderTarget, 5 );
  7168. renderer.render( scene, cameraNZ );
  7169. renderer.setRenderTarget( currentRenderTarget );
  7170. renderer.toneMapping = currentToneMapping;
  7171. renderer.xr.enabled = currentXrEnabled;
  7172. renderTarget.texture.needsPMREMUpdate = true;
  7173. }
  7174. }
  7175. class CubeTexture extends Texture {
  7176. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7177. images = images !== undefined ? images : [];
  7178. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7179. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7180. this.isCubeTexture = true;
  7181. this.flipY = false;
  7182. }
  7183. get images() {
  7184. return this.image;
  7185. }
  7186. set images( value ) {
  7187. this.image = value;
  7188. }
  7189. }
  7190. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7191. constructor( size = 1, options = {} ) {
  7192. super( size, size, options );
  7193. this.isWebGLCubeRenderTarget = true;
  7194. const image = { width: size, height: size, depth: 1 };
  7195. const images = [ image, image, image, image, image, image ];
  7196. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7197. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7198. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7199. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7200. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7201. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7202. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7203. this.texture.isRenderTargetTexture = true;
  7204. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7205. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7206. }
  7207. fromEquirectangularTexture( renderer, texture ) {
  7208. this.texture.type = texture.type;
  7209. this.texture.encoding = texture.encoding;
  7210. this.texture.generateMipmaps = texture.generateMipmaps;
  7211. this.texture.minFilter = texture.minFilter;
  7212. this.texture.magFilter = texture.magFilter;
  7213. const shader = {
  7214. uniforms: {
  7215. tEquirect: { value: null },
  7216. },
  7217. vertexShader: /* glsl */`
  7218. varying vec3 vWorldDirection;
  7219. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7220. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7221. }
  7222. void main() {
  7223. vWorldDirection = transformDirection( position, modelMatrix );
  7224. #include <begin_vertex>
  7225. #include <project_vertex>
  7226. }
  7227. `,
  7228. fragmentShader: /* glsl */`
  7229. uniform sampler2D tEquirect;
  7230. varying vec3 vWorldDirection;
  7231. #include <common>
  7232. void main() {
  7233. vec3 direction = normalize( vWorldDirection );
  7234. vec2 sampleUV = equirectUv( direction );
  7235. gl_FragColor = texture2D( tEquirect, sampleUV );
  7236. }
  7237. `
  7238. };
  7239. const geometry = new BoxGeometry( 5, 5, 5 );
  7240. const material = new ShaderMaterial( {
  7241. name: 'CubemapFromEquirect',
  7242. uniforms: cloneUniforms( shader.uniforms ),
  7243. vertexShader: shader.vertexShader,
  7244. fragmentShader: shader.fragmentShader,
  7245. side: BackSide,
  7246. blending: NoBlending
  7247. } );
  7248. material.uniforms.tEquirect.value = texture;
  7249. const mesh = new Mesh( geometry, material );
  7250. const currentMinFilter = texture.minFilter;
  7251. // Avoid blurred poles
  7252. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7253. const camera = new CubeCamera( 1, 10, this );
  7254. camera.update( renderer, mesh );
  7255. texture.minFilter = currentMinFilter;
  7256. mesh.geometry.dispose();
  7257. mesh.material.dispose();
  7258. return this;
  7259. }
  7260. clear( renderer, color, depth, stencil ) {
  7261. const currentRenderTarget = renderer.getRenderTarget();
  7262. for ( let i = 0; i < 6; i ++ ) {
  7263. renderer.setRenderTarget( this, i );
  7264. renderer.clear( color, depth, stencil );
  7265. }
  7266. renderer.setRenderTarget( currentRenderTarget );
  7267. }
  7268. }
  7269. const _vector1 = /*@__PURE__*/ new Vector3();
  7270. const _vector2 = /*@__PURE__*/ new Vector3();
  7271. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7272. class Plane {
  7273. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7274. this.isPlane = true;
  7275. // normal is assumed to be normalized
  7276. this.normal = normal;
  7277. this.constant = constant;
  7278. }
  7279. set( normal, constant ) {
  7280. this.normal.copy( normal );
  7281. this.constant = constant;
  7282. return this;
  7283. }
  7284. setComponents( x, y, z, w ) {
  7285. this.normal.set( x, y, z );
  7286. this.constant = w;
  7287. return this;
  7288. }
  7289. setFromNormalAndCoplanarPoint( normal, point ) {
  7290. this.normal.copy( normal );
  7291. this.constant = - point.dot( this.normal );
  7292. return this;
  7293. }
  7294. setFromCoplanarPoints( a, b, c ) {
  7295. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7296. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7297. this.setFromNormalAndCoplanarPoint( normal, a );
  7298. return this;
  7299. }
  7300. copy( plane ) {
  7301. this.normal.copy( plane.normal );
  7302. this.constant = plane.constant;
  7303. return this;
  7304. }
  7305. normalize() {
  7306. // Note: will lead to a divide by zero if the plane is invalid.
  7307. const inverseNormalLength = 1.0 / this.normal.length();
  7308. this.normal.multiplyScalar( inverseNormalLength );
  7309. this.constant *= inverseNormalLength;
  7310. return this;
  7311. }
  7312. negate() {
  7313. this.constant *= - 1;
  7314. this.normal.negate();
  7315. return this;
  7316. }
  7317. distanceToPoint( point ) {
  7318. return this.normal.dot( point ) + this.constant;
  7319. }
  7320. distanceToSphere( sphere ) {
  7321. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7322. }
  7323. projectPoint( point, target ) {
  7324. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7325. }
  7326. intersectLine( line, target ) {
  7327. const direction = line.delta( _vector1 );
  7328. const denominator = this.normal.dot( direction );
  7329. if ( denominator === 0 ) {
  7330. // line is coplanar, return origin
  7331. if ( this.distanceToPoint( line.start ) === 0 ) {
  7332. return target.copy( line.start );
  7333. }
  7334. // Unsure if this is the correct method to handle this case.
  7335. return null;
  7336. }
  7337. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7338. if ( t < 0 || t > 1 ) {
  7339. return null;
  7340. }
  7341. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7342. }
  7343. intersectsLine( line ) {
  7344. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7345. const startSign = this.distanceToPoint( line.start );
  7346. const endSign = this.distanceToPoint( line.end );
  7347. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7348. }
  7349. intersectsBox( box ) {
  7350. return box.intersectsPlane( this );
  7351. }
  7352. intersectsSphere( sphere ) {
  7353. return sphere.intersectsPlane( this );
  7354. }
  7355. coplanarPoint( target ) {
  7356. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7357. }
  7358. applyMatrix4( matrix, optionalNormalMatrix ) {
  7359. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7360. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7361. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7362. this.constant = - referencePoint.dot( normal );
  7363. return this;
  7364. }
  7365. translate( offset ) {
  7366. this.constant -= offset.dot( this.normal );
  7367. return this;
  7368. }
  7369. equals( plane ) {
  7370. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7371. }
  7372. clone() {
  7373. return new this.constructor().copy( this );
  7374. }
  7375. }
  7376. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7377. const _vector$7 = /*@__PURE__*/ new Vector3();
  7378. class Frustum {
  7379. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7380. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7381. }
  7382. set( p0, p1, p2, p3, p4, p5 ) {
  7383. const planes = this.planes;
  7384. planes[ 0 ].copy( p0 );
  7385. planes[ 1 ].copy( p1 );
  7386. planes[ 2 ].copy( p2 );
  7387. planes[ 3 ].copy( p3 );
  7388. planes[ 4 ].copy( p4 );
  7389. planes[ 5 ].copy( p5 );
  7390. return this;
  7391. }
  7392. copy( frustum ) {
  7393. const planes = this.planes;
  7394. for ( let i = 0; i < 6; i ++ ) {
  7395. planes[ i ].copy( frustum.planes[ i ] );
  7396. }
  7397. return this;
  7398. }
  7399. setFromProjectionMatrix( m ) {
  7400. const planes = this.planes;
  7401. const me = m.elements;
  7402. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7403. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7404. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7405. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7406. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7407. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7408. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7409. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7410. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7411. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7412. return this;
  7413. }
  7414. intersectsObject( object ) {
  7415. const geometry = object.geometry;
  7416. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7417. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7418. return this.intersectsSphere( _sphere$2 );
  7419. }
  7420. intersectsSprite( sprite ) {
  7421. _sphere$2.center.set( 0, 0, 0 );
  7422. _sphere$2.radius = 0.7071067811865476;
  7423. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7424. return this.intersectsSphere( _sphere$2 );
  7425. }
  7426. intersectsSphere( sphere ) {
  7427. const planes = this.planes;
  7428. const center = sphere.center;
  7429. const negRadius = - sphere.radius;
  7430. for ( let i = 0; i < 6; i ++ ) {
  7431. const distance = planes[ i ].distanceToPoint( center );
  7432. if ( distance < negRadius ) {
  7433. return false;
  7434. }
  7435. }
  7436. return true;
  7437. }
  7438. intersectsBox( box ) {
  7439. const planes = this.planes;
  7440. for ( let i = 0; i < 6; i ++ ) {
  7441. const plane = planes[ i ];
  7442. // corner at max distance
  7443. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7444. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7445. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7446. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7447. return false;
  7448. }
  7449. }
  7450. return true;
  7451. }
  7452. containsPoint( point ) {
  7453. const planes = this.planes;
  7454. for ( let i = 0; i < 6; i ++ ) {
  7455. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7456. return false;
  7457. }
  7458. }
  7459. return true;
  7460. }
  7461. clone() {
  7462. return new this.constructor().copy( this );
  7463. }
  7464. }
  7465. function WebGLAnimation() {
  7466. let context = null;
  7467. let isAnimating = false;
  7468. let animationLoop = null;
  7469. let requestId = null;
  7470. function onAnimationFrame( time, frame ) {
  7471. animationLoop( time, frame );
  7472. requestId = context.requestAnimationFrame( onAnimationFrame );
  7473. }
  7474. return {
  7475. start: function () {
  7476. if ( isAnimating === true ) return;
  7477. if ( animationLoop === null ) return;
  7478. requestId = context.requestAnimationFrame( onAnimationFrame );
  7479. isAnimating = true;
  7480. },
  7481. stop: function () {
  7482. context.cancelAnimationFrame( requestId );
  7483. isAnimating = false;
  7484. },
  7485. setAnimationLoop: function ( callback ) {
  7486. animationLoop = callback;
  7487. },
  7488. setContext: function ( value ) {
  7489. context = value;
  7490. }
  7491. };
  7492. }
  7493. function WebGLAttributes( gl, capabilities ) {
  7494. const isWebGL2 = capabilities.isWebGL2;
  7495. const buffers = new WeakMap();
  7496. function createBuffer( attribute, bufferType ) {
  7497. const array = attribute.array;
  7498. const usage = attribute.usage;
  7499. const buffer = gl.createBuffer();
  7500. gl.bindBuffer( bufferType, buffer );
  7501. gl.bufferData( bufferType, array, usage );
  7502. attribute.onUploadCallback();
  7503. let type;
  7504. if ( array instanceof Float32Array ) {
  7505. type = gl.FLOAT;
  7506. } else if ( array instanceof Uint16Array ) {
  7507. if ( attribute.isFloat16BufferAttribute ) {
  7508. if ( isWebGL2 ) {
  7509. type = gl.HALF_FLOAT;
  7510. } else {
  7511. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7512. }
  7513. } else {
  7514. type = gl.UNSIGNED_SHORT;
  7515. }
  7516. } else if ( array instanceof Int16Array ) {
  7517. type = gl.SHORT;
  7518. } else if ( array instanceof Uint32Array ) {
  7519. type = gl.UNSIGNED_INT;
  7520. } else if ( array instanceof Int32Array ) {
  7521. type = gl.INT;
  7522. } else if ( array instanceof Int8Array ) {
  7523. type = gl.BYTE;
  7524. } else if ( array instanceof Uint8Array ) {
  7525. type = gl.UNSIGNED_BYTE;
  7526. } else if ( array instanceof Uint8ClampedArray ) {
  7527. type = gl.UNSIGNED_BYTE;
  7528. } else {
  7529. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7530. }
  7531. return {
  7532. buffer: buffer,
  7533. type: type,
  7534. bytesPerElement: array.BYTES_PER_ELEMENT,
  7535. version: attribute.version
  7536. };
  7537. }
  7538. function updateBuffer( buffer, attribute, bufferType ) {
  7539. const array = attribute.array;
  7540. const updateRange = attribute.updateRange;
  7541. gl.bindBuffer( bufferType, buffer );
  7542. if ( updateRange.count === - 1 ) {
  7543. // Not using update ranges
  7544. gl.bufferSubData( bufferType, 0, array );
  7545. } else {
  7546. if ( isWebGL2 ) {
  7547. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7548. array, updateRange.offset, updateRange.count );
  7549. } else {
  7550. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7551. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7552. }
  7553. updateRange.count = - 1; // reset range
  7554. }
  7555. attribute.onUploadCallback();
  7556. }
  7557. //
  7558. function get( attribute ) {
  7559. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7560. return buffers.get( attribute );
  7561. }
  7562. function remove( attribute ) {
  7563. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7564. const data = buffers.get( attribute );
  7565. if ( data ) {
  7566. gl.deleteBuffer( data.buffer );
  7567. buffers.delete( attribute );
  7568. }
  7569. }
  7570. function update( attribute, bufferType ) {
  7571. if ( attribute.isGLBufferAttribute ) {
  7572. const cached = buffers.get( attribute );
  7573. if ( ! cached || cached.version < attribute.version ) {
  7574. buffers.set( attribute, {
  7575. buffer: attribute.buffer,
  7576. type: attribute.type,
  7577. bytesPerElement: attribute.elementSize,
  7578. version: attribute.version
  7579. } );
  7580. }
  7581. return;
  7582. }
  7583. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7584. const data = buffers.get( attribute );
  7585. if ( data === undefined ) {
  7586. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7587. } else if ( data.version < attribute.version ) {
  7588. updateBuffer( data.buffer, attribute, bufferType );
  7589. data.version = attribute.version;
  7590. }
  7591. }
  7592. return {
  7593. get: get,
  7594. remove: remove,
  7595. update: update
  7596. };
  7597. }
  7598. class PlaneGeometry extends BufferGeometry {
  7599. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7600. super();
  7601. this.type = 'PlaneGeometry';
  7602. this.parameters = {
  7603. width: width,
  7604. height: height,
  7605. widthSegments: widthSegments,
  7606. heightSegments: heightSegments
  7607. };
  7608. const width_half = width / 2;
  7609. const height_half = height / 2;
  7610. const gridX = Math.floor( widthSegments );
  7611. const gridY = Math.floor( heightSegments );
  7612. const gridX1 = gridX + 1;
  7613. const gridY1 = gridY + 1;
  7614. const segment_width = width / gridX;
  7615. const segment_height = height / gridY;
  7616. //
  7617. const indices = [];
  7618. const vertices = [];
  7619. const normals = [];
  7620. const uvs = [];
  7621. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7622. const y = iy * segment_height - height_half;
  7623. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7624. const x = ix * segment_width - width_half;
  7625. vertices.push( x, - y, 0 );
  7626. normals.push( 0, 0, 1 );
  7627. uvs.push( ix / gridX );
  7628. uvs.push( 1 - ( iy / gridY ) );
  7629. }
  7630. }
  7631. for ( let iy = 0; iy < gridY; iy ++ ) {
  7632. for ( let ix = 0; ix < gridX; ix ++ ) {
  7633. const a = ix + gridX1 * iy;
  7634. const b = ix + gridX1 * ( iy + 1 );
  7635. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7636. const d = ( ix + 1 ) + gridX1 * iy;
  7637. indices.push( a, b, d );
  7638. indices.push( b, c, d );
  7639. }
  7640. }
  7641. this.setIndex( indices );
  7642. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7643. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7644. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7645. }
  7646. static fromJSON( data ) {
  7647. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7648. }
  7649. }
  7650. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7651. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7652. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7653. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7654. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7655. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7656. var begin_vertex = "vec3 transformed = vec3( position );";
  7657. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7658. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7659. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  7660. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7661. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7662. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7663. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7664. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7665. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7666. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7667. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7668. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7669. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7670. 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_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7671. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7672. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7673. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7674. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7675. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7676. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7677. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  7678. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#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";
  7679. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7680. 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";
  7681. 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";
  7682. 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";
  7683. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7684. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7685. 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";
  7686. 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";
  7687. 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}";
  7688. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7689. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7690. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7691. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  7692. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7693. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7694. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7695. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  7696. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7697. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  7698. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7699. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7700. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\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.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7701. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7702. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  7703. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7704. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  7705. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  7706. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  7707. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7708. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7709. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7710. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7711. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7712. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7713. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  7714. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7715. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7716. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7717. 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 = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7718. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7719. 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";
  7720. 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";
  7721. 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";
  7722. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7723. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7724. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7725. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7726. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7727. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7728. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7729. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7730. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  7731. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7732. 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";
  7733. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7734. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7735. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\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 shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7736. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7737. 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";
  7738. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7739. 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";
  7740. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  7741. 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";
  7742. 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";
  7743. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7744. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7745. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7746. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7747. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  7748. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7749. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7750. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7751. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7752. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7753. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7754. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7755. 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_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7756. 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}";
  7757. 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 <encodings_fragment>\n}";
  7758. 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}";
  7759. 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;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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 <encodings_fragment>\n}";
  7760. 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}";
  7761. 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 <encodings_fragment>\n}";
  7762. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7763. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7764. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7765. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7766. 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}";
  7767. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7768. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7769. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7770. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7771. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7772. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7773. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7774. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7775. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7776. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7777. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  7778. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7779. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7780. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7781. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7782. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7783. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7784. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  7785. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7786. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7787. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7788. 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}";
  7789. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7790. const ShaderChunk = {
  7791. alphamap_fragment: alphamap_fragment,
  7792. alphamap_pars_fragment: alphamap_pars_fragment,
  7793. alphatest_fragment: alphatest_fragment,
  7794. alphatest_pars_fragment: alphatest_pars_fragment,
  7795. aomap_fragment: aomap_fragment,
  7796. aomap_pars_fragment: aomap_pars_fragment,
  7797. begin_vertex: begin_vertex,
  7798. beginnormal_vertex: beginnormal_vertex,
  7799. bsdfs: bsdfs,
  7800. iridescence_fragment: iridescence_fragment,
  7801. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7802. clipping_planes_fragment: clipping_planes_fragment,
  7803. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7804. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7805. clipping_planes_vertex: clipping_planes_vertex,
  7806. color_fragment: color_fragment,
  7807. color_pars_fragment: color_pars_fragment,
  7808. color_pars_vertex: color_pars_vertex,
  7809. color_vertex: color_vertex,
  7810. common: common,
  7811. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7812. defaultnormal_vertex: defaultnormal_vertex,
  7813. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7814. displacementmap_vertex: displacementmap_vertex,
  7815. emissivemap_fragment: emissivemap_fragment,
  7816. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7817. encodings_fragment: encodings_fragment,
  7818. encodings_pars_fragment: encodings_pars_fragment,
  7819. envmap_fragment: envmap_fragment,
  7820. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7821. envmap_pars_fragment: envmap_pars_fragment,
  7822. envmap_pars_vertex: envmap_pars_vertex,
  7823. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7824. envmap_vertex: envmap_vertex,
  7825. fog_vertex: fog_vertex,
  7826. fog_pars_vertex: fog_pars_vertex,
  7827. fog_fragment: fog_fragment,
  7828. fog_pars_fragment: fog_pars_fragment,
  7829. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7830. lightmap_fragment: lightmap_fragment,
  7831. lightmap_pars_fragment: lightmap_pars_fragment,
  7832. lights_lambert_fragment: lights_lambert_fragment,
  7833. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7834. lights_pars_begin: lights_pars_begin,
  7835. lights_toon_fragment: lights_toon_fragment,
  7836. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7837. lights_phong_fragment: lights_phong_fragment,
  7838. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7839. lights_physical_fragment: lights_physical_fragment,
  7840. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7841. lights_fragment_begin: lights_fragment_begin,
  7842. lights_fragment_maps: lights_fragment_maps,
  7843. lights_fragment_end: lights_fragment_end,
  7844. logdepthbuf_fragment: logdepthbuf_fragment,
  7845. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7846. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7847. logdepthbuf_vertex: logdepthbuf_vertex,
  7848. map_fragment: map_fragment,
  7849. map_pars_fragment: map_pars_fragment,
  7850. map_particle_fragment: map_particle_fragment,
  7851. map_particle_pars_fragment: map_particle_pars_fragment,
  7852. metalnessmap_fragment: metalnessmap_fragment,
  7853. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7854. morphcolor_vertex: morphcolor_vertex,
  7855. morphnormal_vertex: morphnormal_vertex,
  7856. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7857. morphtarget_vertex: morphtarget_vertex,
  7858. normal_fragment_begin: normal_fragment_begin,
  7859. normal_fragment_maps: normal_fragment_maps,
  7860. normal_pars_fragment: normal_pars_fragment,
  7861. normal_pars_vertex: normal_pars_vertex,
  7862. normal_vertex: normal_vertex,
  7863. normalmap_pars_fragment: normalmap_pars_fragment,
  7864. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7865. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7866. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7867. iridescence_pars_fragment: iridescence_pars_fragment,
  7868. output_fragment: output_fragment,
  7869. packing: packing,
  7870. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7871. project_vertex: project_vertex,
  7872. dithering_fragment: dithering_fragment,
  7873. dithering_pars_fragment: dithering_pars_fragment,
  7874. roughnessmap_fragment: roughnessmap_fragment,
  7875. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7876. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7877. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7878. shadowmap_vertex: shadowmap_vertex,
  7879. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7880. skinbase_vertex: skinbase_vertex,
  7881. skinning_pars_vertex: skinning_pars_vertex,
  7882. skinning_vertex: skinning_vertex,
  7883. skinnormal_vertex: skinnormal_vertex,
  7884. specularmap_fragment: specularmap_fragment,
  7885. specularmap_pars_fragment: specularmap_pars_fragment,
  7886. tonemapping_fragment: tonemapping_fragment,
  7887. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7888. transmission_fragment: transmission_fragment,
  7889. transmission_pars_fragment: transmission_pars_fragment,
  7890. uv_pars_fragment: uv_pars_fragment,
  7891. uv_pars_vertex: uv_pars_vertex,
  7892. uv_vertex: uv_vertex,
  7893. uv2_pars_fragment: uv2_pars_fragment,
  7894. uv2_pars_vertex: uv2_pars_vertex,
  7895. uv2_vertex: uv2_vertex,
  7896. worldpos_vertex: worldpos_vertex,
  7897. background_vert: vertex$h,
  7898. background_frag: fragment$h,
  7899. backgroundCube_vert: vertex$g,
  7900. backgroundCube_frag: fragment$g,
  7901. cube_vert: vertex$f,
  7902. cube_frag: fragment$f,
  7903. depth_vert: vertex$e,
  7904. depth_frag: fragment$e,
  7905. distanceRGBA_vert: vertex$d,
  7906. distanceRGBA_frag: fragment$d,
  7907. equirect_vert: vertex$c,
  7908. equirect_frag: fragment$c,
  7909. linedashed_vert: vertex$b,
  7910. linedashed_frag: fragment$b,
  7911. meshbasic_vert: vertex$a,
  7912. meshbasic_frag: fragment$a,
  7913. meshlambert_vert: vertex$9,
  7914. meshlambert_frag: fragment$9,
  7915. meshmatcap_vert: vertex$8,
  7916. meshmatcap_frag: fragment$8,
  7917. meshnormal_vert: vertex$7,
  7918. meshnormal_frag: fragment$7,
  7919. meshphong_vert: vertex$6,
  7920. meshphong_frag: fragment$6,
  7921. meshphysical_vert: vertex$5,
  7922. meshphysical_frag: fragment$5,
  7923. meshtoon_vert: vertex$4,
  7924. meshtoon_frag: fragment$4,
  7925. points_vert: vertex$3,
  7926. points_frag: fragment$3,
  7927. shadow_vert: vertex$2,
  7928. shadow_frag: fragment$2,
  7929. sprite_vert: vertex$1,
  7930. sprite_frag: fragment$1
  7931. };
  7932. /**
  7933. * Uniforms library for shared webgl shaders
  7934. */
  7935. const UniformsLib = {
  7936. common: {
  7937. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7938. opacity: { value: 1.0 },
  7939. map: { value: null },
  7940. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7941. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7942. alphaMap: { value: null },
  7943. alphaTest: { value: 0 }
  7944. },
  7945. specularmap: {
  7946. specularMap: { value: null },
  7947. },
  7948. envmap: {
  7949. envMap: { value: null },
  7950. flipEnvMap: { value: - 1 },
  7951. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7952. ior: { value: 1.5 }, // physical
  7953. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  7954. },
  7955. aomap: {
  7956. aoMap: { value: null },
  7957. aoMapIntensity: { value: 1 }
  7958. },
  7959. lightmap: {
  7960. lightMap: { value: null },
  7961. lightMapIntensity: { value: 1 }
  7962. },
  7963. emissivemap: {
  7964. emissiveMap: { value: null }
  7965. },
  7966. bumpmap: {
  7967. bumpMap: { value: null },
  7968. bumpScale: { value: 1 }
  7969. },
  7970. normalmap: {
  7971. normalMap: { value: null },
  7972. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  7973. },
  7974. displacementmap: {
  7975. displacementMap: { value: null },
  7976. displacementScale: { value: 1 },
  7977. displacementBias: { value: 0 }
  7978. },
  7979. roughnessmap: {
  7980. roughnessMap: { value: null }
  7981. },
  7982. metalnessmap: {
  7983. metalnessMap: { value: null }
  7984. },
  7985. gradientmap: {
  7986. gradientMap: { value: null }
  7987. },
  7988. fog: {
  7989. fogDensity: { value: 0.00025 },
  7990. fogNear: { value: 1 },
  7991. fogFar: { value: 2000 },
  7992. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  7993. },
  7994. lights: {
  7995. ambientLightColor: { value: [] },
  7996. lightProbe: { value: [] },
  7997. directionalLights: { value: [], properties: {
  7998. direction: {},
  7999. color: {}
  8000. } },
  8001. directionalLightShadows: { value: [], properties: {
  8002. shadowBias: {},
  8003. shadowNormalBias: {},
  8004. shadowRadius: {},
  8005. shadowMapSize: {}
  8006. } },
  8007. directionalShadowMap: { value: [] },
  8008. directionalShadowMatrix: { value: [] },
  8009. spotLights: { value: [], properties: {
  8010. color: {},
  8011. position: {},
  8012. direction: {},
  8013. distance: {},
  8014. coneCos: {},
  8015. penumbraCos: {},
  8016. decay: {}
  8017. } },
  8018. spotLightShadows: { value: [], properties: {
  8019. shadowBias: {},
  8020. shadowNormalBias: {},
  8021. shadowRadius: {},
  8022. shadowMapSize: {}
  8023. } },
  8024. spotLightMap: { value: [] },
  8025. spotShadowMap: { value: [] },
  8026. spotLightMatrix: { value: [] },
  8027. pointLights: { value: [], properties: {
  8028. color: {},
  8029. position: {},
  8030. decay: {},
  8031. distance: {}
  8032. } },
  8033. pointLightShadows: { value: [], properties: {
  8034. shadowBias: {},
  8035. shadowNormalBias: {},
  8036. shadowRadius: {},
  8037. shadowMapSize: {},
  8038. shadowCameraNear: {},
  8039. shadowCameraFar: {}
  8040. } },
  8041. pointShadowMap: { value: [] },
  8042. pointShadowMatrix: { value: [] },
  8043. hemisphereLights: { value: [], properties: {
  8044. direction: {},
  8045. skyColor: {},
  8046. groundColor: {}
  8047. } },
  8048. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8049. rectAreaLights: { value: [], properties: {
  8050. color: {},
  8051. position: {},
  8052. width: {},
  8053. height: {}
  8054. } },
  8055. ltc_1: { value: null },
  8056. ltc_2: { value: null }
  8057. },
  8058. points: {
  8059. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8060. opacity: { value: 1.0 },
  8061. size: { value: 1.0 },
  8062. scale: { value: 1.0 },
  8063. map: { value: null },
  8064. alphaMap: { value: null },
  8065. alphaTest: { value: 0 },
  8066. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8067. },
  8068. sprite: {
  8069. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8070. opacity: { value: 1.0 },
  8071. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8072. rotation: { value: 0.0 },
  8073. map: { value: null },
  8074. alphaMap: { value: null },
  8075. alphaTest: { value: 0 },
  8076. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8077. }
  8078. };
  8079. const ShaderLib = {
  8080. basic: {
  8081. uniforms: /*@__PURE__*/ mergeUniforms( [
  8082. UniformsLib.common,
  8083. UniformsLib.specularmap,
  8084. UniformsLib.envmap,
  8085. UniformsLib.aomap,
  8086. UniformsLib.lightmap,
  8087. UniformsLib.fog
  8088. ] ),
  8089. vertexShader: ShaderChunk.meshbasic_vert,
  8090. fragmentShader: ShaderChunk.meshbasic_frag
  8091. },
  8092. lambert: {
  8093. uniforms: /*@__PURE__*/ mergeUniforms( [
  8094. UniformsLib.common,
  8095. UniformsLib.specularmap,
  8096. UniformsLib.envmap,
  8097. UniformsLib.aomap,
  8098. UniformsLib.lightmap,
  8099. UniformsLib.emissivemap,
  8100. UniformsLib.bumpmap,
  8101. UniformsLib.normalmap,
  8102. UniformsLib.displacementmap,
  8103. UniformsLib.fog,
  8104. UniformsLib.lights,
  8105. {
  8106. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8107. }
  8108. ] ),
  8109. vertexShader: ShaderChunk.meshlambert_vert,
  8110. fragmentShader: ShaderChunk.meshlambert_frag
  8111. },
  8112. phong: {
  8113. uniforms: /*@__PURE__*/ mergeUniforms( [
  8114. UniformsLib.common,
  8115. UniformsLib.specularmap,
  8116. UniformsLib.envmap,
  8117. UniformsLib.aomap,
  8118. UniformsLib.lightmap,
  8119. UniformsLib.emissivemap,
  8120. UniformsLib.bumpmap,
  8121. UniformsLib.normalmap,
  8122. UniformsLib.displacementmap,
  8123. UniformsLib.fog,
  8124. UniformsLib.lights,
  8125. {
  8126. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8127. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8128. shininess: { value: 30 }
  8129. }
  8130. ] ),
  8131. vertexShader: ShaderChunk.meshphong_vert,
  8132. fragmentShader: ShaderChunk.meshphong_frag
  8133. },
  8134. standard: {
  8135. uniforms: /*@__PURE__*/ mergeUniforms( [
  8136. UniformsLib.common,
  8137. UniformsLib.envmap,
  8138. UniformsLib.aomap,
  8139. UniformsLib.lightmap,
  8140. UniformsLib.emissivemap,
  8141. UniformsLib.bumpmap,
  8142. UniformsLib.normalmap,
  8143. UniformsLib.displacementmap,
  8144. UniformsLib.roughnessmap,
  8145. UniformsLib.metalnessmap,
  8146. UniformsLib.fog,
  8147. UniformsLib.lights,
  8148. {
  8149. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8150. roughness: { value: 1.0 },
  8151. metalness: { value: 0.0 },
  8152. envMapIntensity: { value: 1 } // temporary
  8153. }
  8154. ] ),
  8155. vertexShader: ShaderChunk.meshphysical_vert,
  8156. fragmentShader: ShaderChunk.meshphysical_frag
  8157. },
  8158. toon: {
  8159. uniforms: /*@__PURE__*/ mergeUniforms( [
  8160. UniformsLib.common,
  8161. UniformsLib.aomap,
  8162. UniformsLib.lightmap,
  8163. UniformsLib.emissivemap,
  8164. UniformsLib.bumpmap,
  8165. UniformsLib.normalmap,
  8166. UniformsLib.displacementmap,
  8167. UniformsLib.gradientmap,
  8168. UniformsLib.fog,
  8169. UniformsLib.lights,
  8170. {
  8171. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8172. }
  8173. ] ),
  8174. vertexShader: ShaderChunk.meshtoon_vert,
  8175. fragmentShader: ShaderChunk.meshtoon_frag
  8176. },
  8177. matcap: {
  8178. uniforms: /*@__PURE__*/ mergeUniforms( [
  8179. UniformsLib.common,
  8180. UniformsLib.bumpmap,
  8181. UniformsLib.normalmap,
  8182. UniformsLib.displacementmap,
  8183. UniformsLib.fog,
  8184. {
  8185. matcap: { value: null }
  8186. }
  8187. ] ),
  8188. vertexShader: ShaderChunk.meshmatcap_vert,
  8189. fragmentShader: ShaderChunk.meshmatcap_frag
  8190. },
  8191. points: {
  8192. uniforms: /*@__PURE__*/ mergeUniforms( [
  8193. UniformsLib.points,
  8194. UniformsLib.fog
  8195. ] ),
  8196. vertexShader: ShaderChunk.points_vert,
  8197. fragmentShader: ShaderChunk.points_frag
  8198. },
  8199. dashed: {
  8200. uniforms: /*@__PURE__*/ mergeUniforms( [
  8201. UniformsLib.common,
  8202. UniformsLib.fog,
  8203. {
  8204. scale: { value: 1 },
  8205. dashSize: { value: 1 },
  8206. totalSize: { value: 2 }
  8207. }
  8208. ] ),
  8209. vertexShader: ShaderChunk.linedashed_vert,
  8210. fragmentShader: ShaderChunk.linedashed_frag
  8211. },
  8212. depth: {
  8213. uniforms: /*@__PURE__*/ mergeUniforms( [
  8214. UniformsLib.common,
  8215. UniformsLib.displacementmap
  8216. ] ),
  8217. vertexShader: ShaderChunk.depth_vert,
  8218. fragmentShader: ShaderChunk.depth_frag
  8219. },
  8220. normal: {
  8221. uniforms: /*@__PURE__*/ mergeUniforms( [
  8222. UniformsLib.common,
  8223. UniformsLib.bumpmap,
  8224. UniformsLib.normalmap,
  8225. UniformsLib.displacementmap,
  8226. {
  8227. opacity: { value: 1.0 }
  8228. }
  8229. ] ),
  8230. vertexShader: ShaderChunk.meshnormal_vert,
  8231. fragmentShader: ShaderChunk.meshnormal_frag
  8232. },
  8233. sprite: {
  8234. uniforms: /*@__PURE__*/ mergeUniforms( [
  8235. UniformsLib.sprite,
  8236. UniformsLib.fog
  8237. ] ),
  8238. vertexShader: ShaderChunk.sprite_vert,
  8239. fragmentShader: ShaderChunk.sprite_frag
  8240. },
  8241. background: {
  8242. uniforms: {
  8243. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8244. t2D: { value: null },
  8245. backgroundIntensity: { value: 1 }
  8246. },
  8247. vertexShader: ShaderChunk.background_vert,
  8248. fragmentShader: ShaderChunk.background_frag
  8249. },
  8250. backgroundCube: {
  8251. uniforms: {
  8252. envMap: { value: null },
  8253. flipEnvMap: { value: - 1 },
  8254. backgroundBlurriness: { value: 0 },
  8255. backgroundIntensity: { value: 1 }
  8256. },
  8257. vertexShader: ShaderChunk.backgroundCube_vert,
  8258. fragmentShader: ShaderChunk.backgroundCube_frag
  8259. },
  8260. cube: {
  8261. uniforms: {
  8262. tCube: { value: null },
  8263. tFlip: { value: - 1 },
  8264. opacity: { value: 1.0 }
  8265. },
  8266. vertexShader: ShaderChunk.cube_vert,
  8267. fragmentShader: ShaderChunk.cube_frag
  8268. },
  8269. equirect: {
  8270. uniforms: {
  8271. tEquirect: { value: null },
  8272. },
  8273. vertexShader: ShaderChunk.equirect_vert,
  8274. fragmentShader: ShaderChunk.equirect_frag
  8275. },
  8276. distanceRGBA: {
  8277. uniforms: /*@__PURE__*/ mergeUniforms( [
  8278. UniformsLib.common,
  8279. UniformsLib.displacementmap,
  8280. {
  8281. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8282. nearDistance: { value: 1 },
  8283. farDistance: { value: 1000 }
  8284. }
  8285. ] ),
  8286. vertexShader: ShaderChunk.distanceRGBA_vert,
  8287. fragmentShader: ShaderChunk.distanceRGBA_frag
  8288. },
  8289. shadow: {
  8290. uniforms: /*@__PURE__*/ mergeUniforms( [
  8291. UniformsLib.lights,
  8292. UniformsLib.fog,
  8293. {
  8294. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8295. opacity: { value: 1.0 }
  8296. },
  8297. ] ),
  8298. vertexShader: ShaderChunk.shadow_vert,
  8299. fragmentShader: ShaderChunk.shadow_frag
  8300. }
  8301. };
  8302. ShaderLib.physical = {
  8303. uniforms: /*@__PURE__*/ mergeUniforms( [
  8304. ShaderLib.standard.uniforms,
  8305. {
  8306. clearcoat: { value: 0 },
  8307. clearcoatMap: { value: null },
  8308. clearcoatRoughness: { value: 0 },
  8309. clearcoatRoughnessMap: { value: null },
  8310. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8311. clearcoatNormalMap: { value: null },
  8312. iridescence: { value: 0 },
  8313. iridescenceMap: { value: null },
  8314. iridescenceIOR: { value: 1.3 },
  8315. iridescenceThicknessMinimum: { value: 100 },
  8316. iridescenceThicknessMaximum: { value: 400 },
  8317. iridescenceThicknessMap: { value: null },
  8318. sheen: { value: 0 },
  8319. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8320. sheenColorMap: { value: null },
  8321. sheenRoughness: { value: 1 },
  8322. sheenRoughnessMap: { value: null },
  8323. transmission: { value: 0 },
  8324. transmissionMap: { value: null },
  8325. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8326. transmissionSamplerMap: { value: null },
  8327. thickness: { value: 0 },
  8328. thicknessMap: { value: null },
  8329. attenuationDistance: { value: 0 },
  8330. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8331. specularIntensity: { value: 1 },
  8332. specularIntensityMap: { value: null },
  8333. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8334. specularColorMap: { value: null },
  8335. }
  8336. ] ),
  8337. vertexShader: ShaderChunk.meshphysical_vert,
  8338. fragmentShader: ShaderChunk.meshphysical_frag
  8339. };
  8340. const _rgb = { r: 0, b: 0, g: 0 };
  8341. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8342. const clearColor = new Color( 0x000000 );
  8343. let clearAlpha = alpha === true ? 0 : 1;
  8344. let planeMesh;
  8345. let boxMesh;
  8346. let currentBackground = null;
  8347. let currentBackgroundVersion = 0;
  8348. let currentTonemapping = null;
  8349. function render( renderList, scene ) {
  8350. let forceClear = false;
  8351. let background = scene.isScene === true ? scene.background : null;
  8352. if ( background && background.isTexture ) {
  8353. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8354. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8355. }
  8356. // Ignore background in AR
  8357. // TODO: Reconsider this.
  8358. const xr = renderer.xr;
  8359. const session = xr.getSession && xr.getSession();
  8360. if ( session && session.environmentBlendMode === 'additive' ) {
  8361. background = null;
  8362. }
  8363. if ( background === null ) {
  8364. setClear( clearColor, clearAlpha );
  8365. } else if ( background && background.isColor ) {
  8366. setClear( background, 1 );
  8367. forceClear = true;
  8368. }
  8369. if ( renderer.autoClear || forceClear ) {
  8370. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8371. }
  8372. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8373. if ( boxMesh === undefined ) {
  8374. boxMesh = new Mesh(
  8375. new BoxGeometry( 1, 1, 1 ),
  8376. new ShaderMaterial( {
  8377. name: 'BackgroundCubeMaterial',
  8378. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8379. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8380. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8381. side: BackSide,
  8382. depthTest: false,
  8383. depthWrite: false,
  8384. fog: false
  8385. } )
  8386. );
  8387. boxMesh.geometry.deleteAttribute( 'normal' );
  8388. boxMesh.geometry.deleteAttribute( 'uv' );
  8389. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8390. this.matrixWorld.copyPosition( camera.matrixWorld );
  8391. };
  8392. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8393. Object.defineProperty( boxMesh.material, 'envMap', {
  8394. get: function () {
  8395. return this.uniforms.envMap.value;
  8396. }
  8397. } );
  8398. objects.update( boxMesh );
  8399. }
  8400. boxMesh.material.uniforms.envMap.value = background;
  8401. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8402. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8403. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8404. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8405. if ( currentBackground !== background ||
  8406. currentBackgroundVersion !== background.version ||
  8407. currentTonemapping !== renderer.toneMapping ) {
  8408. boxMesh.material.needsUpdate = true;
  8409. currentBackground = background;
  8410. currentBackgroundVersion = background.version;
  8411. currentTonemapping = renderer.toneMapping;
  8412. }
  8413. boxMesh.layers.enableAll();
  8414. // push to the pre-sorted opaque render list
  8415. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8416. } else if ( background && background.isTexture ) {
  8417. if ( planeMesh === undefined ) {
  8418. planeMesh = new Mesh(
  8419. new PlaneGeometry( 2, 2 ),
  8420. new ShaderMaterial( {
  8421. name: 'BackgroundMaterial',
  8422. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8423. vertexShader: ShaderLib.background.vertexShader,
  8424. fragmentShader: ShaderLib.background.fragmentShader,
  8425. side: FrontSide,
  8426. depthTest: false,
  8427. depthWrite: false,
  8428. fog: false
  8429. } )
  8430. );
  8431. planeMesh.geometry.deleteAttribute( 'normal' );
  8432. // add "map" material property so the renderer can evaluate it like for built-in materials
  8433. Object.defineProperty( planeMesh.material, 'map', {
  8434. get: function () {
  8435. return this.uniforms.t2D.value;
  8436. }
  8437. } );
  8438. objects.update( planeMesh );
  8439. }
  8440. planeMesh.material.uniforms.t2D.value = background;
  8441. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8442. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8443. if ( background.matrixAutoUpdate === true ) {
  8444. background.updateMatrix();
  8445. }
  8446. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8447. if ( currentBackground !== background ||
  8448. currentBackgroundVersion !== background.version ||
  8449. currentTonemapping !== renderer.toneMapping ) {
  8450. planeMesh.material.needsUpdate = true;
  8451. currentBackground = background;
  8452. currentBackgroundVersion = background.version;
  8453. currentTonemapping = renderer.toneMapping;
  8454. }
  8455. planeMesh.layers.enableAll();
  8456. // push to the pre-sorted opaque render list
  8457. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8458. }
  8459. }
  8460. function setClear( color, alpha ) {
  8461. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8462. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8463. }
  8464. return {
  8465. getClearColor: function () {
  8466. return clearColor;
  8467. },
  8468. setClearColor: function ( color, alpha = 1 ) {
  8469. clearColor.set( color );
  8470. clearAlpha = alpha;
  8471. setClear( clearColor, clearAlpha );
  8472. },
  8473. getClearAlpha: function () {
  8474. return clearAlpha;
  8475. },
  8476. setClearAlpha: function ( alpha ) {
  8477. clearAlpha = alpha;
  8478. setClear( clearColor, clearAlpha );
  8479. },
  8480. render: render
  8481. };
  8482. }
  8483. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8484. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8485. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8486. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8487. const bindingStates = {};
  8488. const defaultState = createBindingState( null );
  8489. let currentState = defaultState;
  8490. let forceUpdate = false;
  8491. function setup( object, material, program, geometry, index ) {
  8492. let updateBuffers = false;
  8493. if ( vaoAvailable ) {
  8494. const state = getBindingState( geometry, program, material );
  8495. if ( currentState !== state ) {
  8496. currentState = state;
  8497. bindVertexArrayObject( currentState.object );
  8498. }
  8499. updateBuffers = needsUpdate( object, geometry, program, index );
  8500. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8501. } else {
  8502. const wireframe = ( material.wireframe === true );
  8503. if ( currentState.geometry !== geometry.id ||
  8504. currentState.program !== program.id ||
  8505. currentState.wireframe !== wireframe ) {
  8506. currentState.geometry = geometry.id;
  8507. currentState.program = program.id;
  8508. currentState.wireframe = wireframe;
  8509. updateBuffers = true;
  8510. }
  8511. }
  8512. if ( index !== null ) {
  8513. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8514. }
  8515. if ( updateBuffers || forceUpdate ) {
  8516. forceUpdate = false;
  8517. setupVertexAttributes( object, material, program, geometry );
  8518. if ( index !== null ) {
  8519. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8520. }
  8521. }
  8522. }
  8523. function createVertexArrayObject() {
  8524. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8525. return extension.createVertexArrayOES();
  8526. }
  8527. function bindVertexArrayObject( vao ) {
  8528. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8529. return extension.bindVertexArrayOES( vao );
  8530. }
  8531. function deleteVertexArrayObject( vao ) {
  8532. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8533. return extension.deleteVertexArrayOES( vao );
  8534. }
  8535. function getBindingState( geometry, program, material ) {
  8536. const wireframe = ( material.wireframe === true );
  8537. let programMap = bindingStates[ geometry.id ];
  8538. if ( programMap === undefined ) {
  8539. programMap = {};
  8540. bindingStates[ geometry.id ] = programMap;
  8541. }
  8542. let stateMap = programMap[ program.id ];
  8543. if ( stateMap === undefined ) {
  8544. stateMap = {};
  8545. programMap[ program.id ] = stateMap;
  8546. }
  8547. let state = stateMap[ wireframe ];
  8548. if ( state === undefined ) {
  8549. state = createBindingState( createVertexArrayObject() );
  8550. stateMap[ wireframe ] = state;
  8551. }
  8552. return state;
  8553. }
  8554. function createBindingState( vao ) {
  8555. const newAttributes = [];
  8556. const enabledAttributes = [];
  8557. const attributeDivisors = [];
  8558. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8559. newAttributes[ i ] = 0;
  8560. enabledAttributes[ i ] = 0;
  8561. attributeDivisors[ i ] = 0;
  8562. }
  8563. return {
  8564. // for backward compatibility on non-VAO support browser
  8565. geometry: null,
  8566. program: null,
  8567. wireframe: false,
  8568. newAttributes: newAttributes,
  8569. enabledAttributes: enabledAttributes,
  8570. attributeDivisors: attributeDivisors,
  8571. object: vao,
  8572. attributes: {},
  8573. index: null
  8574. };
  8575. }
  8576. function needsUpdate( object, geometry, program, index ) {
  8577. const cachedAttributes = currentState.attributes;
  8578. const geometryAttributes = geometry.attributes;
  8579. let attributesNum = 0;
  8580. const programAttributes = program.getAttributes();
  8581. for ( const name in programAttributes ) {
  8582. const programAttribute = programAttributes[ name ];
  8583. if ( programAttribute.location >= 0 ) {
  8584. const cachedAttribute = cachedAttributes[ name ];
  8585. let geometryAttribute = geometryAttributes[ name ];
  8586. if ( geometryAttribute === undefined ) {
  8587. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8588. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8589. }
  8590. if ( cachedAttribute === undefined ) return true;
  8591. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8592. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8593. attributesNum ++;
  8594. }
  8595. }
  8596. if ( currentState.attributesNum !== attributesNum ) return true;
  8597. if ( currentState.index !== index ) return true;
  8598. return false;
  8599. }
  8600. function saveCache( object, geometry, program, index ) {
  8601. const cache = {};
  8602. const attributes = geometry.attributes;
  8603. let attributesNum = 0;
  8604. const programAttributes = program.getAttributes();
  8605. for ( const name in programAttributes ) {
  8606. const programAttribute = programAttributes[ name ];
  8607. if ( programAttribute.location >= 0 ) {
  8608. let attribute = attributes[ name ];
  8609. if ( attribute === undefined ) {
  8610. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8611. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8612. }
  8613. const data = {};
  8614. data.attribute = attribute;
  8615. if ( attribute && attribute.data ) {
  8616. data.data = attribute.data;
  8617. }
  8618. cache[ name ] = data;
  8619. attributesNum ++;
  8620. }
  8621. }
  8622. currentState.attributes = cache;
  8623. currentState.attributesNum = attributesNum;
  8624. currentState.index = index;
  8625. }
  8626. function initAttributes() {
  8627. const newAttributes = currentState.newAttributes;
  8628. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8629. newAttributes[ i ] = 0;
  8630. }
  8631. }
  8632. function enableAttribute( attribute ) {
  8633. enableAttributeAndDivisor( attribute, 0 );
  8634. }
  8635. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8636. const newAttributes = currentState.newAttributes;
  8637. const enabledAttributes = currentState.enabledAttributes;
  8638. const attributeDivisors = currentState.attributeDivisors;
  8639. newAttributes[ attribute ] = 1;
  8640. if ( enabledAttributes[ attribute ] === 0 ) {
  8641. gl.enableVertexAttribArray( attribute );
  8642. enabledAttributes[ attribute ] = 1;
  8643. }
  8644. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8645. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8646. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8647. attributeDivisors[ attribute ] = meshPerAttribute;
  8648. }
  8649. }
  8650. function disableUnusedAttributes() {
  8651. const newAttributes = currentState.newAttributes;
  8652. const enabledAttributes = currentState.enabledAttributes;
  8653. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8654. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8655. gl.disableVertexAttribArray( i );
  8656. enabledAttributes[ i ] = 0;
  8657. }
  8658. }
  8659. }
  8660. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8661. if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) {
  8662. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8663. } else {
  8664. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8665. }
  8666. }
  8667. function setupVertexAttributes( object, material, program, geometry ) {
  8668. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8669. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8670. }
  8671. initAttributes();
  8672. const geometryAttributes = geometry.attributes;
  8673. const programAttributes = program.getAttributes();
  8674. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8675. for ( const name in programAttributes ) {
  8676. const programAttribute = programAttributes[ name ];
  8677. if ( programAttribute.location >= 0 ) {
  8678. let geometryAttribute = geometryAttributes[ name ];
  8679. if ( geometryAttribute === undefined ) {
  8680. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8681. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8682. }
  8683. if ( geometryAttribute !== undefined ) {
  8684. const normalized = geometryAttribute.normalized;
  8685. const size = geometryAttribute.itemSize;
  8686. const attribute = attributes.get( geometryAttribute );
  8687. // TODO Attribute may not be available on context restore
  8688. if ( attribute === undefined ) continue;
  8689. const buffer = attribute.buffer;
  8690. const type = attribute.type;
  8691. const bytesPerElement = attribute.bytesPerElement;
  8692. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8693. const data = geometryAttribute.data;
  8694. const stride = data.stride;
  8695. const offset = geometryAttribute.offset;
  8696. if ( data.isInstancedInterleavedBuffer ) {
  8697. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8698. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8699. }
  8700. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8701. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8702. }
  8703. } else {
  8704. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8705. enableAttribute( programAttribute.location + i );
  8706. }
  8707. }
  8708. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8709. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8710. vertexAttribPointer(
  8711. programAttribute.location + i,
  8712. size / programAttribute.locationSize,
  8713. type,
  8714. normalized,
  8715. stride * bytesPerElement,
  8716. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8717. );
  8718. }
  8719. } else {
  8720. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8721. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8722. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8723. }
  8724. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8725. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8726. }
  8727. } else {
  8728. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8729. enableAttribute( programAttribute.location + i );
  8730. }
  8731. }
  8732. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8733. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8734. vertexAttribPointer(
  8735. programAttribute.location + i,
  8736. size / programAttribute.locationSize,
  8737. type,
  8738. normalized,
  8739. size * bytesPerElement,
  8740. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8741. );
  8742. }
  8743. }
  8744. } else if ( materialDefaultAttributeValues !== undefined ) {
  8745. const value = materialDefaultAttributeValues[ name ];
  8746. if ( value !== undefined ) {
  8747. switch ( value.length ) {
  8748. case 2:
  8749. gl.vertexAttrib2fv( programAttribute.location, value );
  8750. break;
  8751. case 3:
  8752. gl.vertexAttrib3fv( programAttribute.location, value );
  8753. break;
  8754. case 4:
  8755. gl.vertexAttrib4fv( programAttribute.location, value );
  8756. break;
  8757. default:
  8758. gl.vertexAttrib1fv( programAttribute.location, value );
  8759. }
  8760. }
  8761. }
  8762. }
  8763. }
  8764. disableUnusedAttributes();
  8765. }
  8766. function dispose() {
  8767. reset();
  8768. for ( const geometryId in bindingStates ) {
  8769. const programMap = bindingStates[ geometryId ];
  8770. for ( const programId in programMap ) {
  8771. const stateMap = programMap[ programId ];
  8772. for ( const wireframe in stateMap ) {
  8773. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8774. delete stateMap[ wireframe ];
  8775. }
  8776. delete programMap[ programId ];
  8777. }
  8778. delete bindingStates[ geometryId ];
  8779. }
  8780. }
  8781. function releaseStatesOfGeometry( geometry ) {
  8782. if ( bindingStates[ geometry.id ] === undefined ) return;
  8783. const programMap = bindingStates[ geometry.id ];
  8784. for ( const programId in programMap ) {
  8785. const stateMap = programMap[ programId ];
  8786. for ( const wireframe in stateMap ) {
  8787. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8788. delete stateMap[ wireframe ];
  8789. }
  8790. delete programMap[ programId ];
  8791. }
  8792. delete bindingStates[ geometry.id ];
  8793. }
  8794. function releaseStatesOfProgram( program ) {
  8795. for ( const geometryId in bindingStates ) {
  8796. const programMap = bindingStates[ geometryId ];
  8797. if ( programMap[ program.id ] === undefined ) continue;
  8798. const stateMap = programMap[ program.id ];
  8799. for ( const wireframe in stateMap ) {
  8800. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8801. delete stateMap[ wireframe ];
  8802. }
  8803. delete programMap[ program.id ];
  8804. }
  8805. }
  8806. function reset() {
  8807. resetDefaultState();
  8808. forceUpdate = true;
  8809. if ( currentState === defaultState ) return;
  8810. currentState = defaultState;
  8811. bindVertexArrayObject( currentState.object );
  8812. }
  8813. // for backward-compatibility
  8814. function resetDefaultState() {
  8815. defaultState.geometry = null;
  8816. defaultState.program = null;
  8817. defaultState.wireframe = false;
  8818. }
  8819. return {
  8820. setup: setup,
  8821. reset: reset,
  8822. resetDefaultState: resetDefaultState,
  8823. dispose: dispose,
  8824. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8825. releaseStatesOfProgram: releaseStatesOfProgram,
  8826. initAttributes: initAttributes,
  8827. enableAttribute: enableAttribute,
  8828. disableUnusedAttributes: disableUnusedAttributes
  8829. };
  8830. }
  8831. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8832. const isWebGL2 = capabilities.isWebGL2;
  8833. let mode;
  8834. function setMode( value ) {
  8835. mode = value;
  8836. }
  8837. function render( start, count ) {
  8838. gl.drawArrays( mode, start, count );
  8839. info.update( count, mode, 1 );
  8840. }
  8841. function renderInstances( start, count, primcount ) {
  8842. if ( primcount === 0 ) return;
  8843. let extension, methodName;
  8844. if ( isWebGL2 ) {
  8845. extension = gl;
  8846. methodName = 'drawArraysInstanced';
  8847. } else {
  8848. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8849. methodName = 'drawArraysInstancedANGLE';
  8850. if ( extension === null ) {
  8851. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8852. return;
  8853. }
  8854. }
  8855. extension[ methodName ]( mode, start, count, primcount );
  8856. info.update( count, mode, primcount );
  8857. }
  8858. //
  8859. this.setMode = setMode;
  8860. this.render = render;
  8861. this.renderInstances = renderInstances;
  8862. }
  8863. function WebGLCapabilities( gl, extensions, parameters ) {
  8864. let maxAnisotropy;
  8865. function getMaxAnisotropy() {
  8866. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8867. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8868. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8869. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8870. } else {
  8871. maxAnisotropy = 0;
  8872. }
  8873. return maxAnisotropy;
  8874. }
  8875. function getMaxPrecision( precision ) {
  8876. if ( precision === 'highp' ) {
  8877. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  8878. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  8879. return 'highp';
  8880. }
  8881. precision = 'mediump';
  8882. }
  8883. if ( precision === 'mediump' ) {
  8884. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  8885. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  8886. return 'mediump';
  8887. }
  8888. }
  8889. return 'lowp';
  8890. }
  8891. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  8892. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8893. const maxPrecision = getMaxPrecision( precision );
  8894. if ( maxPrecision !== precision ) {
  8895. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8896. precision = maxPrecision;
  8897. }
  8898. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8899. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8900. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  8901. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  8902. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  8903. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  8904. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8905. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  8906. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  8907. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  8908. const vertexTextures = maxVertexTextures > 0;
  8909. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8910. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8911. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  8912. return {
  8913. isWebGL2: isWebGL2,
  8914. drawBuffers: drawBuffers,
  8915. getMaxAnisotropy: getMaxAnisotropy,
  8916. getMaxPrecision: getMaxPrecision,
  8917. precision: precision,
  8918. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8919. maxTextures: maxTextures,
  8920. maxVertexTextures: maxVertexTextures,
  8921. maxTextureSize: maxTextureSize,
  8922. maxCubemapSize: maxCubemapSize,
  8923. maxAttributes: maxAttributes,
  8924. maxVertexUniforms: maxVertexUniforms,
  8925. maxVaryings: maxVaryings,
  8926. maxFragmentUniforms: maxFragmentUniforms,
  8927. vertexTextures: vertexTextures,
  8928. floatFragmentTextures: floatFragmentTextures,
  8929. floatVertexTextures: floatVertexTextures,
  8930. maxSamples: maxSamples
  8931. };
  8932. }
  8933. function WebGLClipping( properties ) {
  8934. const scope = this;
  8935. let globalState = null,
  8936. numGlobalPlanes = 0,
  8937. localClippingEnabled = false,
  8938. renderingShadows = false;
  8939. const plane = new Plane(),
  8940. viewNormalMatrix = new Matrix3(),
  8941. uniform = { value: null, needsUpdate: false };
  8942. this.uniform = uniform;
  8943. this.numPlanes = 0;
  8944. this.numIntersection = 0;
  8945. this.init = function ( planes, enableLocalClipping ) {
  8946. const enabled =
  8947. planes.length !== 0 ||
  8948. enableLocalClipping ||
  8949. // enable state of previous frame - the clipping code has to
  8950. // run another frame in order to reset the state:
  8951. numGlobalPlanes !== 0 ||
  8952. localClippingEnabled;
  8953. localClippingEnabled = enableLocalClipping;
  8954. numGlobalPlanes = planes.length;
  8955. return enabled;
  8956. };
  8957. this.beginShadows = function () {
  8958. renderingShadows = true;
  8959. projectPlanes( null );
  8960. };
  8961. this.endShadows = function () {
  8962. renderingShadows = false;
  8963. };
  8964. this.setGlobalState = function ( planes, camera ) {
  8965. globalState = projectPlanes( planes, camera, 0 );
  8966. };
  8967. this.setState = function ( material, camera, useCache ) {
  8968. const planes = material.clippingPlanes,
  8969. clipIntersection = material.clipIntersection,
  8970. clipShadows = material.clipShadows;
  8971. const materialProperties = properties.get( material );
  8972. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8973. // there's no local clipping
  8974. if ( renderingShadows ) {
  8975. // there's no global clipping
  8976. projectPlanes( null );
  8977. } else {
  8978. resetGlobalState();
  8979. }
  8980. } else {
  8981. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8982. lGlobal = nGlobal * 4;
  8983. let dstArray = materialProperties.clippingState || null;
  8984. uniform.value = dstArray; // ensure unique state
  8985. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8986. for ( let i = 0; i !== lGlobal; ++ i ) {
  8987. dstArray[ i ] = globalState[ i ];
  8988. }
  8989. materialProperties.clippingState = dstArray;
  8990. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8991. this.numPlanes += nGlobal;
  8992. }
  8993. };
  8994. function resetGlobalState() {
  8995. if ( uniform.value !== globalState ) {
  8996. uniform.value = globalState;
  8997. uniform.needsUpdate = numGlobalPlanes > 0;
  8998. }
  8999. scope.numPlanes = numGlobalPlanes;
  9000. scope.numIntersection = 0;
  9001. }
  9002. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9003. const nPlanes = planes !== null ? planes.length : 0;
  9004. let dstArray = null;
  9005. if ( nPlanes !== 0 ) {
  9006. dstArray = uniform.value;
  9007. if ( skipTransform !== true || dstArray === null ) {
  9008. const flatSize = dstOffset + nPlanes * 4,
  9009. viewMatrix = camera.matrixWorldInverse;
  9010. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9011. if ( dstArray === null || dstArray.length < flatSize ) {
  9012. dstArray = new Float32Array( flatSize );
  9013. }
  9014. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9015. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9016. plane.normal.toArray( dstArray, i4 );
  9017. dstArray[ i4 + 3 ] = plane.constant;
  9018. }
  9019. }
  9020. uniform.value = dstArray;
  9021. uniform.needsUpdate = true;
  9022. }
  9023. scope.numPlanes = nPlanes;
  9024. scope.numIntersection = 0;
  9025. return dstArray;
  9026. }
  9027. }
  9028. function WebGLCubeMaps( renderer ) {
  9029. let cubemaps = new WeakMap();
  9030. function mapTextureMapping( texture, mapping ) {
  9031. if ( mapping === EquirectangularReflectionMapping ) {
  9032. texture.mapping = CubeReflectionMapping;
  9033. } else if ( mapping === EquirectangularRefractionMapping ) {
  9034. texture.mapping = CubeRefractionMapping;
  9035. }
  9036. return texture;
  9037. }
  9038. function get( texture ) {
  9039. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9040. const mapping = texture.mapping;
  9041. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9042. if ( cubemaps.has( texture ) ) {
  9043. const cubemap = cubemaps.get( texture ).texture;
  9044. return mapTextureMapping( cubemap, texture.mapping );
  9045. } else {
  9046. const image = texture.image;
  9047. if ( image && image.height > 0 ) {
  9048. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9049. renderTarget.fromEquirectangularTexture( renderer, texture );
  9050. cubemaps.set( texture, renderTarget );
  9051. texture.addEventListener( 'dispose', onTextureDispose );
  9052. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9053. } else {
  9054. // image not yet ready. try the conversion next frame
  9055. return null;
  9056. }
  9057. }
  9058. }
  9059. }
  9060. return texture;
  9061. }
  9062. function onTextureDispose( event ) {
  9063. const texture = event.target;
  9064. texture.removeEventListener( 'dispose', onTextureDispose );
  9065. const cubemap = cubemaps.get( texture );
  9066. if ( cubemap !== undefined ) {
  9067. cubemaps.delete( texture );
  9068. cubemap.dispose();
  9069. }
  9070. }
  9071. function dispose() {
  9072. cubemaps = new WeakMap();
  9073. }
  9074. return {
  9075. get: get,
  9076. dispose: dispose
  9077. };
  9078. }
  9079. class OrthographicCamera extends Camera {
  9080. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9081. super();
  9082. this.isOrthographicCamera = true;
  9083. this.type = 'OrthographicCamera';
  9084. this.zoom = 1;
  9085. this.view = null;
  9086. this.left = left;
  9087. this.right = right;
  9088. this.top = top;
  9089. this.bottom = bottom;
  9090. this.near = near;
  9091. this.far = far;
  9092. this.updateProjectionMatrix();
  9093. }
  9094. copy( source, recursive ) {
  9095. super.copy( source, recursive );
  9096. this.left = source.left;
  9097. this.right = source.right;
  9098. this.top = source.top;
  9099. this.bottom = source.bottom;
  9100. this.near = source.near;
  9101. this.far = source.far;
  9102. this.zoom = source.zoom;
  9103. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9104. return this;
  9105. }
  9106. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9107. if ( this.view === null ) {
  9108. this.view = {
  9109. enabled: true,
  9110. fullWidth: 1,
  9111. fullHeight: 1,
  9112. offsetX: 0,
  9113. offsetY: 0,
  9114. width: 1,
  9115. height: 1
  9116. };
  9117. }
  9118. this.view.enabled = true;
  9119. this.view.fullWidth = fullWidth;
  9120. this.view.fullHeight = fullHeight;
  9121. this.view.offsetX = x;
  9122. this.view.offsetY = y;
  9123. this.view.width = width;
  9124. this.view.height = height;
  9125. this.updateProjectionMatrix();
  9126. }
  9127. clearViewOffset() {
  9128. if ( this.view !== null ) {
  9129. this.view.enabled = false;
  9130. }
  9131. this.updateProjectionMatrix();
  9132. }
  9133. updateProjectionMatrix() {
  9134. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9135. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9136. const cx = ( this.right + this.left ) / 2;
  9137. const cy = ( this.top + this.bottom ) / 2;
  9138. let left = cx - dx;
  9139. let right = cx + dx;
  9140. let top = cy + dy;
  9141. let bottom = cy - dy;
  9142. if ( this.view !== null && this.view.enabled ) {
  9143. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9144. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9145. left += scaleW * this.view.offsetX;
  9146. right = left + scaleW * this.view.width;
  9147. top -= scaleH * this.view.offsetY;
  9148. bottom = top - scaleH * this.view.height;
  9149. }
  9150. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9151. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9152. }
  9153. toJSON( meta ) {
  9154. const data = super.toJSON( meta );
  9155. data.object.zoom = this.zoom;
  9156. data.object.left = this.left;
  9157. data.object.right = this.right;
  9158. data.object.top = this.top;
  9159. data.object.bottom = this.bottom;
  9160. data.object.near = this.near;
  9161. data.object.far = this.far;
  9162. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9163. return data;
  9164. }
  9165. }
  9166. const LOD_MIN = 4;
  9167. // The standard deviations (radians) associated with the extra mips. These are
  9168. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9169. // geometric shadowing function. These sigma values squared must match the
  9170. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9171. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9172. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9173. // samples and exit early, but not recompile the shader.
  9174. const MAX_SAMPLES = 20;
  9175. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9176. const _clearColor = /*@__PURE__*/ new Color();
  9177. let _oldTarget = null;
  9178. // Golden Ratio
  9179. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9180. const INV_PHI = 1 / PHI;
  9181. // Vertices of a dodecahedron (except the opposites, which represent the
  9182. // same axis), used as axis directions evenly spread on a sphere.
  9183. const _axisDirections = [
  9184. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9185. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9186. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9187. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9188. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9189. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9190. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9191. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9192. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9193. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9194. /**
  9195. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9196. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9197. * blur to be quickly accessed based on material roughness. It is packed into a
  9198. * special CubeUV format that allows us to perform custom interpolation so that
  9199. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9200. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9201. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9202. * higher roughness levels. In this way we maintain resolution to smoothly
  9203. * interpolate diffuse lighting while limiting sampling computation.
  9204. *
  9205. * Paper: Fast, Accurate Image-Based Lighting
  9206. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9207. */
  9208. class PMREMGenerator {
  9209. constructor( renderer ) {
  9210. this._renderer = renderer;
  9211. this._pingPongRenderTarget = null;
  9212. this._lodMax = 0;
  9213. this._cubeSize = 0;
  9214. this._lodPlanes = [];
  9215. this._sizeLods = [];
  9216. this._sigmas = [];
  9217. this._blurMaterial = null;
  9218. this._cubemapMaterial = null;
  9219. this._equirectMaterial = null;
  9220. this._compileMaterial( this._blurMaterial );
  9221. }
  9222. /**
  9223. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9224. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9225. * in radians to be applied to the scene before PMREM generation. Optional near
  9226. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9227. * is placed at the origin).
  9228. */
  9229. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9230. _oldTarget = this._renderer.getRenderTarget();
  9231. this._setSize( 256 );
  9232. const cubeUVRenderTarget = this._allocateTargets();
  9233. cubeUVRenderTarget.depthBuffer = true;
  9234. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9235. if ( sigma > 0 ) {
  9236. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9237. }
  9238. this._applyPMREM( cubeUVRenderTarget );
  9239. this._cleanup( cubeUVRenderTarget );
  9240. return cubeUVRenderTarget;
  9241. }
  9242. /**
  9243. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9244. * or HDR. The ideal input image size is 1k (1024 x 512),
  9245. * as this matches best with the 256 x 256 cubemap output.
  9246. */
  9247. fromEquirectangular( equirectangular, renderTarget = null ) {
  9248. return this._fromTexture( equirectangular, renderTarget );
  9249. }
  9250. /**
  9251. * Generates a PMREM from an cubemap texture, which can be either LDR
  9252. * or HDR. The ideal input cube size is 256 x 256,
  9253. * as this matches best with the 256 x 256 cubemap output.
  9254. */
  9255. fromCubemap( cubemap, renderTarget = null ) {
  9256. return this._fromTexture( cubemap, renderTarget );
  9257. }
  9258. /**
  9259. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9260. * your texture's network fetch for increased concurrency.
  9261. */
  9262. compileCubemapShader() {
  9263. if ( this._cubemapMaterial === null ) {
  9264. this._cubemapMaterial = _getCubemapMaterial();
  9265. this._compileMaterial( this._cubemapMaterial );
  9266. }
  9267. }
  9268. /**
  9269. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9270. * your texture's network fetch for increased concurrency.
  9271. */
  9272. compileEquirectangularShader() {
  9273. if ( this._equirectMaterial === null ) {
  9274. this._equirectMaterial = _getEquirectMaterial();
  9275. this._compileMaterial( this._equirectMaterial );
  9276. }
  9277. }
  9278. /**
  9279. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9280. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9281. * one of them will cause any others to also become unusable.
  9282. */
  9283. dispose() {
  9284. this._dispose();
  9285. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9286. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9287. }
  9288. // private interface
  9289. _setSize( cubeSize ) {
  9290. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9291. this._cubeSize = Math.pow( 2, this._lodMax );
  9292. }
  9293. _dispose() {
  9294. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9295. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9296. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9297. this._lodPlanes[ i ].dispose();
  9298. }
  9299. }
  9300. _cleanup( outputTarget ) {
  9301. this._renderer.setRenderTarget( _oldTarget );
  9302. outputTarget.scissorTest = false;
  9303. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9304. }
  9305. _fromTexture( texture, renderTarget ) {
  9306. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9307. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9308. } else { // Equirectangular
  9309. this._setSize( texture.image.width / 4 );
  9310. }
  9311. _oldTarget = this._renderer.getRenderTarget();
  9312. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9313. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9314. this._applyPMREM( cubeUVRenderTarget );
  9315. this._cleanup( cubeUVRenderTarget );
  9316. return cubeUVRenderTarget;
  9317. }
  9318. _allocateTargets() {
  9319. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9320. const height = 4 * this._cubeSize;
  9321. const params = {
  9322. magFilter: LinearFilter,
  9323. minFilter: LinearFilter,
  9324. generateMipmaps: false,
  9325. type: HalfFloatType,
  9326. format: RGBAFormat,
  9327. encoding: LinearEncoding,
  9328. depthBuffer: false
  9329. };
  9330. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9331. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9332. if ( this._pingPongRenderTarget !== null ) {
  9333. this._dispose();
  9334. }
  9335. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9336. const { _lodMax } = this;
  9337. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9338. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9339. }
  9340. return cubeUVRenderTarget;
  9341. }
  9342. _compileMaterial( material ) {
  9343. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9344. this._renderer.compile( tmpMesh, _flatCamera );
  9345. }
  9346. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9347. const fov = 90;
  9348. const aspect = 1;
  9349. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9350. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9351. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9352. const renderer = this._renderer;
  9353. const originalAutoClear = renderer.autoClear;
  9354. const toneMapping = renderer.toneMapping;
  9355. renderer.getClearColor( _clearColor );
  9356. renderer.toneMapping = NoToneMapping;
  9357. renderer.autoClear = false;
  9358. const backgroundMaterial = new MeshBasicMaterial( {
  9359. name: 'PMREM.Background',
  9360. side: BackSide,
  9361. depthWrite: false,
  9362. depthTest: false,
  9363. } );
  9364. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9365. let useSolidColor = false;
  9366. const background = scene.background;
  9367. if ( background ) {
  9368. if ( background.isColor ) {
  9369. backgroundMaterial.color.copy( background );
  9370. scene.background = null;
  9371. useSolidColor = true;
  9372. }
  9373. } else {
  9374. backgroundMaterial.color.copy( _clearColor );
  9375. useSolidColor = true;
  9376. }
  9377. for ( let i = 0; i < 6; i ++ ) {
  9378. const col = i % 3;
  9379. if ( col === 0 ) {
  9380. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9381. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9382. } else if ( col === 1 ) {
  9383. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9384. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9385. } else {
  9386. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9387. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9388. }
  9389. const size = this._cubeSize;
  9390. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9391. renderer.setRenderTarget( cubeUVRenderTarget );
  9392. if ( useSolidColor ) {
  9393. renderer.render( backgroundBox, cubeCamera );
  9394. }
  9395. renderer.render( scene, cubeCamera );
  9396. }
  9397. backgroundBox.geometry.dispose();
  9398. backgroundBox.material.dispose();
  9399. renderer.toneMapping = toneMapping;
  9400. renderer.autoClear = originalAutoClear;
  9401. scene.background = background;
  9402. }
  9403. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9404. const renderer = this._renderer;
  9405. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9406. if ( isCubeTexture ) {
  9407. if ( this._cubemapMaterial === null ) {
  9408. this._cubemapMaterial = _getCubemapMaterial();
  9409. }
  9410. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9411. } else {
  9412. if ( this._equirectMaterial === null ) {
  9413. this._equirectMaterial = _getEquirectMaterial();
  9414. }
  9415. }
  9416. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9417. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9418. const uniforms = material.uniforms;
  9419. uniforms[ 'envMap' ].value = texture;
  9420. const size = this._cubeSize;
  9421. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9422. renderer.setRenderTarget( cubeUVRenderTarget );
  9423. renderer.render( mesh, _flatCamera );
  9424. }
  9425. _applyPMREM( cubeUVRenderTarget ) {
  9426. const renderer = this._renderer;
  9427. const autoClear = renderer.autoClear;
  9428. renderer.autoClear = false;
  9429. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9430. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9431. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9432. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9433. }
  9434. renderer.autoClear = autoClear;
  9435. }
  9436. /**
  9437. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9438. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9439. * the blur latitudinally (around the poles), and then longitudinally (towards
  9440. * the poles) to approximate the orthogonally-separable blur. It is least
  9441. * accurate at the poles, but still does a decent job.
  9442. */
  9443. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9444. const pingPongRenderTarget = this._pingPongRenderTarget;
  9445. this._halfBlur(
  9446. cubeUVRenderTarget,
  9447. pingPongRenderTarget,
  9448. lodIn,
  9449. lodOut,
  9450. sigma,
  9451. 'latitudinal',
  9452. poleAxis );
  9453. this._halfBlur(
  9454. pingPongRenderTarget,
  9455. cubeUVRenderTarget,
  9456. lodOut,
  9457. lodOut,
  9458. sigma,
  9459. 'longitudinal',
  9460. poleAxis );
  9461. }
  9462. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9463. const renderer = this._renderer;
  9464. const blurMaterial = this._blurMaterial;
  9465. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9466. console.error(
  9467. 'blur direction must be either latitudinal or longitudinal!' );
  9468. }
  9469. // Number of standard deviations at which to cut off the discrete approximation.
  9470. const STANDARD_DEVIATIONS = 3;
  9471. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9472. const blurUniforms = blurMaterial.uniforms;
  9473. const pixels = this._sizeLods[ lodIn ] - 1;
  9474. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9475. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9476. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9477. if ( samples > MAX_SAMPLES ) {
  9478. console.warn( `sigmaRadians, ${
  9479. sigmaRadians}, is too large and will clip, as it requested ${
  9480. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9481. }
  9482. const weights = [];
  9483. let sum = 0;
  9484. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9485. const x = i / sigmaPixels;
  9486. const weight = Math.exp( - x * x / 2 );
  9487. weights.push( weight );
  9488. if ( i === 0 ) {
  9489. sum += weight;
  9490. } else if ( i < samples ) {
  9491. sum += 2 * weight;
  9492. }
  9493. }
  9494. for ( let i = 0; i < weights.length; i ++ ) {
  9495. weights[ i ] = weights[ i ] / sum;
  9496. }
  9497. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9498. blurUniforms[ 'samples' ].value = samples;
  9499. blurUniforms[ 'weights' ].value = weights;
  9500. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9501. if ( poleAxis ) {
  9502. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9503. }
  9504. const { _lodMax } = this;
  9505. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9506. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9507. const outputSize = this._sizeLods[ lodOut ];
  9508. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9509. const y = 4 * ( this._cubeSize - outputSize );
  9510. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9511. renderer.setRenderTarget( targetOut );
  9512. renderer.render( blurMesh, _flatCamera );
  9513. }
  9514. }
  9515. function _createPlanes( lodMax ) {
  9516. const lodPlanes = [];
  9517. const sizeLods = [];
  9518. const sigmas = [];
  9519. let lod = lodMax;
  9520. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9521. for ( let i = 0; i < totalLods; i ++ ) {
  9522. const sizeLod = Math.pow( 2, lod );
  9523. sizeLods.push( sizeLod );
  9524. let sigma = 1.0 / sizeLod;
  9525. if ( i > lodMax - LOD_MIN ) {
  9526. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9527. } else if ( i === 0 ) {
  9528. sigma = 0;
  9529. }
  9530. sigmas.push( sigma );
  9531. const texelSize = 1.0 / ( sizeLod - 2 );
  9532. const min = - texelSize;
  9533. const max = 1 + texelSize;
  9534. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9535. const cubeFaces = 6;
  9536. const vertices = 6;
  9537. const positionSize = 3;
  9538. const uvSize = 2;
  9539. const faceIndexSize = 1;
  9540. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9541. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9542. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9543. for ( let face = 0; face < cubeFaces; face ++ ) {
  9544. const x = ( face % 3 ) * 2 / 3 - 1;
  9545. const y = face > 2 ? 0 : - 1;
  9546. const coordinates = [
  9547. x, y, 0,
  9548. x + 2 / 3, y, 0,
  9549. x + 2 / 3, y + 1, 0,
  9550. x, y, 0,
  9551. x + 2 / 3, y + 1, 0,
  9552. x, y + 1, 0
  9553. ];
  9554. position.set( coordinates, positionSize * vertices * face );
  9555. uv.set( uv1, uvSize * vertices * face );
  9556. const fill = [ face, face, face, face, face, face ];
  9557. faceIndex.set( fill, faceIndexSize * vertices * face );
  9558. }
  9559. const planes = new BufferGeometry();
  9560. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9561. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9562. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9563. lodPlanes.push( planes );
  9564. if ( lod > LOD_MIN ) {
  9565. lod --;
  9566. }
  9567. }
  9568. return { lodPlanes, sizeLods, sigmas };
  9569. }
  9570. function _createRenderTarget( width, height, params ) {
  9571. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9572. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9573. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9574. cubeUVRenderTarget.scissorTest = true;
  9575. return cubeUVRenderTarget;
  9576. }
  9577. function _setViewport( target, x, y, width, height ) {
  9578. target.viewport.set( x, y, width, height );
  9579. target.scissor.set( x, y, width, height );
  9580. }
  9581. function _getBlurShader( lodMax, width, height ) {
  9582. const weights = new Float32Array( MAX_SAMPLES );
  9583. const poleAxis = new Vector3( 0, 1, 0 );
  9584. const shaderMaterial = new ShaderMaterial( {
  9585. name: 'SphericalGaussianBlur',
  9586. defines: {
  9587. 'n': MAX_SAMPLES,
  9588. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9589. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9590. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9591. },
  9592. uniforms: {
  9593. 'envMap': { value: null },
  9594. 'samples': { value: 1 },
  9595. 'weights': { value: weights },
  9596. 'latitudinal': { value: false },
  9597. 'dTheta': { value: 0 },
  9598. 'mipInt': { value: 0 },
  9599. 'poleAxis': { value: poleAxis }
  9600. },
  9601. vertexShader: _getCommonVertexShader(),
  9602. fragmentShader: /* glsl */`
  9603. precision mediump float;
  9604. precision mediump int;
  9605. varying vec3 vOutputDirection;
  9606. uniform sampler2D envMap;
  9607. uniform int samples;
  9608. uniform float weights[ n ];
  9609. uniform bool latitudinal;
  9610. uniform float dTheta;
  9611. uniform float mipInt;
  9612. uniform vec3 poleAxis;
  9613. #define ENVMAP_TYPE_CUBE_UV
  9614. #include <cube_uv_reflection_fragment>
  9615. vec3 getSample( float theta, vec3 axis ) {
  9616. float cosTheta = cos( theta );
  9617. // Rodrigues' axis-angle rotation
  9618. vec3 sampleDirection = vOutputDirection * cosTheta
  9619. + cross( axis, vOutputDirection ) * sin( theta )
  9620. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9621. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9622. }
  9623. void main() {
  9624. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9625. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9626. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9627. }
  9628. axis = normalize( axis );
  9629. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9630. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9631. for ( int i = 1; i < n; i++ ) {
  9632. if ( i >= samples ) {
  9633. break;
  9634. }
  9635. float theta = dTheta * float( i );
  9636. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9637. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9638. }
  9639. }
  9640. `,
  9641. blending: NoBlending,
  9642. depthTest: false,
  9643. depthWrite: false
  9644. } );
  9645. return shaderMaterial;
  9646. }
  9647. function _getEquirectMaterial() {
  9648. return new ShaderMaterial( {
  9649. name: 'EquirectangularToCubeUV',
  9650. uniforms: {
  9651. 'envMap': { value: null }
  9652. },
  9653. vertexShader: _getCommonVertexShader(),
  9654. fragmentShader: /* glsl */`
  9655. precision mediump float;
  9656. precision mediump int;
  9657. varying vec3 vOutputDirection;
  9658. uniform sampler2D envMap;
  9659. #include <common>
  9660. void main() {
  9661. vec3 outputDirection = normalize( vOutputDirection );
  9662. vec2 uv = equirectUv( outputDirection );
  9663. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9664. }
  9665. `,
  9666. blending: NoBlending,
  9667. depthTest: false,
  9668. depthWrite: false
  9669. } );
  9670. }
  9671. function _getCubemapMaterial() {
  9672. return new ShaderMaterial( {
  9673. name: 'CubemapToCubeUV',
  9674. uniforms: {
  9675. 'envMap': { value: null },
  9676. 'flipEnvMap': { value: - 1 }
  9677. },
  9678. vertexShader: _getCommonVertexShader(),
  9679. fragmentShader: /* glsl */`
  9680. precision mediump float;
  9681. precision mediump int;
  9682. uniform float flipEnvMap;
  9683. varying vec3 vOutputDirection;
  9684. uniform samplerCube envMap;
  9685. void main() {
  9686. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9687. }
  9688. `,
  9689. blending: NoBlending,
  9690. depthTest: false,
  9691. depthWrite: false
  9692. } );
  9693. }
  9694. function _getCommonVertexShader() {
  9695. return /* glsl */`
  9696. precision mediump float;
  9697. precision mediump int;
  9698. attribute float faceIndex;
  9699. varying vec3 vOutputDirection;
  9700. // RH coordinate system; PMREM face-indexing convention
  9701. vec3 getDirection( vec2 uv, float face ) {
  9702. uv = 2.0 * uv - 1.0;
  9703. vec3 direction = vec3( uv, 1.0 );
  9704. if ( face == 0.0 ) {
  9705. direction = direction.zyx; // ( 1, v, u ) pos x
  9706. } else if ( face == 1.0 ) {
  9707. direction = direction.xzy;
  9708. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9709. } else if ( face == 2.0 ) {
  9710. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9711. } else if ( face == 3.0 ) {
  9712. direction = direction.zyx;
  9713. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9714. } else if ( face == 4.0 ) {
  9715. direction = direction.xzy;
  9716. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9717. } else if ( face == 5.0 ) {
  9718. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9719. }
  9720. return direction;
  9721. }
  9722. void main() {
  9723. vOutputDirection = getDirection( uv, faceIndex );
  9724. gl_Position = vec4( position, 1.0 );
  9725. }
  9726. `;
  9727. }
  9728. function WebGLCubeUVMaps( renderer ) {
  9729. let cubeUVmaps = new WeakMap();
  9730. let pmremGenerator = null;
  9731. function get( texture ) {
  9732. if ( texture && texture.isTexture ) {
  9733. const mapping = texture.mapping;
  9734. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9735. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9736. // equirect/cube map to cubeUV conversion
  9737. if ( isEquirectMap || isCubeMap ) {
  9738. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9739. texture.needsPMREMUpdate = false;
  9740. let renderTarget = cubeUVmaps.get( texture );
  9741. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9742. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9743. cubeUVmaps.set( texture, renderTarget );
  9744. return renderTarget.texture;
  9745. } else {
  9746. if ( cubeUVmaps.has( texture ) ) {
  9747. return cubeUVmaps.get( texture ).texture;
  9748. } else {
  9749. const image = texture.image;
  9750. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9751. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9752. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9753. cubeUVmaps.set( texture, renderTarget );
  9754. texture.addEventListener( 'dispose', onTextureDispose );
  9755. return renderTarget.texture;
  9756. } else {
  9757. // image not yet ready. try the conversion next frame
  9758. return null;
  9759. }
  9760. }
  9761. }
  9762. }
  9763. }
  9764. return texture;
  9765. }
  9766. function isCubeTextureComplete( image ) {
  9767. let count = 0;
  9768. const length = 6;
  9769. for ( let i = 0; i < length; i ++ ) {
  9770. if ( image[ i ] !== undefined ) count ++;
  9771. }
  9772. return count === length;
  9773. }
  9774. function onTextureDispose( event ) {
  9775. const texture = event.target;
  9776. texture.removeEventListener( 'dispose', onTextureDispose );
  9777. const cubemapUV = cubeUVmaps.get( texture );
  9778. if ( cubemapUV !== undefined ) {
  9779. cubeUVmaps.delete( texture );
  9780. cubemapUV.dispose();
  9781. }
  9782. }
  9783. function dispose() {
  9784. cubeUVmaps = new WeakMap();
  9785. if ( pmremGenerator !== null ) {
  9786. pmremGenerator.dispose();
  9787. pmremGenerator = null;
  9788. }
  9789. }
  9790. return {
  9791. get: get,
  9792. dispose: dispose
  9793. };
  9794. }
  9795. function WebGLExtensions( gl ) {
  9796. const extensions = {};
  9797. function getExtension( name ) {
  9798. if ( extensions[ name ] !== undefined ) {
  9799. return extensions[ name ];
  9800. }
  9801. let extension;
  9802. switch ( name ) {
  9803. case 'WEBGL_depth_texture':
  9804. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9805. break;
  9806. case 'EXT_texture_filter_anisotropic':
  9807. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9808. break;
  9809. case 'WEBGL_compressed_texture_s3tc':
  9810. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9811. break;
  9812. case 'WEBGL_compressed_texture_pvrtc':
  9813. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9814. break;
  9815. default:
  9816. extension = gl.getExtension( name );
  9817. }
  9818. extensions[ name ] = extension;
  9819. return extension;
  9820. }
  9821. return {
  9822. has: function ( name ) {
  9823. return getExtension( name ) !== null;
  9824. },
  9825. init: function ( capabilities ) {
  9826. if ( capabilities.isWebGL2 ) {
  9827. getExtension( 'EXT_color_buffer_float' );
  9828. } else {
  9829. getExtension( 'WEBGL_depth_texture' );
  9830. getExtension( 'OES_texture_float' );
  9831. getExtension( 'OES_texture_half_float' );
  9832. getExtension( 'OES_texture_half_float_linear' );
  9833. getExtension( 'OES_standard_derivatives' );
  9834. getExtension( 'OES_element_index_uint' );
  9835. getExtension( 'OES_vertex_array_object' );
  9836. getExtension( 'ANGLE_instanced_arrays' );
  9837. }
  9838. getExtension( 'OES_texture_float_linear' );
  9839. getExtension( 'EXT_color_buffer_half_float' );
  9840. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9841. },
  9842. get: function ( name ) {
  9843. const extension = getExtension( name );
  9844. if ( extension === null ) {
  9845. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9846. }
  9847. return extension;
  9848. }
  9849. };
  9850. }
  9851. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9852. const geometries = {};
  9853. const wireframeAttributes = new WeakMap();
  9854. function onGeometryDispose( event ) {
  9855. const geometry = event.target;
  9856. if ( geometry.index !== null ) {
  9857. attributes.remove( geometry.index );
  9858. }
  9859. for ( const name in geometry.attributes ) {
  9860. attributes.remove( geometry.attributes[ name ] );
  9861. }
  9862. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9863. delete geometries[ geometry.id ];
  9864. const attribute = wireframeAttributes.get( geometry );
  9865. if ( attribute ) {
  9866. attributes.remove( attribute );
  9867. wireframeAttributes.delete( geometry );
  9868. }
  9869. bindingStates.releaseStatesOfGeometry( geometry );
  9870. if ( geometry.isInstancedBufferGeometry === true ) {
  9871. delete geometry._maxInstanceCount;
  9872. }
  9873. //
  9874. info.memory.geometries --;
  9875. }
  9876. function get( object, geometry ) {
  9877. if ( geometries[ geometry.id ] === true ) return geometry;
  9878. geometry.addEventListener( 'dispose', onGeometryDispose );
  9879. geometries[ geometry.id ] = true;
  9880. info.memory.geometries ++;
  9881. return geometry;
  9882. }
  9883. function update( geometry ) {
  9884. const geometryAttributes = geometry.attributes;
  9885. // Updating index buffer in VAO now. See WebGLBindingStates.
  9886. for ( const name in geometryAttributes ) {
  9887. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9888. }
  9889. // morph targets
  9890. const morphAttributes = geometry.morphAttributes;
  9891. for ( const name in morphAttributes ) {
  9892. const array = morphAttributes[ name ];
  9893. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9894. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9895. }
  9896. }
  9897. }
  9898. function updateWireframeAttribute( geometry ) {
  9899. const indices = [];
  9900. const geometryIndex = geometry.index;
  9901. const geometryPosition = geometry.attributes.position;
  9902. let version = 0;
  9903. if ( geometryIndex !== null ) {
  9904. const array = geometryIndex.array;
  9905. version = geometryIndex.version;
  9906. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9907. const a = array[ i + 0 ];
  9908. const b = array[ i + 1 ];
  9909. const c = array[ i + 2 ];
  9910. indices.push( a, b, b, c, c, a );
  9911. }
  9912. } else {
  9913. const array = geometryPosition.array;
  9914. version = geometryPosition.version;
  9915. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9916. const a = i + 0;
  9917. const b = i + 1;
  9918. const c = i + 2;
  9919. indices.push( a, b, b, c, c, a );
  9920. }
  9921. }
  9922. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9923. attribute.version = version;
  9924. // Updating index buffer in VAO now. See WebGLBindingStates
  9925. //
  9926. const previousAttribute = wireframeAttributes.get( geometry );
  9927. if ( previousAttribute ) attributes.remove( previousAttribute );
  9928. //
  9929. wireframeAttributes.set( geometry, attribute );
  9930. }
  9931. function getWireframeAttribute( geometry ) {
  9932. const currentAttribute = wireframeAttributes.get( geometry );
  9933. if ( currentAttribute ) {
  9934. const geometryIndex = geometry.index;
  9935. if ( geometryIndex !== null ) {
  9936. // if the attribute is obsolete, create a new one
  9937. if ( currentAttribute.version < geometryIndex.version ) {
  9938. updateWireframeAttribute( geometry );
  9939. }
  9940. }
  9941. } else {
  9942. updateWireframeAttribute( geometry );
  9943. }
  9944. return wireframeAttributes.get( geometry );
  9945. }
  9946. return {
  9947. get: get,
  9948. update: update,
  9949. getWireframeAttribute: getWireframeAttribute
  9950. };
  9951. }
  9952. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9953. const isWebGL2 = capabilities.isWebGL2;
  9954. let mode;
  9955. function setMode( value ) {
  9956. mode = value;
  9957. }
  9958. let type, bytesPerElement;
  9959. function setIndex( value ) {
  9960. type = value.type;
  9961. bytesPerElement = value.bytesPerElement;
  9962. }
  9963. function render( start, count ) {
  9964. gl.drawElements( mode, count, type, start * bytesPerElement );
  9965. info.update( count, mode, 1 );
  9966. }
  9967. function renderInstances( start, count, primcount ) {
  9968. if ( primcount === 0 ) return;
  9969. let extension, methodName;
  9970. if ( isWebGL2 ) {
  9971. extension = gl;
  9972. methodName = 'drawElementsInstanced';
  9973. } else {
  9974. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9975. methodName = 'drawElementsInstancedANGLE';
  9976. if ( extension === null ) {
  9977. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9978. return;
  9979. }
  9980. }
  9981. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9982. info.update( count, mode, primcount );
  9983. }
  9984. //
  9985. this.setMode = setMode;
  9986. this.setIndex = setIndex;
  9987. this.render = render;
  9988. this.renderInstances = renderInstances;
  9989. }
  9990. function WebGLInfo( gl ) {
  9991. const memory = {
  9992. geometries: 0,
  9993. textures: 0
  9994. };
  9995. const render = {
  9996. frame: 0,
  9997. calls: 0,
  9998. triangles: 0,
  9999. points: 0,
  10000. lines: 0
  10001. };
  10002. function update( count, mode, instanceCount ) {
  10003. render.calls ++;
  10004. switch ( mode ) {
  10005. case gl.TRIANGLES:
  10006. render.triangles += instanceCount * ( count / 3 );
  10007. break;
  10008. case gl.LINES:
  10009. render.lines += instanceCount * ( count / 2 );
  10010. break;
  10011. case gl.LINE_STRIP:
  10012. render.lines += instanceCount * ( count - 1 );
  10013. break;
  10014. case gl.LINE_LOOP:
  10015. render.lines += instanceCount * count;
  10016. break;
  10017. case gl.POINTS:
  10018. render.points += instanceCount * count;
  10019. break;
  10020. default:
  10021. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10022. break;
  10023. }
  10024. }
  10025. function reset() {
  10026. render.frame ++;
  10027. render.calls = 0;
  10028. render.triangles = 0;
  10029. render.points = 0;
  10030. render.lines = 0;
  10031. }
  10032. return {
  10033. memory: memory,
  10034. render: render,
  10035. programs: null,
  10036. autoReset: true,
  10037. reset: reset,
  10038. update: update
  10039. };
  10040. }
  10041. function numericalSort( a, b ) {
  10042. return a[ 0 ] - b[ 0 ];
  10043. }
  10044. function absNumericalSort( a, b ) {
  10045. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10046. }
  10047. function WebGLMorphtargets( gl, capabilities, textures ) {
  10048. const influencesList = {};
  10049. const morphInfluences = new Float32Array( 8 );
  10050. const morphTextures = new WeakMap();
  10051. const morph = new Vector4();
  10052. const workInfluences = [];
  10053. for ( let i = 0; i < 8; i ++ ) {
  10054. workInfluences[ i ] = [ i, 0 ];
  10055. }
  10056. function update( object, geometry, material, program ) {
  10057. const objectInfluences = object.morphTargetInfluences;
  10058. if ( capabilities.isWebGL2 === true ) {
  10059. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10060. // into an array of data textures. Each layer represents a single morph target.
  10061. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10062. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10063. let entry = morphTextures.get( geometry );
  10064. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10065. if ( entry !== undefined ) entry.texture.dispose();
  10066. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10067. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10068. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10069. const morphTargets = geometry.morphAttributes.position || [];
  10070. const morphNormals = geometry.morphAttributes.normal || [];
  10071. const morphColors = geometry.morphAttributes.color || [];
  10072. let vertexDataCount = 0;
  10073. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10074. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10075. if ( hasMorphColors === true ) vertexDataCount = 3;
  10076. let width = geometry.attributes.position.count * vertexDataCount;
  10077. let height = 1;
  10078. if ( width > capabilities.maxTextureSize ) {
  10079. height = Math.ceil( width / capabilities.maxTextureSize );
  10080. width = capabilities.maxTextureSize;
  10081. }
  10082. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10083. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10084. texture.type = FloatType;
  10085. texture.needsUpdate = true;
  10086. // fill buffer
  10087. const vertexDataStride = vertexDataCount * 4;
  10088. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10089. const morphTarget = morphTargets[ i ];
  10090. const morphNormal = morphNormals[ i ];
  10091. const morphColor = morphColors[ i ];
  10092. const offset = width * height * 4 * i;
  10093. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10094. const stride = j * vertexDataStride;
  10095. if ( hasMorphPosition === true ) {
  10096. morph.fromBufferAttribute( morphTarget, j );
  10097. buffer[ offset + stride + 0 ] = morph.x;
  10098. buffer[ offset + stride + 1 ] = morph.y;
  10099. buffer[ offset + stride + 2 ] = morph.z;
  10100. buffer[ offset + stride + 3 ] = 0;
  10101. }
  10102. if ( hasMorphNormals === true ) {
  10103. morph.fromBufferAttribute( morphNormal, j );
  10104. buffer[ offset + stride + 4 ] = morph.x;
  10105. buffer[ offset + stride + 5 ] = morph.y;
  10106. buffer[ offset + stride + 6 ] = morph.z;
  10107. buffer[ offset + stride + 7 ] = 0;
  10108. }
  10109. if ( hasMorphColors === true ) {
  10110. morph.fromBufferAttribute( morphColor, j );
  10111. buffer[ offset + stride + 8 ] = morph.x;
  10112. buffer[ offset + stride + 9 ] = morph.y;
  10113. buffer[ offset + stride + 10 ] = morph.z;
  10114. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10115. }
  10116. }
  10117. }
  10118. entry = {
  10119. count: morphTargetsCount,
  10120. texture: texture,
  10121. size: new Vector2( width, height )
  10122. };
  10123. morphTextures.set( geometry, entry );
  10124. function disposeTexture() {
  10125. texture.dispose();
  10126. morphTextures.delete( geometry );
  10127. geometry.removeEventListener( 'dispose', disposeTexture );
  10128. }
  10129. geometry.addEventListener( 'dispose', disposeTexture );
  10130. }
  10131. //
  10132. let morphInfluencesSum = 0;
  10133. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10134. morphInfluencesSum += objectInfluences[ i ];
  10135. }
  10136. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10137. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10138. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10139. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10140. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10141. } else {
  10142. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10143. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10144. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10145. let influences = influencesList[ geometry.id ];
  10146. if ( influences === undefined || influences.length !== length ) {
  10147. // initialise list
  10148. influences = [];
  10149. for ( let i = 0; i < length; i ++ ) {
  10150. influences[ i ] = [ i, 0 ];
  10151. }
  10152. influencesList[ geometry.id ] = influences;
  10153. }
  10154. // Collect influences
  10155. for ( let i = 0; i < length; i ++ ) {
  10156. const influence = influences[ i ];
  10157. influence[ 0 ] = i;
  10158. influence[ 1 ] = objectInfluences[ i ];
  10159. }
  10160. influences.sort( absNumericalSort );
  10161. for ( let i = 0; i < 8; i ++ ) {
  10162. if ( i < length && influences[ i ][ 1 ] ) {
  10163. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10164. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10165. } else {
  10166. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10167. workInfluences[ i ][ 1 ] = 0;
  10168. }
  10169. }
  10170. workInfluences.sort( numericalSort );
  10171. const morphTargets = geometry.morphAttributes.position;
  10172. const morphNormals = geometry.morphAttributes.normal;
  10173. let morphInfluencesSum = 0;
  10174. for ( let i = 0; i < 8; i ++ ) {
  10175. const influence = workInfluences[ i ];
  10176. const index = influence[ 0 ];
  10177. const value = influence[ 1 ];
  10178. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10179. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10180. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10181. }
  10182. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10183. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10184. }
  10185. morphInfluences[ i ] = value;
  10186. morphInfluencesSum += value;
  10187. } else {
  10188. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10189. geometry.deleteAttribute( 'morphTarget' + i );
  10190. }
  10191. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10192. geometry.deleteAttribute( 'morphNormal' + i );
  10193. }
  10194. morphInfluences[ i ] = 0;
  10195. }
  10196. }
  10197. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10198. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10199. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10200. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10201. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10202. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10203. }
  10204. }
  10205. return {
  10206. update: update
  10207. };
  10208. }
  10209. function WebGLObjects( gl, geometries, attributes, info ) {
  10210. let updateMap = new WeakMap();
  10211. function update( object ) {
  10212. const frame = info.render.frame;
  10213. const geometry = object.geometry;
  10214. const buffergeometry = geometries.get( object, geometry );
  10215. // Update once per frame
  10216. if ( updateMap.get( buffergeometry ) !== frame ) {
  10217. geometries.update( buffergeometry );
  10218. updateMap.set( buffergeometry, frame );
  10219. }
  10220. if ( object.isInstancedMesh ) {
  10221. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10222. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10223. }
  10224. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10225. if ( object.instanceColor !== null ) {
  10226. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10227. }
  10228. }
  10229. return buffergeometry;
  10230. }
  10231. function dispose() {
  10232. updateMap = new WeakMap();
  10233. }
  10234. function onInstancedMeshDispose( event ) {
  10235. const instancedMesh = event.target;
  10236. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10237. attributes.remove( instancedMesh.instanceMatrix );
  10238. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10239. }
  10240. return {
  10241. update: update,
  10242. dispose: dispose
  10243. };
  10244. }
  10245. /**
  10246. * Uniforms of a program.
  10247. * Those form a tree structure with a special top-level container for the root,
  10248. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10249. *
  10250. *
  10251. * Properties of inner nodes including the top-level container:
  10252. *
  10253. * .seq - array of nested uniforms
  10254. * .map - nested uniforms by name
  10255. *
  10256. *
  10257. * Methods of all nodes except the top-level container:
  10258. *
  10259. * .setValue( gl, value, [textures] )
  10260. *
  10261. * uploads a uniform value(s)
  10262. * the 'textures' parameter is needed for sampler uniforms
  10263. *
  10264. *
  10265. * Static methods of the top-level container (textures factorizations):
  10266. *
  10267. * .upload( gl, seq, values, textures )
  10268. *
  10269. * sets uniforms in 'seq' to 'values[id].value'
  10270. *
  10271. * .seqWithValue( seq, values ) : filteredSeq
  10272. *
  10273. * filters 'seq' entries with corresponding entry in values
  10274. *
  10275. *
  10276. * Methods of the top-level container (textures factorizations):
  10277. *
  10278. * .setValue( gl, name, value, textures )
  10279. *
  10280. * sets uniform with name 'name' to 'value'
  10281. *
  10282. * .setOptional( gl, obj, prop )
  10283. *
  10284. * like .set for an optional property of the object
  10285. *
  10286. */
  10287. const emptyTexture = /*@__PURE__*/ new Texture();
  10288. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10289. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10290. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10291. // --- Utilities ---
  10292. // Array Caches (provide typed arrays for temporary by size)
  10293. const arrayCacheF32 = [];
  10294. const arrayCacheI32 = [];
  10295. // Float32Array caches used for uploading Matrix uniforms
  10296. const mat4array = new Float32Array( 16 );
  10297. const mat3array = new Float32Array( 9 );
  10298. const mat2array = new Float32Array( 4 );
  10299. // Flattening for arrays of vectors and matrices
  10300. function flatten( array, nBlocks, blockSize ) {
  10301. const firstElem = array[ 0 ];
  10302. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10303. // unoptimized: ! isNaN( firstElem )
  10304. // see http://jacksondunstan.com/articles/983
  10305. const n = nBlocks * blockSize;
  10306. let r = arrayCacheF32[ n ];
  10307. if ( r === undefined ) {
  10308. r = new Float32Array( n );
  10309. arrayCacheF32[ n ] = r;
  10310. }
  10311. if ( nBlocks !== 0 ) {
  10312. firstElem.toArray( r, 0 );
  10313. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10314. offset += blockSize;
  10315. array[ i ].toArray( r, offset );
  10316. }
  10317. }
  10318. return r;
  10319. }
  10320. function arraysEqual( a, b ) {
  10321. if ( a.length !== b.length ) return false;
  10322. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10323. if ( a[ i ] !== b[ i ] ) return false;
  10324. }
  10325. return true;
  10326. }
  10327. function copyArray( a, b ) {
  10328. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10329. a[ i ] = b[ i ];
  10330. }
  10331. }
  10332. // Texture unit allocation
  10333. function allocTexUnits( textures, n ) {
  10334. let r = arrayCacheI32[ n ];
  10335. if ( r === undefined ) {
  10336. r = new Int32Array( n );
  10337. arrayCacheI32[ n ] = r;
  10338. }
  10339. for ( let i = 0; i !== n; ++ i ) {
  10340. r[ i ] = textures.allocateTextureUnit();
  10341. }
  10342. return r;
  10343. }
  10344. // --- Setters ---
  10345. // Note: Defining these methods externally, because they come in a bunch
  10346. // and this way their names minify.
  10347. // Single scalar
  10348. function setValueV1f( gl, v ) {
  10349. const cache = this.cache;
  10350. if ( cache[ 0 ] === v ) return;
  10351. gl.uniform1f( this.addr, v );
  10352. cache[ 0 ] = v;
  10353. }
  10354. // Single float vector (from flat array or THREE.VectorN)
  10355. function setValueV2f( gl, v ) {
  10356. const cache = this.cache;
  10357. if ( v.x !== undefined ) {
  10358. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10359. gl.uniform2f( this.addr, v.x, v.y );
  10360. cache[ 0 ] = v.x;
  10361. cache[ 1 ] = v.y;
  10362. }
  10363. } else {
  10364. if ( arraysEqual( cache, v ) ) return;
  10365. gl.uniform2fv( this.addr, v );
  10366. copyArray( cache, v );
  10367. }
  10368. }
  10369. function setValueV3f( gl, v ) {
  10370. const cache = this.cache;
  10371. if ( v.x !== undefined ) {
  10372. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10373. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10374. cache[ 0 ] = v.x;
  10375. cache[ 1 ] = v.y;
  10376. cache[ 2 ] = v.z;
  10377. }
  10378. } else if ( v.r !== undefined ) {
  10379. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10380. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10381. cache[ 0 ] = v.r;
  10382. cache[ 1 ] = v.g;
  10383. cache[ 2 ] = v.b;
  10384. }
  10385. } else {
  10386. if ( arraysEqual( cache, v ) ) return;
  10387. gl.uniform3fv( this.addr, v );
  10388. copyArray( cache, v );
  10389. }
  10390. }
  10391. function setValueV4f( gl, v ) {
  10392. const cache = this.cache;
  10393. if ( v.x !== undefined ) {
  10394. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10395. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10396. cache[ 0 ] = v.x;
  10397. cache[ 1 ] = v.y;
  10398. cache[ 2 ] = v.z;
  10399. cache[ 3 ] = v.w;
  10400. }
  10401. } else {
  10402. if ( arraysEqual( cache, v ) ) return;
  10403. gl.uniform4fv( this.addr, v );
  10404. copyArray( cache, v );
  10405. }
  10406. }
  10407. // Single matrix (from flat array or THREE.MatrixN)
  10408. function setValueM2( gl, v ) {
  10409. const cache = this.cache;
  10410. const elements = v.elements;
  10411. if ( elements === undefined ) {
  10412. if ( arraysEqual( cache, v ) ) return;
  10413. gl.uniformMatrix2fv( this.addr, false, v );
  10414. copyArray( cache, v );
  10415. } else {
  10416. if ( arraysEqual( cache, elements ) ) return;
  10417. mat2array.set( elements );
  10418. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10419. copyArray( cache, elements );
  10420. }
  10421. }
  10422. function setValueM3( gl, v ) {
  10423. const cache = this.cache;
  10424. const elements = v.elements;
  10425. if ( elements === undefined ) {
  10426. if ( arraysEqual( cache, v ) ) return;
  10427. gl.uniformMatrix3fv( this.addr, false, v );
  10428. copyArray( cache, v );
  10429. } else {
  10430. if ( arraysEqual( cache, elements ) ) return;
  10431. mat3array.set( elements );
  10432. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10433. copyArray( cache, elements );
  10434. }
  10435. }
  10436. function setValueM4( gl, v ) {
  10437. const cache = this.cache;
  10438. const elements = v.elements;
  10439. if ( elements === undefined ) {
  10440. if ( arraysEqual( cache, v ) ) return;
  10441. gl.uniformMatrix4fv( this.addr, false, v );
  10442. copyArray( cache, v );
  10443. } else {
  10444. if ( arraysEqual( cache, elements ) ) return;
  10445. mat4array.set( elements );
  10446. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10447. copyArray( cache, elements );
  10448. }
  10449. }
  10450. // Single integer / boolean
  10451. function setValueV1i( gl, v ) {
  10452. const cache = this.cache;
  10453. if ( cache[ 0 ] === v ) return;
  10454. gl.uniform1i( this.addr, v );
  10455. cache[ 0 ] = v;
  10456. }
  10457. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10458. function setValueV2i( gl, v ) {
  10459. const cache = this.cache;
  10460. if ( v.x !== undefined ) {
  10461. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10462. gl.uniform2i( this.addr, v.x, v.y );
  10463. cache[ 0 ] = v.x;
  10464. cache[ 1 ] = v.y;
  10465. }
  10466. } else {
  10467. if ( arraysEqual( cache, v ) ) return;
  10468. gl.uniform2iv( this.addr, v );
  10469. copyArray( cache, v );
  10470. }
  10471. }
  10472. function setValueV3i( gl, v ) {
  10473. const cache = this.cache;
  10474. if ( v.x !== undefined ) {
  10475. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10476. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10477. cache[ 0 ] = v.x;
  10478. cache[ 1 ] = v.y;
  10479. cache[ 2 ] = v.z;
  10480. }
  10481. } else {
  10482. if ( arraysEqual( cache, v ) ) return;
  10483. gl.uniform3iv( this.addr, v );
  10484. copyArray( cache, v );
  10485. }
  10486. }
  10487. function setValueV4i( gl, v ) {
  10488. const cache = this.cache;
  10489. if ( v.x !== undefined ) {
  10490. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10491. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10492. cache[ 0 ] = v.x;
  10493. cache[ 1 ] = v.y;
  10494. cache[ 2 ] = v.z;
  10495. cache[ 3 ] = v.w;
  10496. }
  10497. } else {
  10498. if ( arraysEqual( cache, v ) ) return;
  10499. gl.uniform4iv( this.addr, v );
  10500. copyArray( cache, v );
  10501. }
  10502. }
  10503. // Single unsigned integer
  10504. function setValueV1ui( gl, v ) {
  10505. const cache = this.cache;
  10506. if ( cache[ 0 ] === v ) return;
  10507. gl.uniform1ui( this.addr, v );
  10508. cache[ 0 ] = v;
  10509. }
  10510. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10511. function setValueV2ui( gl, v ) {
  10512. const cache = this.cache;
  10513. if ( v.x !== undefined ) {
  10514. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10515. gl.uniform2ui( this.addr, v.x, v.y );
  10516. cache[ 0 ] = v.x;
  10517. cache[ 1 ] = v.y;
  10518. }
  10519. } else {
  10520. if ( arraysEqual( cache, v ) ) return;
  10521. gl.uniform2uiv( this.addr, v );
  10522. copyArray( cache, v );
  10523. }
  10524. }
  10525. function setValueV3ui( gl, v ) {
  10526. const cache = this.cache;
  10527. if ( v.x !== undefined ) {
  10528. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10529. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10530. cache[ 0 ] = v.x;
  10531. cache[ 1 ] = v.y;
  10532. cache[ 2 ] = v.z;
  10533. }
  10534. } else {
  10535. if ( arraysEqual( cache, v ) ) return;
  10536. gl.uniform3uiv( this.addr, v );
  10537. copyArray( cache, v );
  10538. }
  10539. }
  10540. function setValueV4ui( gl, v ) {
  10541. const cache = this.cache;
  10542. if ( v.x !== undefined ) {
  10543. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10544. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10545. cache[ 0 ] = v.x;
  10546. cache[ 1 ] = v.y;
  10547. cache[ 2 ] = v.z;
  10548. cache[ 3 ] = v.w;
  10549. }
  10550. } else {
  10551. if ( arraysEqual( cache, v ) ) return;
  10552. gl.uniform4uiv( this.addr, v );
  10553. copyArray( cache, v );
  10554. }
  10555. }
  10556. // Single texture (2D / Cube)
  10557. function setValueT1( gl, v, textures ) {
  10558. const cache = this.cache;
  10559. const unit = textures.allocateTextureUnit();
  10560. if ( cache[ 0 ] !== unit ) {
  10561. gl.uniform1i( this.addr, unit );
  10562. cache[ 0 ] = unit;
  10563. }
  10564. textures.setTexture2D( v || emptyTexture, unit );
  10565. }
  10566. function setValueT3D1( gl, v, textures ) {
  10567. const cache = this.cache;
  10568. const unit = textures.allocateTextureUnit();
  10569. if ( cache[ 0 ] !== unit ) {
  10570. gl.uniform1i( this.addr, unit );
  10571. cache[ 0 ] = unit;
  10572. }
  10573. textures.setTexture3D( v || empty3dTexture, unit );
  10574. }
  10575. function setValueT6( gl, v, textures ) {
  10576. const cache = this.cache;
  10577. const unit = textures.allocateTextureUnit();
  10578. if ( cache[ 0 ] !== unit ) {
  10579. gl.uniform1i( this.addr, unit );
  10580. cache[ 0 ] = unit;
  10581. }
  10582. textures.setTextureCube( v || emptyCubeTexture, unit );
  10583. }
  10584. function setValueT2DArray1( gl, v, textures ) {
  10585. const cache = this.cache;
  10586. const unit = textures.allocateTextureUnit();
  10587. if ( cache[ 0 ] !== unit ) {
  10588. gl.uniform1i( this.addr, unit );
  10589. cache[ 0 ] = unit;
  10590. }
  10591. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10592. }
  10593. // Helper to pick the right setter for the singular case
  10594. function getSingularSetter( type ) {
  10595. switch ( type ) {
  10596. case 0x1406: return setValueV1f; // FLOAT
  10597. case 0x8b50: return setValueV2f; // _VEC2
  10598. case 0x8b51: return setValueV3f; // _VEC3
  10599. case 0x8b52: return setValueV4f; // _VEC4
  10600. case 0x8b5a: return setValueM2; // _MAT2
  10601. case 0x8b5b: return setValueM3; // _MAT3
  10602. case 0x8b5c: return setValueM4; // _MAT4
  10603. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10604. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10605. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10606. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10607. case 0x1405: return setValueV1ui; // UINT
  10608. case 0x8dc6: return setValueV2ui; // _VEC2
  10609. case 0x8dc7: return setValueV3ui; // _VEC3
  10610. case 0x8dc8: return setValueV4ui; // _VEC4
  10611. case 0x8b5e: // SAMPLER_2D
  10612. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10613. case 0x8dca: // INT_SAMPLER_2D
  10614. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10615. case 0x8b62: // SAMPLER_2D_SHADOW
  10616. return setValueT1;
  10617. case 0x8b5f: // SAMPLER_3D
  10618. case 0x8dcb: // INT_SAMPLER_3D
  10619. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10620. return setValueT3D1;
  10621. case 0x8b60: // SAMPLER_CUBE
  10622. case 0x8dcc: // INT_SAMPLER_CUBE
  10623. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10624. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10625. return setValueT6;
  10626. case 0x8dc1: // SAMPLER_2D_ARRAY
  10627. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10628. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10629. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10630. return setValueT2DArray1;
  10631. }
  10632. }
  10633. // Array of scalars
  10634. function setValueV1fArray( gl, v ) {
  10635. gl.uniform1fv( this.addr, v );
  10636. }
  10637. // Array of vectors (from flat array or array of THREE.VectorN)
  10638. function setValueV2fArray( gl, v ) {
  10639. const data = flatten( v, this.size, 2 );
  10640. gl.uniform2fv( this.addr, data );
  10641. }
  10642. function setValueV3fArray( gl, v ) {
  10643. const data = flatten( v, this.size, 3 );
  10644. gl.uniform3fv( this.addr, data );
  10645. }
  10646. function setValueV4fArray( gl, v ) {
  10647. const data = flatten( v, this.size, 4 );
  10648. gl.uniform4fv( this.addr, data );
  10649. }
  10650. // Array of matrices (from flat array or array of THREE.MatrixN)
  10651. function setValueM2Array( gl, v ) {
  10652. const data = flatten( v, this.size, 4 );
  10653. gl.uniformMatrix2fv( this.addr, false, data );
  10654. }
  10655. function setValueM3Array( gl, v ) {
  10656. const data = flatten( v, this.size, 9 );
  10657. gl.uniformMatrix3fv( this.addr, false, data );
  10658. }
  10659. function setValueM4Array( gl, v ) {
  10660. const data = flatten( v, this.size, 16 );
  10661. gl.uniformMatrix4fv( this.addr, false, data );
  10662. }
  10663. // Array of integer / boolean
  10664. function setValueV1iArray( gl, v ) {
  10665. gl.uniform1iv( this.addr, v );
  10666. }
  10667. // Array of integer / boolean vectors (from flat array)
  10668. function setValueV2iArray( gl, v ) {
  10669. gl.uniform2iv( this.addr, v );
  10670. }
  10671. function setValueV3iArray( gl, v ) {
  10672. gl.uniform3iv( this.addr, v );
  10673. }
  10674. function setValueV4iArray( gl, v ) {
  10675. gl.uniform4iv( this.addr, v );
  10676. }
  10677. // Array of unsigned integer
  10678. function setValueV1uiArray( gl, v ) {
  10679. gl.uniform1uiv( this.addr, v );
  10680. }
  10681. // Array of unsigned integer vectors (from flat array)
  10682. function setValueV2uiArray( gl, v ) {
  10683. gl.uniform2uiv( this.addr, v );
  10684. }
  10685. function setValueV3uiArray( gl, v ) {
  10686. gl.uniform3uiv( this.addr, v );
  10687. }
  10688. function setValueV4uiArray( gl, v ) {
  10689. gl.uniform4uiv( this.addr, v );
  10690. }
  10691. // Array of textures (2D / 3D / Cube / 2DArray)
  10692. function setValueT1Array( gl, v, textures ) {
  10693. const cache = this.cache;
  10694. const n = v.length;
  10695. const units = allocTexUnits( textures, n );
  10696. if ( ! arraysEqual( cache, units ) ) {
  10697. gl.uniform1iv( this.addr, units );
  10698. copyArray( cache, units );
  10699. }
  10700. for ( let i = 0; i !== n; ++ i ) {
  10701. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10702. }
  10703. }
  10704. function setValueT3DArray( gl, v, textures ) {
  10705. const cache = this.cache;
  10706. const n = v.length;
  10707. const units = allocTexUnits( textures, n );
  10708. if ( ! arraysEqual( cache, units ) ) {
  10709. gl.uniform1iv( this.addr, units );
  10710. copyArray( cache, units );
  10711. }
  10712. for ( let i = 0; i !== n; ++ i ) {
  10713. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10714. }
  10715. }
  10716. function setValueT6Array( gl, v, textures ) {
  10717. const cache = this.cache;
  10718. const n = v.length;
  10719. const units = allocTexUnits( textures, n );
  10720. if ( ! arraysEqual( cache, units ) ) {
  10721. gl.uniform1iv( this.addr, units );
  10722. copyArray( cache, units );
  10723. }
  10724. for ( let i = 0; i !== n; ++ i ) {
  10725. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10726. }
  10727. }
  10728. function setValueT2DArrayArray( gl, v, textures ) {
  10729. const cache = this.cache;
  10730. const n = v.length;
  10731. const units = allocTexUnits( textures, n );
  10732. if ( ! arraysEqual( cache, units ) ) {
  10733. gl.uniform1iv( this.addr, units );
  10734. copyArray( cache, units );
  10735. }
  10736. for ( let i = 0; i !== n; ++ i ) {
  10737. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10738. }
  10739. }
  10740. // Helper to pick the right setter for a pure (bottom-level) array
  10741. function getPureArraySetter( type ) {
  10742. switch ( type ) {
  10743. case 0x1406: return setValueV1fArray; // FLOAT
  10744. case 0x8b50: return setValueV2fArray; // _VEC2
  10745. case 0x8b51: return setValueV3fArray; // _VEC3
  10746. case 0x8b52: return setValueV4fArray; // _VEC4
  10747. case 0x8b5a: return setValueM2Array; // _MAT2
  10748. case 0x8b5b: return setValueM3Array; // _MAT3
  10749. case 0x8b5c: return setValueM4Array; // _MAT4
  10750. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10751. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10752. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10753. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10754. case 0x1405: return setValueV1uiArray; // UINT
  10755. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10756. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10757. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10758. case 0x8b5e: // SAMPLER_2D
  10759. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10760. case 0x8dca: // INT_SAMPLER_2D
  10761. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10762. case 0x8b62: // SAMPLER_2D_SHADOW
  10763. return setValueT1Array;
  10764. case 0x8b5f: // SAMPLER_3D
  10765. case 0x8dcb: // INT_SAMPLER_3D
  10766. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10767. return setValueT3DArray;
  10768. case 0x8b60: // SAMPLER_CUBE
  10769. case 0x8dcc: // INT_SAMPLER_CUBE
  10770. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10771. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10772. return setValueT6Array;
  10773. case 0x8dc1: // SAMPLER_2D_ARRAY
  10774. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10775. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10776. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10777. return setValueT2DArrayArray;
  10778. }
  10779. }
  10780. // --- Uniform Classes ---
  10781. class SingleUniform {
  10782. constructor( id, activeInfo, addr ) {
  10783. this.id = id;
  10784. this.addr = addr;
  10785. this.cache = [];
  10786. this.setValue = getSingularSetter( activeInfo.type );
  10787. // this.path = activeInfo.name; // DEBUG
  10788. }
  10789. }
  10790. class PureArrayUniform {
  10791. constructor( id, activeInfo, addr ) {
  10792. this.id = id;
  10793. this.addr = addr;
  10794. this.cache = [];
  10795. this.size = activeInfo.size;
  10796. this.setValue = getPureArraySetter( activeInfo.type );
  10797. // this.path = activeInfo.name; // DEBUG
  10798. }
  10799. }
  10800. class StructuredUniform {
  10801. constructor( id ) {
  10802. this.id = id;
  10803. this.seq = [];
  10804. this.map = {};
  10805. }
  10806. setValue( gl, value, textures ) {
  10807. const seq = this.seq;
  10808. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10809. const u = seq[ i ];
  10810. u.setValue( gl, value[ u.id ], textures );
  10811. }
  10812. }
  10813. }
  10814. // --- Top-level ---
  10815. // Parser - builds up the property tree from the path strings
  10816. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10817. // extracts
  10818. // - the identifier (member name or array index)
  10819. // - followed by an optional right bracket (found when array index)
  10820. // - followed by an optional left bracket or dot (type of subscript)
  10821. //
  10822. // Note: These portions can be read in a non-overlapping fashion and
  10823. // allow straightforward parsing of the hierarchy that WebGL encodes
  10824. // in the uniform names.
  10825. function addUniform( container, uniformObject ) {
  10826. container.seq.push( uniformObject );
  10827. container.map[ uniformObject.id ] = uniformObject;
  10828. }
  10829. function parseUniform( activeInfo, addr, container ) {
  10830. const path = activeInfo.name,
  10831. pathLength = path.length;
  10832. // reset RegExp object, because of the early exit of a previous run
  10833. RePathPart.lastIndex = 0;
  10834. while ( true ) {
  10835. const match = RePathPart.exec( path ),
  10836. matchEnd = RePathPart.lastIndex;
  10837. let id = match[ 1 ];
  10838. const idIsIndex = match[ 2 ] === ']',
  10839. subscript = match[ 3 ];
  10840. if ( idIsIndex ) id = id | 0; // convert to integer
  10841. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10842. // bare name or "pure" bottom-level array "[0]" suffix
  10843. addUniform( container, subscript === undefined ?
  10844. new SingleUniform( id, activeInfo, addr ) :
  10845. new PureArrayUniform( id, activeInfo, addr ) );
  10846. break;
  10847. } else {
  10848. // step into inner node / create it in case it doesn't exist
  10849. const map = container.map;
  10850. let next = map[ id ];
  10851. if ( next === undefined ) {
  10852. next = new StructuredUniform( id );
  10853. addUniform( container, next );
  10854. }
  10855. container = next;
  10856. }
  10857. }
  10858. }
  10859. // Root Container
  10860. class WebGLUniforms {
  10861. constructor( gl, program ) {
  10862. this.seq = [];
  10863. this.map = {};
  10864. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  10865. for ( let i = 0; i < n; ++ i ) {
  10866. const info = gl.getActiveUniform( program, i ),
  10867. addr = gl.getUniformLocation( program, info.name );
  10868. parseUniform( info, addr, this );
  10869. }
  10870. }
  10871. setValue( gl, name, value, textures ) {
  10872. const u = this.map[ name ];
  10873. if ( u !== undefined ) u.setValue( gl, value, textures );
  10874. }
  10875. setOptional( gl, object, name ) {
  10876. const v = object[ name ];
  10877. if ( v !== undefined ) this.setValue( gl, name, v );
  10878. }
  10879. static upload( gl, seq, values, textures ) {
  10880. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10881. const u = seq[ i ],
  10882. v = values[ u.id ];
  10883. if ( v.needsUpdate !== false ) {
  10884. // note: always updating when .needsUpdate is undefined
  10885. u.setValue( gl, v.value, textures );
  10886. }
  10887. }
  10888. }
  10889. static seqWithValue( seq, values ) {
  10890. const r = [];
  10891. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10892. const u = seq[ i ];
  10893. if ( u.id in values ) r.push( u );
  10894. }
  10895. return r;
  10896. }
  10897. }
  10898. function WebGLShader( gl, type, string ) {
  10899. const shader = gl.createShader( type );
  10900. gl.shaderSource( shader, string );
  10901. gl.compileShader( shader );
  10902. return shader;
  10903. }
  10904. let programIdCount = 0;
  10905. function handleSource( string, errorLine ) {
  10906. const lines = string.split( '\n' );
  10907. const lines2 = [];
  10908. const from = Math.max( errorLine - 6, 0 );
  10909. const to = Math.min( errorLine + 6, lines.length );
  10910. for ( let i = from; i < to; i ++ ) {
  10911. const line = i + 1;
  10912. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10913. }
  10914. return lines2.join( '\n' );
  10915. }
  10916. function getEncodingComponents( encoding ) {
  10917. switch ( encoding ) {
  10918. case LinearEncoding:
  10919. return [ 'Linear', '( value )' ];
  10920. case sRGBEncoding:
  10921. return [ 'sRGB', '( value )' ];
  10922. default:
  10923. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10924. return [ 'Linear', '( value )' ];
  10925. }
  10926. }
  10927. function getShaderErrors( gl, shader, type ) {
  10928. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  10929. const errors = gl.getShaderInfoLog( shader ).trim();
  10930. if ( status && errors === '' ) return '';
  10931. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10932. if ( errorMatches ) {
  10933. // --enable-privileged-webgl-extension
  10934. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10935. const errorLine = parseInt( errorMatches[ 1 ] );
  10936. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10937. } else {
  10938. return errors;
  10939. }
  10940. }
  10941. function getTexelEncodingFunction( functionName, encoding ) {
  10942. const components = getEncodingComponents( encoding );
  10943. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10944. }
  10945. function getToneMappingFunction( functionName, toneMapping ) {
  10946. let toneMappingName;
  10947. switch ( toneMapping ) {
  10948. case LinearToneMapping:
  10949. toneMappingName = 'Linear';
  10950. break;
  10951. case ReinhardToneMapping:
  10952. toneMappingName = 'Reinhard';
  10953. break;
  10954. case CineonToneMapping:
  10955. toneMappingName = 'OptimizedCineon';
  10956. break;
  10957. case ACESFilmicToneMapping:
  10958. toneMappingName = 'ACESFilmic';
  10959. break;
  10960. case CustomToneMapping:
  10961. toneMappingName = 'Custom';
  10962. break;
  10963. default:
  10964. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10965. toneMappingName = 'Linear';
  10966. }
  10967. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10968. }
  10969. function generateExtensions( parameters ) {
  10970. const chunks = [
  10971. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10972. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10973. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10974. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10975. ];
  10976. return chunks.filter( filterEmptyLine ).join( '\n' );
  10977. }
  10978. function generateDefines( defines ) {
  10979. const chunks = [];
  10980. for ( const name in defines ) {
  10981. const value = defines[ name ];
  10982. if ( value === false ) continue;
  10983. chunks.push( '#define ' + name + ' ' + value );
  10984. }
  10985. return chunks.join( '\n' );
  10986. }
  10987. function fetchAttributeLocations( gl, program ) {
  10988. const attributes = {};
  10989. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10990. for ( let i = 0; i < n; i ++ ) {
  10991. const info = gl.getActiveAttrib( program, i );
  10992. const name = info.name;
  10993. let locationSize = 1;
  10994. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  10995. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  10996. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  10997. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10998. attributes[ name ] = {
  10999. type: info.type,
  11000. location: gl.getAttribLocation( program, name ),
  11001. locationSize: locationSize
  11002. };
  11003. }
  11004. return attributes;
  11005. }
  11006. function filterEmptyLine( string ) {
  11007. return string !== '';
  11008. }
  11009. function replaceLightNums( string, parameters ) {
  11010. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11011. return string
  11012. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11013. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11014. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11015. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11016. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11017. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11018. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11019. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11020. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11021. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11022. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11023. }
  11024. function replaceClippingPlaneNums( string, parameters ) {
  11025. return string
  11026. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11027. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11028. }
  11029. // Resolve Includes
  11030. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11031. function resolveIncludes( string ) {
  11032. return string.replace( includePattern, includeReplacer );
  11033. }
  11034. function includeReplacer( match, include ) {
  11035. const string = ShaderChunk[ include ];
  11036. if ( string === undefined ) {
  11037. throw new Error( 'Can not resolve #include <' + include + '>' );
  11038. }
  11039. return resolveIncludes( string );
  11040. }
  11041. // Unroll Loops
  11042. 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;
  11043. function unrollLoops( string ) {
  11044. return string.replace( unrollLoopPattern, loopReplacer );
  11045. }
  11046. function loopReplacer( match, start, end, snippet ) {
  11047. let string = '';
  11048. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11049. string += snippet
  11050. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11051. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11052. }
  11053. return string;
  11054. }
  11055. //
  11056. function generatePrecision( parameters ) {
  11057. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11058. if ( parameters.precision === 'highp' ) {
  11059. precisionstring += '\n#define HIGH_PRECISION';
  11060. } else if ( parameters.precision === 'mediump' ) {
  11061. precisionstring += '\n#define MEDIUM_PRECISION';
  11062. } else if ( parameters.precision === 'lowp' ) {
  11063. precisionstring += '\n#define LOW_PRECISION';
  11064. }
  11065. return precisionstring;
  11066. }
  11067. function generateShadowMapTypeDefine( parameters ) {
  11068. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11069. if ( parameters.shadowMapType === PCFShadowMap ) {
  11070. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11071. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11072. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11073. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11074. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11075. }
  11076. return shadowMapTypeDefine;
  11077. }
  11078. function generateEnvMapTypeDefine( parameters ) {
  11079. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11080. if ( parameters.envMap ) {
  11081. switch ( parameters.envMapMode ) {
  11082. case CubeReflectionMapping:
  11083. case CubeRefractionMapping:
  11084. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11085. break;
  11086. case CubeUVReflectionMapping:
  11087. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11088. break;
  11089. }
  11090. }
  11091. return envMapTypeDefine;
  11092. }
  11093. function generateEnvMapModeDefine( parameters ) {
  11094. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11095. if ( parameters.envMap ) {
  11096. switch ( parameters.envMapMode ) {
  11097. case CubeRefractionMapping:
  11098. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11099. break;
  11100. }
  11101. }
  11102. return envMapModeDefine;
  11103. }
  11104. function generateEnvMapBlendingDefine( parameters ) {
  11105. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11106. if ( parameters.envMap ) {
  11107. switch ( parameters.combine ) {
  11108. case MultiplyOperation:
  11109. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11110. break;
  11111. case MixOperation:
  11112. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11113. break;
  11114. case AddOperation:
  11115. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11116. break;
  11117. }
  11118. }
  11119. return envMapBlendingDefine;
  11120. }
  11121. function generateCubeUVSize( parameters ) {
  11122. const imageHeight = parameters.envMapCubeUVHeight;
  11123. if ( imageHeight === null ) return null;
  11124. const maxMip = Math.log2( imageHeight ) - 2;
  11125. const texelHeight = 1.0 / imageHeight;
  11126. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11127. return { texelWidth, texelHeight, maxMip };
  11128. }
  11129. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11130. // TODO Send this event to Three.js DevTools
  11131. // console.log( 'WebGLProgram', cacheKey );
  11132. const gl = renderer.getContext();
  11133. const defines = parameters.defines;
  11134. let vertexShader = parameters.vertexShader;
  11135. let fragmentShader = parameters.fragmentShader;
  11136. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11137. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11138. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11139. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11140. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11141. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11142. const customDefines = generateDefines( defines );
  11143. const program = gl.createProgram();
  11144. let prefixVertex, prefixFragment;
  11145. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11146. if ( parameters.isRawShaderMaterial ) {
  11147. prefixVertex = [
  11148. customDefines
  11149. ].filter( filterEmptyLine ).join( '\n' );
  11150. if ( prefixVertex.length > 0 ) {
  11151. prefixVertex += '\n';
  11152. }
  11153. prefixFragment = [
  11154. customExtensions,
  11155. customDefines
  11156. ].filter( filterEmptyLine ).join( '\n' );
  11157. if ( prefixFragment.length > 0 ) {
  11158. prefixFragment += '\n';
  11159. }
  11160. } else {
  11161. prefixVertex = [
  11162. generatePrecision( parameters ),
  11163. '#define SHADER_NAME ' + parameters.shaderName,
  11164. customDefines,
  11165. parameters.instancing ? '#define USE_INSTANCING' : '',
  11166. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11167. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11168. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11169. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11170. parameters.map ? '#define USE_MAP' : '',
  11171. parameters.envMap ? '#define USE_ENVMAP' : '',
  11172. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11173. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11174. parameters.aoMap ? '#define USE_AOMAP' : '',
  11175. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11176. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11177. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11178. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11179. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11180. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11181. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11182. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11183. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11184. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11185. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11186. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11187. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11188. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11189. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11190. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11191. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11192. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11193. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11194. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11195. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11196. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11197. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11198. parameters.vertexColors ? '#define USE_COLOR' : '',
  11199. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11200. parameters.vertexUvs ? '#define USE_UV' : '',
  11201. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11202. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11203. parameters.skinning ? '#define USE_SKINNING' : '',
  11204. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11205. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11206. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11207. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11208. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11209. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11210. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11211. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11212. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11213. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11214. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11215. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11216. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11217. 'uniform mat4 modelMatrix;',
  11218. 'uniform mat4 modelViewMatrix;',
  11219. 'uniform mat4 projectionMatrix;',
  11220. 'uniform mat4 viewMatrix;',
  11221. 'uniform mat3 normalMatrix;',
  11222. 'uniform vec3 cameraPosition;',
  11223. 'uniform bool isOrthographic;',
  11224. '#ifdef USE_INSTANCING',
  11225. ' attribute mat4 instanceMatrix;',
  11226. '#endif',
  11227. '#ifdef USE_INSTANCING_COLOR',
  11228. ' attribute vec3 instanceColor;',
  11229. '#endif',
  11230. 'attribute vec3 position;',
  11231. 'attribute vec3 normal;',
  11232. 'attribute vec2 uv;',
  11233. '#ifdef USE_TANGENT',
  11234. ' attribute vec4 tangent;',
  11235. '#endif',
  11236. '#if defined( USE_COLOR_ALPHA )',
  11237. ' attribute vec4 color;',
  11238. '#elif defined( USE_COLOR )',
  11239. ' attribute vec3 color;',
  11240. '#endif',
  11241. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11242. ' attribute vec3 morphTarget0;',
  11243. ' attribute vec3 morphTarget1;',
  11244. ' attribute vec3 morphTarget2;',
  11245. ' attribute vec3 morphTarget3;',
  11246. ' #ifdef USE_MORPHNORMALS',
  11247. ' attribute vec3 morphNormal0;',
  11248. ' attribute vec3 morphNormal1;',
  11249. ' attribute vec3 morphNormal2;',
  11250. ' attribute vec3 morphNormal3;',
  11251. ' #else',
  11252. ' attribute vec3 morphTarget4;',
  11253. ' attribute vec3 morphTarget5;',
  11254. ' attribute vec3 morphTarget6;',
  11255. ' attribute vec3 morphTarget7;',
  11256. ' #endif',
  11257. '#endif',
  11258. '#ifdef USE_SKINNING',
  11259. ' attribute vec4 skinIndex;',
  11260. ' attribute vec4 skinWeight;',
  11261. '#endif',
  11262. '\n'
  11263. ].filter( filterEmptyLine ).join( '\n' );
  11264. prefixFragment = [
  11265. customExtensions,
  11266. generatePrecision( parameters ),
  11267. '#define SHADER_NAME ' + parameters.shaderName,
  11268. customDefines,
  11269. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11270. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11271. parameters.map ? '#define USE_MAP' : '',
  11272. parameters.matcap ? '#define USE_MATCAP' : '',
  11273. parameters.envMap ? '#define USE_ENVMAP' : '',
  11274. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11275. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11276. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11277. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11278. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11279. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11280. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11281. parameters.aoMap ? '#define USE_AOMAP' : '',
  11282. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11283. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11284. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11285. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11286. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11287. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11288. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11289. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11290. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11291. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11292. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11293. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11294. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11295. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11296. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11297. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11298. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11299. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11300. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11301. parameters.sheen ? '#define USE_SHEEN' : '',
  11302. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11303. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11304. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11305. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11306. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11307. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11308. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11309. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11310. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11311. parameters.vertexUvs ? '#define USE_UV' : '',
  11312. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11313. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11314. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11315. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11316. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11317. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11318. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11319. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11320. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11321. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11322. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11323. 'uniform mat4 viewMatrix;',
  11324. 'uniform vec3 cameraPosition;',
  11325. 'uniform bool isOrthographic;',
  11326. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11327. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11328. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11329. parameters.dithering ? '#define DITHERING' : '',
  11330. parameters.opaque ? '#define OPAQUE' : '',
  11331. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11332. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11333. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11334. '\n'
  11335. ].filter( filterEmptyLine ).join( '\n' );
  11336. }
  11337. vertexShader = resolveIncludes( vertexShader );
  11338. vertexShader = replaceLightNums( vertexShader, parameters );
  11339. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11340. fragmentShader = resolveIncludes( fragmentShader );
  11341. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11342. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11343. vertexShader = unrollLoops( vertexShader );
  11344. fragmentShader = unrollLoops( fragmentShader );
  11345. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11346. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11347. versionString = '#version 300 es\n';
  11348. prefixVertex = [
  11349. 'precision mediump sampler2DArray;',
  11350. '#define attribute in',
  11351. '#define varying out',
  11352. '#define texture2D texture'
  11353. ].join( '\n' ) + '\n' + prefixVertex;
  11354. prefixFragment = [
  11355. '#define varying in',
  11356. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11357. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11358. '#define gl_FragDepthEXT gl_FragDepth',
  11359. '#define texture2D texture',
  11360. '#define textureCube texture',
  11361. '#define texture2DProj textureProj',
  11362. '#define texture2DLodEXT textureLod',
  11363. '#define texture2DProjLodEXT textureProjLod',
  11364. '#define textureCubeLodEXT textureLod',
  11365. '#define texture2DGradEXT textureGrad',
  11366. '#define texture2DProjGradEXT textureProjGrad',
  11367. '#define textureCubeGradEXT textureGrad'
  11368. ].join( '\n' ) + '\n' + prefixFragment;
  11369. }
  11370. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11371. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11372. // console.log( '*VERTEX*', vertexGlsl );
  11373. // console.log( '*FRAGMENT*', fragmentGlsl );
  11374. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11375. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11376. gl.attachShader( program, glVertexShader );
  11377. gl.attachShader( program, glFragmentShader );
  11378. // Force a particular attribute to index 0.
  11379. if ( parameters.index0AttributeName !== undefined ) {
  11380. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11381. } else if ( parameters.morphTargets === true ) {
  11382. // programs with morphTargets displace position out of attribute 0
  11383. gl.bindAttribLocation( program, 0, 'position' );
  11384. }
  11385. gl.linkProgram( program );
  11386. // check for link errors
  11387. if ( renderer.debug.checkShaderErrors ) {
  11388. const programLog = gl.getProgramInfoLog( program ).trim();
  11389. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11390. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11391. let runnable = true;
  11392. let haveDiagnostics = true;
  11393. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11394. runnable = false;
  11395. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11396. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11397. console.error(
  11398. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11399. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11400. 'Program Info Log: ' + programLog + '\n' +
  11401. vertexErrors + '\n' +
  11402. fragmentErrors
  11403. );
  11404. } else if ( programLog !== '' ) {
  11405. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11406. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11407. haveDiagnostics = false;
  11408. }
  11409. if ( haveDiagnostics ) {
  11410. this.diagnostics = {
  11411. runnable: runnable,
  11412. programLog: programLog,
  11413. vertexShader: {
  11414. log: vertexLog,
  11415. prefix: prefixVertex
  11416. },
  11417. fragmentShader: {
  11418. log: fragmentLog,
  11419. prefix: prefixFragment
  11420. }
  11421. };
  11422. }
  11423. }
  11424. // Clean up
  11425. // Crashes in iOS9 and iOS10. #18402
  11426. // gl.detachShader( program, glVertexShader );
  11427. // gl.detachShader( program, glFragmentShader );
  11428. gl.deleteShader( glVertexShader );
  11429. gl.deleteShader( glFragmentShader );
  11430. // set up caching for uniform locations
  11431. let cachedUniforms;
  11432. this.getUniforms = function () {
  11433. if ( cachedUniforms === undefined ) {
  11434. cachedUniforms = new WebGLUniforms( gl, program );
  11435. }
  11436. return cachedUniforms;
  11437. };
  11438. // set up caching for attribute locations
  11439. let cachedAttributes;
  11440. this.getAttributes = function () {
  11441. if ( cachedAttributes === undefined ) {
  11442. cachedAttributes = fetchAttributeLocations( gl, program );
  11443. }
  11444. return cachedAttributes;
  11445. };
  11446. // free resource
  11447. this.destroy = function () {
  11448. bindingStates.releaseStatesOfProgram( this );
  11449. gl.deleteProgram( program );
  11450. this.program = undefined;
  11451. };
  11452. //
  11453. this.name = parameters.shaderName;
  11454. this.id = programIdCount ++;
  11455. this.cacheKey = cacheKey;
  11456. this.usedTimes = 1;
  11457. this.program = program;
  11458. this.vertexShader = glVertexShader;
  11459. this.fragmentShader = glFragmentShader;
  11460. return this;
  11461. }
  11462. let _id = 0;
  11463. class WebGLShaderCache {
  11464. constructor() {
  11465. this.shaderCache = new Map();
  11466. this.materialCache = new Map();
  11467. }
  11468. update( material ) {
  11469. const vertexShader = material.vertexShader;
  11470. const fragmentShader = material.fragmentShader;
  11471. const vertexShaderStage = this._getShaderStage( vertexShader );
  11472. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11473. const materialShaders = this._getShaderCacheForMaterial( material );
  11474. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11475. materialShaders.add( vertexShaderStage );
  11476. vertexShaderStage.usedTimes ++;
  11477. }
  11478. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11479. materialShaders.add( fragmentShaderStage );
  11480. fragmentShaderStage.usedTimes ++;
  11481. }
  11482. return this;
  11483. }
  11484. remove( material ) {
  11485. const materialShaders = this.materialCache.get( material );
  11486. for ( const shaderStage of materialShaders ) {
  11487. shaderStage.usedTimes --;
  11488. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11489. }
  11490. this.materialCache.delete( material );
  11491. return this;
  11492. }
  11493. getVertexShaderID( material ) {
  11494. return this._getShaderStage( material.vertexShader ).id;
  11495. }
  11496. getFragmentShaderID( material ) {
  11497. return this._getShaderStage( material.fragmentShader ).id;
  11498. }
  11499. dispose() {
  11500. this.shaderCache.clear();
  11501. this.materialCache.clear();
  11502. }
  11503. _getShaderCacheForMaterial( material ) {
  11504. const cache = this.materialCache;
  11505. let set = cache.get( material );
  11506. if ( set === undefined ) {
  11507. set = new Set();
  11508. cache.set( material, set );
  11509. }
  11510. return set;
  11511. }
  11512. _getShaderStage( code ) {
  11513. const cache = this.shaderCache;
  11514. let stage = cache.get( code );
  11515. if ( stage === undefined ) {
  11516. stage = new WebGLShaderStage( code );
  11517. cache.set( code, stage );
  11518. }
  11519. return stage;
  11520. }
  11521. }
  11522. class WebGLShaderStage {
  11523. constructor( code ) {
  11524. this.id = _id ++;
  11525. this.code = code;
  11526. this.usedTimes = 0;
  11527. }
  11528. }
  11529. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11530. const _programLayers = new Layers();
  11531. const _customShaders = new WebGLShaderCache();
  11532. const programs = [];
  11533. const isWebGL2 = capabilities.isWebGL2;
  11534. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11535. const vertexTextures = capabilities.vertexTextures;
  11536. let precision = capabilities.precision;
  11537. const shaderIDs = {
  11538. MeshDepthMaterial: 'depth',
  11539. MeshDistanceMaterial: 'distanceRGBA',
  11540. MeshNormalMaterial: 'normal',
  11541. MeshBasicMaterial: 'basic',
  11542. MeshLambertMaterial: 'lambert',
  11543. MeshPhongMaterial: 'phong',
  11544. MeshToonMaterial: 'toon',
  11545. MeshStandardMaterial: 'physical',
  11546. MeshPhysicalMaterial: 'physical',
  11547. MeshMatcapMaterial: 'matcap',
  11548. LineBasicMaterial: 'basic',
  11549. LineDashedMaterial: 'dashed',
  11550. PointsMaterial: 'points',
  11551. ShadowMaterial: 'shadow',
  11552. SpriteMaterial: 'sprite'
  11553. };
  11554. function getParameters( material, lights, shadows, scene, object ) {
  11555. const fog = scene.fog;
  11556. const geometry = object.geometry;
  11557. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11558. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11559. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11560. const shaderID = shaderIDs[ material.type ];
  11561. // heuristics to create shader parameters according to lights in the scene
  11562. // (not to blow over maxLights budget)
  11563. if ( material.precision !== null ) {
  11564. precision = capabilities.getMaxPrecision( material.precision );
  11565. if ( precision !== material.precision ) {
  11566. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11567. }
  11568. }
  11569. //
  11570. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11571. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11572. let morphTextureStride = 0;
  11573. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11574. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11575. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11576. //
  11577. let vertexShader, fragmentShader;
  11578. let customVertexShaderID, customFragmentShaderID;
  11579. if ( shaderID ) {
  11580. const shader = ShaderLib[ shaderID ];
  11581. vertexShader = shader.vertexShader;
  11582. fragmentShader = shader.fragmentShader;
  11583. } else {
  11584. vertexShader = material.vertexShader;
  11585. fragmentShader = material.fragmentShader;
  11586. _customShaders.update( material );
  11587. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11588. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11589. }
  11590. const currentRenderTarget = renderer.getRenderTarget();
  11591. const useAlphaTest = material.alphaTest > 0;
  11592. const useClearcoat = material.clearcoat > 0;
  11593. const useIridescence = material.iridescence > 0;
  11594. const parameters = {
  11595. isWebGL2: isWebGL2,
  11596. shaderID: shaderID,
  11597. shaderName: material.type,
  11598. vertexShader: vertexShader,
  11599. fragmentShader: fragmentShader,
  11600. defines: material.defines,
  11601. customVertexShaderID: customVertexShaderID,
  11602. customFragmentShaderID: customFragmentShaderID,
  11603. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11604. glslVersion: material.glslVersion,
  11605. precision: precision,
  11606. instancing: object.isInstancedMesh === true,
  11607. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11608. supportsVertexTextures: vertexTextures,
  11609. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11610. map: !! material.map,
  11611. matcap: !! material.matcap,
  11612. envMap: !! envMap,
  11613. envMapMode: envMap && envMap.mapping,
  11614. envMapCubeUVHeight: envMapCubeUVHeight,
  11615. lightMap: !! material.lightMap,
  11616. aoMap: !! material.aoMap,
  11617. emissiveMap: !! material.emissiveMap,
  11618. bumpMap: !! material.bumpMap,
  11619. normalMap: !! material.normalMap,
  11620. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11621. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11622. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11623. clearcoat: useClearcoat,
  11624. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11625. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11626. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11627. iridescence: useIridescence,
  11628. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11629. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11630. displacementMap: !! material.displacementMap,
  11631. roughnessMap: !! material.roughnessMap,
  11632. metalnessMap: !! material.metalnessMap,
  11633. specularMap: !! material.specularMap,
  11634. specularIntensityMap: !! material.specularIntensityMap,
  11635. specularColorMap: !! material.specularColorMap,
  11636. opaque: material.transparent === false && material.blending === NormalBlending,
  11637. alphaMap: !! material.alphaMap,
  11638. alphaTest: useAlphaTest,
  11639. gradientMap: !! material.gradientMap,
  11640. sheen: material.sheen > 0,
  11641. sheenColorMap: !! material.sheenColorMap,
  11642. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11643. transmission: material.transmission > 0,
  11644. transmissionMap: !! material.transmissionMap,
  11645. thicknessMap: !! material.thicknessMap,
  11646. combine: material.combine,
  11647. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11648. vertexColors: material.vertexColors,
  11649. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11650. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap,
  11651. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap,
  11652. fog: !! fog,
  11653. useFog: material.fog === true,
  11654. fogExp2: ( fog && fog.isFogExp2 ),
  11655. flatShading: !! material.flatShading,
  11656. sizeAttenuation: material.sizeAttenuation,
  11657. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11658. skinning: object.isSkinnedMesh === true,
  11659. morphTargets: geometry.morphAttributes.position !== undefined,
  11660. morphNormals: geometry.morphAttributes.normal !== undefined,
  11661. morphColors: geometry.morphAttributes.color !== undefined,
  11662. morphTargetsCount: morphTargetsCount,
  11663. morphTextureStride: morphTextureStride,
  11664. numDirLights: lights.directional.length,
  11665. numPointLights: lights.point.length,
  11666. numSpotLights: lights.spot.length,
  11667. numSpotLightMaps: lights.spotLightMap.length,
  11668. numRectAreaLights: lights.rectArea.length,
  11669. numHemiLights: lights.hemi.length,
  11670. numDirLightShadows: lights.directionalShadowMap.length,
  11671. numPointLightShadows: lights.pointShadowMap.length,
  11672. numSpotLightShadows: lights.spotShadowMap.length,
  11673. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11674. numClippingPlanes: clipping.numPlanes,
  11675. numClipIntersection: clipping.numIntersection,
  11676. dithering: material.dithering,
  11677. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11678. shadowMapType: renderer.shadowMap.type,
  11679. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11680. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11681. premultipliedAlpha: material.premultipliedAlpha,
  11682. doubleSided: material.side === DoubleSide,
  11683. flipSided: material.side === BackSide,
  11684. useDepthPacking: !! material.depthPacking,
  11685. depthPacking: material.depthPacking || 0,
  11686. index0AttributeName: material.index0AttributeName,
  11687. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11688. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11689. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11690. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11691. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11692. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11693. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11694. customProgramCacheKey: material.customProgramCacheKey()
  11695. };
  11696. return parameters;
  11697. }
  11698. function getProgramCacheKey( parameters ) {
  11699. const array = [];
  11700. if ( parameters.shaderID ) {
  11701. array.push( parameters.shaderID );
  11702. } else {
  11703. array.push( parameters.customVertexShaderID );
  11704. array.push( parameters.customFragmentShaderID );
  11705. }
  11706. if ( parameters.defines !== undefined ) {
  11707. for ( const name in parameters.defines ) {
  11708. array.push( name );
  11709. array.push( parameters.defines[ name ] );
  11710. }
  11711. }
  11712. if ( parameters.isRawShaderMaterial === false ) {
  11713. getProgramCacheKeyParameters( array, parameters );
  11714. getProgramCacheKeyBooleans( array, parameters );
  11715. array.push( renderer.outputEncoding );
  11716. }
  11717. array.push( parameters.customProgramCacheKey );
  11718. return array.join();
  11719. }
  11720. function getProgramCacheKeyParameters( array, parameters ) {
  11721. array.push( parameters.precision );
  11722. array.push( parameters.outputEncoding );
  11723. array.push( parameters.envMapMode );
  11724. array.push( parameters.envMapCubeUVHeight );
  11725. array.push( parameters.combine );
  11726. array.push( parameters.vertexUvs );
  11727. array.push( parameters.fogExp2 );
  11728. array.push( parameters.sizeAttenuation );
  11729. array.push( parameters.morphTargetsCount );
  11730. array.push( parameters.morphAttributeCount );
  11731. array.push( parameters.numDirLights );
  11732. array.push( parameters.numPointLights );
  11733. array.push( parameters.numSpotLights );
  11734. array.push( parameters.numSpotLightMaps );
  11735. array.push( parameters.numHemiLights );
  11736. array.push( parameters.numRectAreaLights );
  11737. array.push( parameters.numDirLightShadows );
  11738. array.push( parameters.numPointLightShadows );
  11739. array.push( parameters.numSpotLightShadows );
  11740. array.push( parameters.numSpotLightShadowsWithMaps );
  11741. array.push( parameters.shadowMapType );
  11742. array.push( parameters.toneMapping );
  11743. array.push( parameters.numClippingPlanes );
  11744. array.push( parameters.numClipIntersection );
  11745. array.push( parameters.depthPacking );
  11746. }
  11747. function getProgramCacheKeyBooleans( array, parameters ) {
  11748. _programLayers.disableAll();
  11749. if ( parameters.isWebGL2 )
  11750. _programLayers.enable( 0 );
  11751. if ( parameters.supportsVertexTextures )
  11752. _programLayers.enable( 1 );
  11753. if ( parameters.instancing )
  11754. _programLayers.enable( 2 );
  11755. if ( parameters.instancingColor )
  11756. _programLayers.enable( 3 );
  11757. if ( parameters.map )
  11758. _programLayers.enable( 4 );
  11759. if ( parameters.matcap )
  11760. _programLayers.enable( 5 );
  11761. if ( parameters.envMap )
  11762. _programLayers.enable( 6 );
  11763. if ( parameters.lightMap )
  11764. _programLayers.enable( 7 );
  11765. if ( parameters.aoMap )
  11766. _programLayers.enable( 8 );
  11767. if ( parameters.emissiveMap )
  11768. _programLayers.enable( 9 );
  11769. if ( parameters.bumpMap )
  11770. _programLayers.enable( 10 );
  11771. if ( parameters.normalMap )
  11772. _programLayers.enable( 11 );
  11773. if ( parameters.objectSpaceNormalMap )
  11774. _programLayers.enable( 12 );
  11775. if ( parameters.tangentSpaceNormalMap )
  11776. _programLayers.enable( 13 );
  11777. if ( parameters.clearcoat )
  11778. _programLayers.enable( 14 );
  11779. if ( parameters.clearcoatMap )
  11780. _programLayers.enable( 15 );
  11781. if ( parameters.clearcoatRoughnessMap )
  11782. _programLayers.enable( 16 );
  11783. if ( parameters.clearcoatNormalMap )
  11784. _programLayers.enable( 17 );
  11785. if ( parameters.iridescence )
  11786. _programLayers.enable( 18 );
  11787. if ( parameters.iridescenceMap )
  11788. _programLayers.enable( 19 );
  11789. if ( parameters.iridescenceThicknessMap )
  11790. _programLayers.enable( 20 );
  11791. if ( parameters.displacementMap )
  11792. _programLayers.enable( 21 );
  11793. if ( parameters.specularMap )
  11794. _programLayers.enable( 22 );
  11795. if ( parameters.roughnessMap )
  11796. _programLayers.enable( 23 );
  11797. if ( parameters.metalnessMap )
  11798. _programLayers.enable( 24 );
  11799. if ( parameters.gradientMap )
  11800. _programLayers.enable( 25 );
  11801. if ( parameters.alphaMap )
  11802. _programLayers.enable( 26 );
  11803. if ( parameters.alphaTest )
  11804. _programLayers.enable( 27 );
  11805. if ( parameters.vertexColors )
  11806. _programLayers.enable( 28 );
  11807. if ( parameters.vertexAlphas )
  11808. _programLayers.enable( 29 );
  11809. if ( parameters.vertexUvs )
  11810. _programLayers.enable( 30 );
  11811. if ( parameters.vertexTangents )
  11812. _programLayers.enable( 31 );
  11813. if ( parameters.uvsVertexOnly )
  11814. _programLayers.enable( 32 );
  11815. array.push( _programLayers.mask );
  11816. _programLayers.disableAll();
  11817. if ( parameters.fog )
  11818. _programLayers.enable( 0 );
  11819. if ( parameters.useFog )
  11820. _programLayers.enable( 1 );
  11821. if ( parameters.flatShading )
  11822. _programLayers.enable( 2 );
  11823. if ( parameters.logarithmicDepthBuffer )
  11824. _programLayers.enable( 3 );
  11825. if ( parameters.skinning )
  11826. _programLayers.enable( 4 );
  11827. if ( parameters.morphTargets )
  11828. _programLayers.enable( 5 );
  11829. if ( parameters.morphNormals )
  11830. _programLayers.enable( 6 );
  11831. if ( parameters.morphColors )
  11832. _programLayers.enable( 7 );
  11833. if ( parameters.premultipliedAlpha )
  11834. _programLayers.enable( 8 );
  11835. if ( parameters.shadowMapEnabled )
  11836. _programLayers.enable( 9 );
  11837. if ( parameters.physicallyCorrectLights )
  11838. _programLayers.enable( 10 );
  11839. if ( parameters.doubleSided )
  11840. _programLayers.enable( 11 );
  11841. if ( parameters.flipSided )
  11842. _programLayers.enable( 12 );
  11843. if ( parameters.useDepthPacking )
  11844. _programLayers.enable( 13 );
  11845. if ( parameters.dithering )
  11846. _programLayers.enable( 14 );
  11847. if ( parameters.specularIntensityMap )
  11848. _programLayers.enable( 15 );
  11849. if ( parameters.specularColorMap )
  11850. _programLayers.enable( 16 );
  11851. if ( parameters.transmission )
  11852. _programLayers.enable( 17 );
  11853. if ( parameters.transmissionMap )
  11854. _programLayers.enable( 18 );
  11855. if ( parameters.thicknessMap )
  11856. _programLayers.enable( 19 );
  11857. if ( parameters.sheen )
  11858. _programLayers.enable( 20 );
  11859. if ( parameters.sheenColorMap )
  11860. _programLayers.enable( 21 );
  11861. if ( parameters.sheenRoughnessMap )
  11862. _programLayers.enable( 22 );
  11863. if ( parameters.decodeVideoTexture )
  11864. _programLayers.enable( 23 );
  11865. if ( parameters.opaque )
  11866. _programLayers.enable( 24 );
  11867. array.push( _programLayers.mask );
  11868. }
  11869. function getUniforms( material ) {
  11870. const shaderID = shaderIDs[ material.type ];
  11871. let uniforms;
  11872. if ( shaderID ) {
  11873. const shader = ShaderLib[ shaderID ];
  11874. uniforms = UniformsUtils.clone( shader.uniforms );
  11875. } else {
  11876. uniforms = material.uniforms;
  11877. }
  11878. return uniforms;
  11879. }
  11880. function acquireProgram( parameters, cacheKey ) {
  11881. let program;
  11882. // Check if code has been already compiled
  11883. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11884. const preexistingProgram = programs[ p ];
  11885. if ( preexistingProgram.cacheKey === cacheKey ) {
  11886. program = preexistingProgram;
  11887. ++ program.usedTimes;
  11888. break;
  11889. }
  11890. }
  11891. if ( program === undefined ) {
  11892. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11893. programs.push( program );
  11894. }
  11895. return program;
  11896. }
  11897. function releaseProgram( program ) {
  11898. if ( -- program.usedTimes === 0 ) {
  11899. // Remove from unordered set
  11900. const i = programs.indexOf( program );
  11901. programs[ i ] = programs[ programs.length - 1 ];
  11902. programs.pop();
  11903. // Free WebGL resources
  11904. program.destroy();
  11905. }
  11906. }
  11907. function releaseShaderCache( material ) {
  11908. _customShaders.remove( material );
  11909. }
  11910. function dispose() {
  11911. _customShaders.dispose();
  11912. }
  11913. return {
  11914. getParameters: getParameters,
  11915. getProgramCacheKey: getProgramCacheKey,
  11916. getUniforms: getUniforms,
  11917. acquireProgram: acquireProgram,
  11918. releaseProgram: releaseProgram,
  11919. releaseShaderCache: releaseShaderCache,
  11920. // Exposed for resource monitoring & error feedback via renderer.info:
  11921. programs: programs,
  11922. dispose: dispose
  11923. };
  11924. }
  11925. function WebGLProperties() {
  11926. let properties = new WeakMap();
  11927. function get( object ) {
  11928. let map = properties.get( object );
  11929. if ( map === undefined ) {
  11930. map = {};
  11931. properties.set( object, map );
  11932. }
  11933. return map;
  11934. }
  11935. function remove( object ) {
  11936. properties.delete( object );
  11937. }
  11938. function update( object, key, value ) {
  11939. properties.get( object )[ key ] = value;
  11940. }
  11941. function dispose() {
  11942. properties = new WeakMap();
  11943. }
  11944. return {
  11945. get: get,
  11946. remove: remove,
  11947. update: update,
  11948. dispose: dispose
  11949. };
  11950. }
  11951. function painterSortStable( a, b ) {
  11952. if ( a.groupOrder !== b.groupOrder ) {
  11953. return a.groupOrder - b.groupOrder;
  11954. } else if ( a.renderOrder !== b.renderOrder ) {
  11955. return a.renderOrder - b.renderOrder;
  11956. } else if ( a.material.id !== b.material.id ) {
  11957. return a.material.id - b.material.id;
  11958. } else if ( a.z !== b.z ) {
  11959. return a.z - b.z;
  11960. } else {
  11961. return a.id - b.id;
  11962. }
  11963. }
  11964. function reversePainterSortStable( a, b ) {
  11965. if ( a.groupOrder !== b.groupOrder ) {
  11966. return a.groupOrder - b.groupOrder;
  11967. } else if ( a.renderOrder !== b.renderOrder ) {
  11968. return a.renderOrder - b.renderOrder;
  11969. } else if ( a.z !== b.z ) {
  11970. return b.z - a.z;
  11971. } else {
  11972. return a.id - b.id;
  11973. }
  11974. }
  11975. function WebGLRenderList() {
  11976. const renderItems = [];
  11977. let renderItemsIndex = 0;
  11978. const opaque = [];
  11979. const transmissive = [];
  11980. const transparent = [];
  11981. function init() {
  11982. renderItemsIndex = 0;
  11983. opaque.length = 0;
  11984. transmissive.length = 0;
  11985. transparent.length = 0;
  11986. }
  11987. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11988. let renderItem = renderItems[ renderItemsIndex ];
  11989. if ( renderItem === undefined ) {
  11990. renderItem = {
  11991. id: object.id,
  11992. object: object,
  11993. geometry: geometry,
  11994. material: material,
  11995. groupOrder: groupOrder,
  11996. renderOrder: object.renderOrder,
  11997. z: z,
  11998. group: group
  11999. };
  12000. renderItems[ renderItemsIndex ] = renderItem;
  12001. } else {
  12002. renderItem.id = object.id;
  12003. renderItem.object = object;
  12004. renderItem.geometry = geometry;
  12005. renderItem.material = material;
  12006. renderItem.groupOrder = groupOrder;
  12007. renderItem.renderOrder = object.renderOrder;
  12008. renderItem.z = z;
  12009. renderItem.group = group;
  12010. }
  12011. renderItemsIndex ++;
  12012. return renderItem;
  12013. }
  12014. function push( object, geometry, material, groupOrder, z, group ) {
  12015. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12016. if ( material.transmission > 0.0 ) {
  12017. transmissive.push( renderItem );
  12018. } else if ( material.transparent === true ) {
  12019. transparent.push( renderItem );
  12020. } else {
  12021. opaque.push( renderItem );
  12022. }
  12023. }
  12024. function unshift( object, geometry, material, groupOrder, z, group ) {
  12025. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12026. if ( material.transmission > 0.0 ) {
  12027. transmissive.unshift( renderItem );
  12028. } else if ( material.transparent === true ) {
  12029. transparent.unshift( renderItem );
  12030. } else {
  12031. opaque.unshift( renderItem );
  12032. }
  12033. }
  12034. function sort( customOpaqueSort, customTransparentSort ) {
  12035. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12036. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12037. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12038. }
  12039. function finish() {
  12040. // Clear references from inactive renderItems in the list
  12041. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12042. const renderItem = renderItems[ i ];
  12043. if ( renderItem.id === null ) break;
  12044. renderItem.id = null;
  12045. renderItem.object = null;
  12046. renderItem.geometry = null;
  12047. renderItem.material = null;
  12048. renderItem.group = null;
  12049. }
  12050. }
  12051. return {
  12052. opaque: opaque,
  12053. transmissive: transmissive,
  12054. transparent: transparent,
  12055. init: init,
  12056. push: push,
  12057. unshift: unshift,
  12058. finish: finish,
  12059. sort: sort
  12060. };
  12061. }
  12062. function WebGLRenderLists() {
  12063. let lists = new WeakMap();
  12064. function get( scene, renderCallDepth ) {
  12065. const listArray = lists.get( scene );
  12066. let list;
  12067. if ( listArray === undefined ) {
  12068. list = new WebGLRenderList();
  12069. lists.set( scene, [ list ] );
  12070. } else {
  12071. if ( renderCallDepth >= listArray.length ) {
  12072. list = new WebGLRenderList();
  12073. listArray.push( list );
  12074. } else {
  12075. list = listArray[ renderCallDepth ];
  12076. }
  12077. }
  12078. return list;
  12079. }
  12080. function dispose() {
  12081. lists = new WeakMap();
  12082. }
  12083. return {
  12084. get: get,
  12085. dispose: dispose
  12086. };
  12087. }
  12088. function UniformsCache() {
  12089. const lights = {};
  12090. return {
  12091. get: function ( light ) {
  12092. if ( lights[ light.id ] !== undefined ) {
  12093. return lights[ light.id ];
  12094. }
  12095. let uniforms;
  12096. switch ( light.type ) {
  12097. case 'DirectionalLight':
  12098. uniforms = {
  12099. direction: new Vector3(),
  12100. color: new Color()
  12101. };
  12102. break;
  12103. case 'SpotLight':
  12104. uniforms = {
  12105. position: new Vector3(),
  12106. direction: new Vector3(),
  12107. color: new Color(),
  12108. distance: 0,
  12109. coneCos: 0,
  12110. penumbraCos: 0,
  12111. decay: 0
  12112. };
  12113. break;
  12114. case 'PointLight':
  12115. uniforms = {
  12116. position: new Vector3(),
  12117. color: new Color(),
  12118. distance: 0,
  12119. decay: 0
  12120. };
  12121. break;
  12122. case 'HemisphereLight':
  12123. uniforms = {
  12124. direction: new Vector3(),
  12125. skyColor: new Color(),
  12126. groundColor: new Color()
  12127. };
  12128. break;
  12129. case 'RectAreaLight':
  12130. uniforms = {
  12131. color: new Color(),
  12132. position: new Vector3(),
  12133. halfWidth: new Vector3(),
  12134. halfHeight: new Vector3()
  12135. };
  12136. break;
  12137. }
  12138. lights[ light.id ] = uniforms;
  12139. return uniforms;
  12140. }
  12141. };
  12142. }
  12143. function ShadowUniformsCache() {
  12144. const lights = {};
  12145. return {
  12146. get: function ( light ) {
  12147. if ( lights[ light.id ] !== undefined ) {
  12148. return lights[ light.id ];
  12149. }
  12150. let uniforms;
  12151. switch ( light.type ) {
  12152. case 'DirectionalLight':
  12153. uniforms = {
  12154. shadowBias: 0,
  12155. shadowNormalBias: 0,
  12156. shadowRadius: 1,
  12157. shadowMapSize: new Vector2()
  12158. };
  12159. break;
  12160. case 'SpotLight':
  12161. uniforms = {
  12162. shadowBias: 0,
  12163. shadowNormalBias: 0,
  12164. shadowRadius: 1,
  12165. shadowMapSize: new Vector2()
  12166. };
  12167. break;
  12168. case 'PointLight':
  12169. uniforms = {
  12170. shadowBias: 0,
  12171. shadowNormalBias: 0,
  12172. shadowRadius: 1,
  12173. shadowMapSize: new Vector2(),
  12174. shadowCameraNear: 1,
  12175. shadowCameraFar: 1000
  12176. };
  12177. break;
  12178. // TODO (abelnation): set RectAreaLight shadow uniforms
  12179. }
  12180. lights[ light.id ] = uniforms;
  12181. return uniforms;
  12182. }
  12183. };
  12184. }
  12185. let nextVersion = 0;
  12186. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12187. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12188. }
  12189. function WebGLLights( extensions, capabilities ) {
  12190. const cache = new UniformsCache();
  12191. const shadowCache = ShadowUniformsCache();
  12192. const state = {
  12193. version: 0,
  12194. hash: {
  12195. directionalLength: - 1,
  12196. pointLength: - 1,
  12197. spotLength: - 1,
  12198. rectAreaLength: - 1,
  12199. hemiLength: - 1,
  12200. numDirectionalShadows: - 1,
  12201. numPointShadows: - 1,
  12202. numSpotShadows: - 1,
  12203. numSpotMaps: - 1
  12204. },
  12205. ambient: [ 0, 0, 0 ],
  12206. probe: [],
  12207. directional: [],
  12208. directionalShadow: [],
  12209. directionalShadowMap: [],
  12210. directionalShadowMatrix: [],
  12211. spot: [],
  12212. spotLightMap: [],
  12213. spotShadow: [],
  12214. spotShadowMap: [],
  12215. spotLightMatrix: [],
  12216. rectArea: [],
  12217. rectAreaLTC1: null,
  12218. rectAreaLTC2: null,
  12219. point: [],
  12220. pointShadow: [],
  12221. pointShadowMap: [],
  12222. pointShadowMatrix: [],
  12223. hemi: [],
  12224. numSpotLightShadowsWithMaps: 0
  12225. };
  12226. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12227. const vector3 = new Vector3();
  12228. const matrix4 = new Matrix4();
  12229. const matrix42 = new Matrix4();
  12230. function setup( lights, physicallyCorrectLights ) {
  12231. let r = 0, g = 0, b = 0;
  12232. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12233. let directionalLength = 0;
  12234. let pointLength = 0;
  12235. let spotLength = 0;
  12236. let rectAreaLength = 0;
  12237. let hemiLength = 0;
  12238. let numDirectionalShadows = 0;
  12239. let numPointShadows = 0;
  12240. let numSpotShadows = 0;
  12241. let numSpotMaps = 0;
  12242. let numSpotShadowsWithMaps = 0;
  12243. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12244. lights.sort( shadowCastingAndTexturingLightsFirst );
  12245. // artist-friendly light intensity scaling factor
  12246. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12247. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12248. const light = lights[ i ];
  12249. const color = light.color;
  12250. const intensity = light.intensity;
  12251. const distance = light.distance;
  12252. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12253. if ( light.isAmbientLight ) {
  12254. r += color.r * intensity * scaleFactor;
  12255. g += color.g * intensity * scaleFactor;
  12256. b += color.b * intensity * scaleFactor;
  12257. } else if ( light.isLightProbe ) {
  12258. for ( let j = 0; j < 9; j ++ ) {
  12259. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12260. }
  12261. } else if ( light.isDirectionalLight ) {
  12262. const uniforms = cache.get( light );
  12263. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12264. if ( light.castShadow ) {
  12265. const shadow = light.shadow;
  12266. const shadowUniforms = shadowCache.get( light );
  12267. shadowUniforms.shadowBias = shadow.bias;
  12268. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12269. shadowUniforms.shadowRadius = shadow.radius;
  12270. shadowUniforms.shadowMapSize = shadow.mapSize;
  12271. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12272. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12273. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12274. numDirectionalShadows ++;
  12275. }
  12276. state.directional[ directionalLength ] = uniforms;
  12277. directionalLength ++;
  12278. } else if ( light.isSpotLight ) {
  12279. const uniforms = cache.get( light );
  12280. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12281. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12282. uniforms.distance = distance;
  12283. uniforms.coneCos = Math.cos( light.angle );
  12284. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12285. uniforms.decay = light.decay;
  12286. state.spot[ spotLength ] = uniforms;
  12287. const shadow = light.shadow;
  12288. if ( light.map ) {
  12289. state.spotLightMap[ numSpotMaps ] = light.map;
  12290. numSpotMaps ++;
  12291. // make sure the lightMatrix is up to date
  12292. // TODO : do it if required only
  12293. shadow.updateMatrices( light );
  12294. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12295. }
  12296. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12297. if ( light.castShadow ) {
  12298. const shadowUniforms = shadowCache.get( light );
  12299. shadowUniforms.shadowBias = shadow.bias;
  12300. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12301. shadowUniforms.shadowRadius = shadow.radius;
  12302. shadowUniforms.shadowMapSize = shadow.mapSize;
  12303. state.spotShadow[ spotLength ] = shadowUniforms;
  12304. state.spotShadowMap[ spotLength ] = shadowMap;
  12305. numSpotShadows ++;
  12306. }
  12307. spotLength ++;
  12308. } else if ( light.isRectAreaLight ) {
  12309. const uniforms = cache.get( light );
  12310. uniforms.color.copy( color ).multiplyScalar( intensity );
  12311. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12312. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12313. state.rectArea[ rectAreaLength ] = uniforms;
  12314. rectAreaLength ++;
  12315. } else if ( light.isPointLight ) {
  12316. const uniforms = cache.get( light );
  12317. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12318. uniforms.distance = light.distance;
  12319. uniforms.decay = light.decay;
  12320. if ( light.castShadow ) {
  12321. const shadow = light.shadow;
  12322. const shadowUniforms = shadowCache.get( light );
  12323. shadowUniforms.shadowBias = shadow.bias;
  12324. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12325. shadowUniforms.shadowRadius = shadow.radius;
  12326. shadowUniforms.shadowMapSize = shadow.mapSize;
  12327. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12328. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12329. state.pointShadow[ pointLength ] = shadowUniforms;
  12330. state.pointShadowMap[ pointLength ] = shadowMap;
  12331. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12332. numPointShadows ++;
  12333. }
  12334. state.point[ pointLength ] = uniforms;
  12335. pointLength ++;
  12336. } else if ( light.isHemisphereLight ) {
  12337. const uniforms = cache.get( light );
  12338. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12339. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12340. state.hemi[ hemiLength ] = uniforms;
  12341. hemiLength ++;
  12342. }
  12343. }
  12344. if ( rectAreaLength > 0 ) {
  12345. if ( capabilities.isWebGL2 ) {
  12346. // WebGL 2
  12347. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12348. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12349. } else {
  12350. // WebGL 1
  12351. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12352. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12353. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12354. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12355. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12356. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12357. } else {
  12358. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12359. }
  12360. }
  12361. }
  12362. state.ambient[ 0 ] = r;
  12363. state.ambient[ 1 ] = g;
  12364. state.ambient[ 2 ] = b;
  12365. const hash = state.hash;
  12366. if ( hash.directionalLength !== directionalLength ||
  12367. hash.pointLength !== pointLength ||
  12368. hash.spotLength !== spotLength ||
  12369. hash.rectAreaLength !== rectAreaLength ||
  12370. hash.hemiLength !== hemiLength ||
  12371. hash.numDirectionalShadows !== numDirectionalShadows ||
  12372. hash.numPointShadows !== numPointShadows ||
  12373. hash.numSpotShadows !== numSpotShadows ||
  12374. hash.numSpotMaps !== numSpotMaps ) {
  12375. state.directional.length = directionalLength;
  12376. state.spot.length = spotLength;
  12377. state.rectArea.length = rectAreaLength;
  12378. state.point.length = pointLength;
  12379. state.hemi.length = hemiLength;
  12380. state.directionalShadow.length = numDirectionalShadows;
  12381. state.directionalShadowMap.length = numDirectionalShadows;
  12382. state.pointShadow.length = numPointShadows;
  12383. state.pointShadowMap.length = numPointShadows;
  12384. state.spotShadow.length = numSpotShadows;
  12385. state.spotShadowMap.length = numSpotShadows;
  12386. state.directionalShadowMatrix.length = numDirectionalShadows;
  12387. state.pointShadowMatrix.length = numPointShadows;
  12388. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12389. state.spotLightMap.length = numSpotMaps;
  12390. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12391. hash.directionalLength = directionalLength;
  12392. hash.pointLength = pointLength;
  12393. hash.spotLength = spotLength;
  12394. hash.rectAreaLength = rectAreaLength;
  12395. hash.hemiLength = hemiLength;
  12396. hash.numDirectionalShadows = numDirectionalShadows;
  12397. hash.numPointShadows = numPointShadows;
  12398. hash.numSpotShadows = numSpotShadows;
  12399. hash.numSpotMaps = numSpotMaps;
  12400. state.version = nextVersion ++;
  12401. }
  12402. }
  12403. function setupView( lights, camera ) {
  12404. let directionalLength = 0;
  12405. let pointLength = 0;
  12406. let spotLength = 0;
  12407. let rectAreaLength = 0;
  12408. let hemiLength = 0;
  12409. const viewMatrix = camera.matrixWorldInverse;
  12410. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12411. const light = lights[ i ];
  12412. if ( light.isDirectionalLight ) {
  12413. const uniforms = state.directional[ directionalLength ];
  12414. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12415. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12416. uniforms.direction.sub( vector3 );
  12417. uniforms.direction.transformDirection( viewMatrix );
  12418. directionalLength ++;
  12419. } else if ( light.isSpotLight ) {
  12420. const uniforms = state.spot[ spotLength ];
  12421. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12422. uniforms.position.applyMatrix4( viewMatrix );
  12423. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12424. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12425. uniforms.direction.sub( vector3 );
  12426. uniforms.direction.transformDirection( viewMatrix );
  12427. spotLength ++;
  12428. } else if ( light.isRectAreaLight ) {
  12429. const uniforms = state.rectArea[ rectAreaLength ];
  12430. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12431. uniforms.position.applyMatrix4( viewMatrix );
  12432. // extract local rotation of light to derive width/height half vectors
  12433. matrix42.identity();
  12434. matrix4.copy( light.matrixWorld );
  12435. matrix4.premultiply( viewMatrix );
  12436. matrix42.extractRotation( matrix4 );
  12437. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12438. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12439. uniforms.halfWidth.applyMatrix4( matrix42 );
  12440. uniforms.halfHeight.applyMatrix4( matrix42 );
  12441. rectAreaLength ++;
  12442. } else if ( light.isPointLight ) {
  12443. const uniforms = state.point[ pointLength ];
  12444. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12445. uniforms.position.applyMatrix4( viewMatrix );
  12446. pointLength ++;
  12447. } else if ( light.isHemisphereLight ) {
  12448. const uniforms = state.hemi[ hemiLength ];
  12449. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12450. uniforms.direction.transformDirection( viewMatrix );
  12451. hemiLength ++;
  12452. }
  12453. }
  12454. }
  12455. return {
  12456. setup: setup,
  12457. setupView: setupView,
  12458. state: state
  12459. };
  12460. }
  12461. function WebGLRenderState( extensions, capabilities ) {
  12462. const lights = new WebGLLights( extensions, capabilities );
  12463. const lightsArray = [];
  12464. const shadowsArray = [];
  12465. function init() {
  12466. lightsArray.length = 0;
  12467. shadowsArray.length = 0;
  12468. }
  12469. function pushLight( light ) {
  12470. lightsArray.push( light );
  12471. }
  12472. function pushShadow( shadowLight ) {
  12473. shadowsArray.push( shadowLight );
  12474. }
  12475. function setupLights( physicallyCorrectLights ) {
  12476. lights.setup( lightsArray, physicallyCorrectLights );
  12477. }
  12478. function setupLightsView( camera ) {
  12479. lights.setupView( lightsArray, camera );
  12480. }
  12481. const state = {
  12482. lightsArray: lightsArray,
  12483. shadowsArray: shadowsArray,
  12484. lights: lights
  12485. };
  12486. return {
  12487. init: init,
  12488. state: state,
  12489. setupLights: setupLights,
  12490. setupLightsView: setupLightsView,
  12491. pushLight: pushLight,
  12492. pushShadow: pushShadow
  12493. };
  12494. }
  12495. function WebGLRenderStates( extensions, capabilities ) {
  12496. let renderStates = new WeakMap();
  12497. function get( scene, renderCallDepth = 0 ) {
  12498. const renderStateArray = renderStates.get( scene );
  12499. let renderState;
  12500. if ( renderStateArray === undefined ) {
  12501. renderState = new WebGLRenderState( extensions, capabilities );
  12502. renderStates.set( scene, [ renderState ] );
  12503. } else {
  12504. if ( renderCallDepth >= renderStateArray.length ) {
  12505. renderState = new WebGLRenderState( extensions, capabilities );
  12506. renderStateArray.push( renderState );
  12507. } else {
  12508. renderState = renderStateArray[ renderCallDepth ];
  12509. }
  12510. }
  12511. return renderState;
  12512. }
  12513. function dispose() {
  12514. renderStates = new WeakMap();
  12515. }
  12516. return {
  12517. get: get,
  12518. dispose: dispose
  12519. };
  12520. }
  12521. class MeshDepthMaterial extends Material {
  12522. constructor( parameters ) {
  12523. super();
  12524. this.isMeshDepthMaterial = true;
  12525. this.type = 'MeshDepthMaterial';
  12526. this.depthPacking = BasicDepthPacking;
  12527. this.map = null;
  12528. this.alphaMap = null;
  12529. this.displacementMap = null;
  12530. this.displacementScale = 1;
  12531. this.displacementBias = 0;
  12532. this.wireframe = false;
  12533. this.wireframeLinewidth = 1;
  12534. this.setValues( parameters );
  12535. }
  12536. copy( source ) {
  12537. super.copy( source );
  12538. this.depthPacking = source.depthPacking;
  12539. this.map = source.map;
  12540. this.alphaMap = source.alphaMap;
  12541. this.displacementMap = source.displacementMap;
  12542. this.displacementScale = source.displacementScale;
  12543. this.displacementBias = source.displacementBias;
  12544. this.wireframe = source.wireframe;
  12545. this.wireframeLinewidth = source.wireframeLinewidth;
  12546. return this;
  12547. }
  12548. }
  12549. class MeshDistanceMaterial extends Material {
  12550. constructor( parameters ) {
  12551. super();
  12552. this.isMeshDistanceMaterial = true;
  12553. this.type = 'MeshDistanceMaterial';
  12554. this.referencePosition = new Vector3();
  12555. this.nearDistance = 1;
  12556. this.farDistance = 1000;
  12557. this.map = null;
  12558. this.alphaMap = null;
  12559. this.displacementMap = null;
  12560. this.displacementScale = 1;
  12561. this.displacementBias = 0;
  12562. this.setValues( parameters );
  12563. }
  12564. copy( source ) {
  12565. super.copy( source );
  12566. this.referencePosition.copy( source.referencePosition );
  12567. this.nearDistance = source.nearDistance;
  12568. this.farDistance = source.farDistance;
  12569. this.map = source.map;
  12570. this.alphaMap = source.alphaMap;
  12571. this.displacementMap = source.displacementMap;
  12572. this.displacementScale = source.displacementScale;
  12573. this.displacementBias = source.displacementBias;
  12574. return this;
  12575. }
  12576. }
  12577. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12578. 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}";
  12579. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12580. let _frustum = new Frustum();
  12581. const _shadowMapSize = new Vector2(),
  12582. _viewportSize = new Vector2(),
  12583. _viewport = new Vector4(),
  12584. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12585. _distanceMaterial = new MeshDistanceMaterial(),
  12586. _materialCache = {},
  12587. _maxTextureSize = _capabilities.maxTextureSize;
  12588. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12589. const shadowMaterialVertical = new ShaderMaterial( {
  12590. defines: {
  12591. VSM_SAMPLES: 8
  12592. },
  12593. uniforms: {
  12594. shadow_pass: { value: null },
  12595. resolution: { value: new Vector2() },
  12596. radius: { value: 4.0 }
  12597. },
  12598. vertexShader: vertex,
  12599. fragmentShader: fragment
  12600. } );
  12601. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12602. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12603. const fullScreenTri = new BufferGeometry();
  12604. fullScreenTri.setAttribute(
  12605. 'position',
  12606. new BufferAttribute(
  12607. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12608. 3
  12609. )
  12610. );
  12611. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12612. const scope = this;
  12613. this.enabled = false;
  12614. this.autoUpdate = true;
  12615. this.needsUpdate = false;
  12616. this.type = PCFShadowMap;
  12617. this.render = function ( lights, scene, camera ) {
  12618. if ( scope.enabled === false ) return;
  12619. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12620. if ( lights.length === 0 ) return;
  12621. const currentRenderTarget = _renderer.getRenderTarget();
  12622. const activeCubeFace = _renderer.getActiveCubeFace();
  12623. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12624. const _state = _renderer.state;
  12625. // Set GL state for depth map.
  12626. _state.setBlending( NoBlending );
  12627. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12628. _state.buffers.depth.setTest( true );
  12629. _state.setScissorTest( false );
  12630. // render depth map
  12631. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12632. const light = lights[ i ];
  12633. const shadow = light.shadow;
  12634. if ( shadow === undefined ) {
  12635. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12636. continue;
  12637. }
  12638. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12639. _shadowMapSize.copy( shadow.mapSize );
  12640. const shadowFrameExtents = shadow.getFrameExtents();
  12641. _shadowMapSize.multiply( shadowFrameExtents );
  12642. _viewportSize.copy( shadow.mapSize );
  12643. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12644. if ( _shadowMapSize.x > _maxTextureSize ) {
  12645. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12646. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12647. shadow.mapSize.x = _viewportSize.x;
  12648. }
  12649. if ( _shadowMapSize.y > _maxTextureSize ) {
  12650. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12651. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12652. shadow.mapSize.y = _viewportSize.y;
  12653. }
  12654. }
  12655. if ( shadow.map === null ) {
  12656. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12657. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12658. shadow.map.texture.name = light.name + '.shadowMap';
  12659. shadow.camera.updateProjectionMatrix();
  12660. }
  12661. _renderer.setRenderTarget( shadow.map );
  12662. _renderer.clear();
  12663. const viewportCount = shadow.getViewportCount();
  12664. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12665. const viewport = shadow.getViewport( vp );
  12666. _viewport.set(
  12667. _viewportSize.x * viewport.x,
  12668. _viewportSize.y * viewport.y,
  12669. _viewportSize.x * viewport.z,
  12670. _viewportSize.y * viewport.w
  12671. );
  12672. _state.viewport( _viewport );
  12673. shadow.updateMatrices( light, vp );
  12674. _frustum = shadow.getFrustum();
  12675. renderObject( scene, camera, shadow.camera, light, this.type );
  12676. }
  12677. // do blur pass for VSM
  12678. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12679. VSMPass( shadow, camera );
  12680. }
  12681. shadow.needsUpdate = false;
  12682. }
  12683. scope.needsUpdate = false;
  12684. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12685. };
  12686. function VSMPass( shadow, camera ) {
  12687. const geometry = _objects.update( fullScreenMesh );
  12688. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12689. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12690. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12691. shadowMaterialVertical.needsUpdate = true;
  12692. shadowMaterialHorizontal.needsUpdate = true;
  12693. }
  12694. if ( shadow.mapPass === null ) {
  12695. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12696. }
  12697. // vertical pass
  12698. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12699. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12700. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12701. _renderer.setRenderTarget( shadow.mapPass );
  12702. _renderer.clear();
  12703. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12704. // horizontal pass
  12705. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12706. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12707. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12708. _renderer.setRenderTarget( shadow.map );
  12709. _renderer.clear();
  12710. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12711. }
  12712. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12713. let result = null;
  12714. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12715. if ( customMaterial !== undefined ) {
  12716. result = customMaterial;
  12717. } else {
  12718. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12719. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12720. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12721. ( material.alphaMap && material.alphaTest > 0 ) ||
  12722. ( material.map && material.alphaTest > 0 ) ) {
  12723. // in this case we need a unique material instance reflecting the
  12724. // appropriate state
  12725. const keyA = result.uuid, keyB = material.uuid;
  12726. let materialsForVariant = _materialCache[ keyA ];
  12727. if ( materialsForVariant === undefined ) {
  12728. materialsForVariant = {};
  12729. _materialCache[ keyA ] = materialsForVariant;
  12730. }
  12731. let cachedMaterial = materialsForVariant[ keyB ];
  12732. if ( cachedMaterial === undefined ) {
  12733. cachedMaterial = result.clone();
  12734. materialsForVariant[ keyB ] = cachedMaterial;
  12735. }
  12736. result = cachedMaterial;
  12737. }
  12738. }
  12739. result.visible = material.visible;
  12740. result.wireframe = material.wireframe;
  12741. if ( type === VSMShadowMap ) {
  12742. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12743. } else {
  12744. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12745. }
  12746. result.alphaMap = material.alphaMap;
  12747. result.alphaTest = material.alphaTest;
  12748. result.map = material.map;
  12749. result.clipShadows = material.clipShadows;
  12750. result.clippingPlanes = material.clippingPlanes;
  12751. result.clipIntersection = material.clipIntersection;
  12752. result.displacementMap = material.displacementMap;
  12753. result.displacementScale = material.displacementScale;
  12754. result.displacementBias = material.displacementBias;
  12755. result.wireframeLinewidth = material.wireframeLinewidth;
  12756. result.linewidth = material.linewidth;
  12757. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12758. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12759. result.nearDistance = shadowCameraNear;
  12760. result.farDistance = shadowCameraFar;
  12761. }
  12762. return result;
  12763. }
  12764. function renderObject( object, camera, shadowCamera, light, type ) {
  12765. if ( object.visible === false ) return;
  12766. const visible = object.layers.test( camera.layers );
  12767. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12768. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12769. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12770. const geometry = _objects.update( object );
  12771. const material = object.material;
  12772. if ( Array.isArray( material ) ) {
  12773. const groups = geometry.groups;
  12774. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12775. const group = groups[ k ];
  12776. const groupMaterial = material[ group.materialIndex ];
  12777. if ( groupMaterial && groupMaterial.visible ) {
  12778. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12779. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12780. }
  12781. }
  12782. } else if ( material.visible ) {
  12783. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12784. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12785. }
  12786. }
  12787. }
  12788. const children = object.children;
  12789. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12790. renderObject( children[ i ], camera, shadowCamera, light, type );
  12791. }
  12792. }
  12793. }
  12794. function WebGLState( gl, extensions, capabilities ) {
  12795. const isWebGL2 = capabilities.isWebGL2;
  12796. function ColorBuffer() {
  12797. let locked = false;
  12798. const color = new Vector4();
  12799. let currentColorMask = null;
  12800. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12801. return {
  12802. setMask: function ( colorMask ) {
  12803. if ( currentColorMask !== colorMask && ! locked ) {
  12804. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12805. currentColorMask = colorMask;
  12806. }
  12807. },
  12808. setLocked: function ( lock ) {
  12809. locked = lock;
  12810. },
  12811. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12812. if ( premultipliedAlpha === true ) {
  12813. r *= a; g *= a; b *= a;
  12814. }
  12815. color.set( r, g, b, a );
  12816. if ( currentColorClear.equals( color ) === false ) {
  12817. gl.clearColor( r, g, b, a );
  12818. currentColorClear.copy( color );
  12819. }
  12820. },
  12821. reset: function () {
  12822. locked = false;
  12823. currentColorMask = null;
  12824. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12825. }
  12826. };
  12827. }
  12828. function DepthBuffer() {
  12829. let locked = false;
  12830. let currentDepthMask = null;
  12831. let currentDepthFunc = null;
  12832. let currentDepthClear = null;
  12833. return {
  12834. setTest: function ( depthTest ) {
  12835. if ( depthTest ) {
  12836. enable( gl.DEPTH_TEST );
  12837. } else {
  12838. disable( gl.DEPTH_TEST );
  12839. }
  12840. },
  12841. setMask: function ( depthMask ) {
  12842. if ( currentDepthMask !== depthMask && ! locked ) {
  12843. gl.depthMask( depthMask );
  12844. currentDepthMask = depthMask;
  12845. }
  12846. },
  12847. setFunc: function ( depthFunc ) {
  12848. if ( currentDepthFunc !== depthFunc ) {
  12849. switch ( depthFunc ) {
  12850. case NeverDepth:
  12851. gl.depthFunc( gl.NEVER );
  12852. break;
  12853. case AlwaysDepth:
  12854. gl.depthFunc( gl.ALWAYS );
  12855. break;
  12856. case LessDepth:
  12857. gl.depthFunc( gl.LESS );
  12858. break;
  12859. case LessEqualDepth:
  12860. gl.depthFunc( gl.LEQUAL );
  12861. break;
  12862. case EqualDepth:
  12863. gl.depthFunc( gl.EQUAL );
  12864. break;
  12865. case GreaterEqualDepth:
  12866. gl.depthFunc( gl.GEQUAL );
  12867. break;
  12868. case GreaterDepth:
  12869. gl.depthFunc( gl.GREATER );
  12870. break;
  12871. case NotEqualDepth:
  12872. gl.depthFunc( gl.NOTEQUAL );
  12873. break;
  12874. default:
  12875. gl.depthFunc( gl.LEQUAL );
  12876. }
  12877. currentDepthFunc = depthFunc;
  12878. }
  12879. },
  12880. setLocked: function ( lock ) {
  12881. locked = lock;
  12882. },
  12883. setClear: function ( depth ) {
  12884. if ( currentDepthClear !== depth ) {
  12885. gl.clearDepth( depth );
  12886. currentDepthClear = depth;
  12887. }
  12888. },
  12889. reset: function () {
  12890. locked = false;
  12891. currentDepthMask = null;
  12892. currentDepthFunc = null;
  12893. currentDepthClear = null;
  12894. }
  12895. };
  12896. }
  12897. function StencilBuffer() {
  12898. let locked = false;
  12899. let currentStencilMask = null;
  12900. let currentStencilFunc = null;
  12901. let currentStencilRef = null;
  12902. let currentStencilFuncMask = null;
  12903. let currentStencilFail = null;
  12904. let currentStencilZFail = null;
  12905. let currentStencilZPass = null;
  12906. let currentStencilClear = null;
  12907. return {
  12908. setTest: function ( stencilTest ) {
  12909. if ( ! locked ) {
  12910. if ( stencilTest ) {
  12911. enable( gl.STENCIL_TEST );
  12912. } else {
  12913. disable( gl.STENCIL_TEST );
  12914. }
  12915. }
  12916. },
  12917. setMask: function ( stencilMask ) {
  12918. if ( currentStencilMask !== stencilMask && ! locked ) {
  12919. gl.stencilMask( stencilMask );
  12920. currentStencilMask = stencilMask;
  12921. }
  12922. },
  12923. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12924. if ( currentStencilFunc !== stencilFunc ||
  12925. currentStencilRef !== stencilRef ||
  12926. currentStencilFuncMask !== stencilMask ) {
  12927. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12928. currentStencilFunc = stencilFunc;
  12929. currentStencilRef = stencilRef;
  12930. currentStencilFuncMask = stencilMask;
  12931. }
  12932. },
  12933. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12934. if ( currentStencilFail !== stencilFail ||
  12935. currentStencilZFail !== stencilZFail ||
  12936. currentStencilZPass !== stencilZPass ) {
  12937. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12938. currentStencilFail = stencilFail;
  12939. currentStencilZFail = stencilZFail;
  12940. currentStencilZPass = stencilZPass;
  12941. }
  12942. },
  12943. setLocked: function ( lock ) {
  12944. locked = lock;
  12945. },
  12946. setClear: function ( stencil ) {
  12947. if ( currentStencilClear !== stencil ) {
  12948. gl.clearStencil( stencil );
  12949. currentStencilClear = stencil;
  12950. }
  12951. },
  12952. reset: function () {
  12953. locked = false;
  12954. currentStencilMask = null;
  12955. currentStencilFunc = null;
  12956. currentStencilRef = null;
  12957. currentStencilFuncMask = null;
  12958. currentStencilFail = null;
  12959. currentStencilZFail = null;
  12960. currentStencilZPass = null;
  12961. currentStencilClear = null;
  12962. }
  12963. };
  12964. }
  12965. //
  12966. const colorBuffer = new ColorBuffer();
  12967. const depthBuffer = new DepthBuffer();
  12968. const stencilBuffer = new StencilBuffer();
  12969. const uboBindings = new WeakMap();
  12970. const uboProgramMap = new WeakMap();
  12971. let enabledCapabilities = {};
  12972. let currentBoundFramebuffers = {};
  12973. let currentDrawbuffers = new WeakMap();
  12974. let defaultDrawbuffers = [];
  12975. let currentProgram = null;
  12976. let currentBlendingEnabled = false;
  12977. let currentBlending = null;
  12978. let currentBlendEquation = null;
  12979. let currentBlendSrc = null;
  12980. let currentBlendDst = null;
  12981. let currentBlendEquationAlpha = null;
  12982. let currentBlendSrcAlpha = null;
  12983. let currentBlendDstAlpha = null;
  12984. let currentPremultipledAlpha = false;
  12985. let currentFlipSided = null;
  12986. let currentCullFace = null;
  12987. let currentLineWidth = null;
  12988. let currentPolygonOffsetFactor = null;
  12989. let currentPolygonOffsetUnits = null;
  12990. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  12991. let lineWidthAvailable = false;
  12992. let version = 0;
  12993. const glVersion = gl.getParameter( gl.VERSION );
  12994. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12995. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12996. lineWidthAvailable = ( version >= 1.0 );
  12997. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12998. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12999. lineWidthAvailable = ( version >= 2.0 );
  13000. }
  13001. let currentTextureSlot = null;
  13002. let currentBoundTextures = {};
  13003. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13004. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13005. const currentScissor = new Vector4().fromArray( scissorParam );
  13006. const currentViewport = new Vector4().fromArray( viewportParam );
  13007. function createTexture( type, target, count ) {
  13008. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13009. const texture = gl.createTexture();
  13010. gl.bindTexture( type, texture );
  13011. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13012. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13013. for ( let i = 0; i < count; i ++ ) {
  13014. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13015. }
  13016. return texture;
  13017. }
  13018. const emptyTextures = {};
  13019. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13020. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13021. // init
  13022. colorBuffer.setClear( 0, 0, 0, 1 );
  13023. depthBuffer.setClear( 1 );
  13024. stencilBuffer.setClear( 0 );
  13025. enable( gl.DEPTH_TEST );
  13026. depthBuffer.setFunc( LessEqualDepth );
  13027. setFlipSided( false );
  13028. setCullFace( CullFaceBack );
  13029. enable( gl.CULL_FACE );
  13030. setBlending( NoBlending );
  13031. //
  13032. function enable( id ) {
  13033. if ( enabledCapabilities[ id ] !== true ) {
  13034. gl.enable( id );
  13035. enabledCapabilities[ id ] = true;
  13036. }
  13037. }
  13038. function disable( id ) {
  13039. if ( enabledCapabilities[ id ] !== false ) {
  13040. gl.disable( id );
  13041. enabledCapabilities[ id ] = false;
  13042. }
  13043. }
  13044. function bindFramebuffer( target, framebuffer ) {
  13045. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13046. gl.bindFramebuffer( target, framebuffer );
  13047. currentBoundFramebuffers[ target ] = framebuffer;
  13048. if ( isWebGL2 ) {
  13049. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13050. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13051. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13052. }
  13053. if ( target === gl.FRAMEBUFFER ) {
  13054. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13055. }
  13056. }
  13057. return true;
  13058. }
  13059. return false;
  13060. }
  13061. function drawBuffers( renderTarget, framebuffer ) {
  13062. let drawBuffers = defaultDrawbuffers;
  13063. let needsUpdate = false;
  13064. if ( renderTarget ) {
  13065. drawBuffers = currentDrawbuffers.get( framebuffer );
  13066. if ( drawBuffers === undefined ) {
  13067. drawBuffers = [];
  13068. currentDrawbuffers.set( framebuffer, drawBuffers );
  13069. }
  13070. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13071. const textures = renderTarget.texture;
  13072. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13073. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13074. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13075. }
  13076. drawBuffers.length = textures.length;
  13077. needsUpdate = true;
  13078. }
  13079. } else {
  13080. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13081. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13082. needsUpdate = true;
  13083. }
  13084. }
  13085. } else {
  13086. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13087. drawBuffers[ 0 ] = gl.BACK;
  13088. needsUpdate = true;
  13089. }
  13090. }
  13091. if ( needsUpdate ) {
  13092. if ( capabilities.isWebGL2 ) {
  13093. gl.drawBuffers( drawBuffers );
  13094. } else {
  13095. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13096. }
  13097. }
  13098. }
  13099. function useProgram( program ) {
  13100. if ( currentProgram !== program ) {
  13101. gl.useProgram( program );
  13102. currentProgram = program;
  13103. return true;
  13104. }
  13105. return false;
  13106. }
  13107. const equationToGL = {
  13108. [ AddEquation ]: gl.FUNC_ADD,
  13109. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13110. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13111. };
  13112. if ( isWebGL2 ) {
  13113. equationToGL[ MinEquation ] = gl.MIN;
  13114. equationToGL[ MaxEquation ] = gl.MAX;
  13115. } else {
  13116. const extension = extensions.get( 'EXT_blend_minmax' );
  13117. if ( extension !== null ) {
  13118. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13119. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13120. }
  13121. }
  13122. const factorToGL = {
  13123. [ ZeroFactor ]: gl.ZERO,
  13124. [ OneFactor ]: gl.ONE,
  13125. [ SrcColorFactor ]: gl.SRC_COLOR,
  13126. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13127. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13128. [ DstColorFactor ]: gl.DST_COLOR,
  13129. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13130. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13131. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13132. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13133. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13134. };
  13135. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13136. if ( blending === NoBlending ) {
  13137. if ( currentBlendingEnabled === true ) {
  13138. disable( gl.BLEND );
  13139. currentBlendingEnabled = false;
  13140. }
  13141. return;
  13142. }
  13143. if ( currentBlendingEnabled === false ) {
  13144. enable( gl.BLEND );
  13145. currentBlendingEnabled = true;
  13146. }
  13147. if ( blending !== CustomBlending ) {
  13148. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13149. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13150. gl.blendEquation( gl.FUNC_ADD );
  13151. currentBlendEquation = AddEquation;
  13152. currentBlendEquationAlpha = AddEquation;
  13153. }
  13154. if ( premultipliedAlpha ) {
  13155. switch ( blending ) {
  13156. case NormalBlending:
  13157. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13158. break;
  13159. case AdditiveBlending:
  13160. gl.blendFunc( gl.ONE, gl.ONE );
  13161. break;
  13162. case SubtractiveBlending:
  13163. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13164. break;
  13165. case MultiplyBlending:
  13166. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13167. break;
  13168. default:
  13169. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13170. break;
  13171. }
  13172. } else {
  13173. switch ( blending ) {
  13174. case NormalBlending:
  13175. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13176. break;
  13177. case AdditiveBlending:
  13178. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13179. break;
  13180. case SubtractiveBlending:
  13181. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13182. break;
  13183. case MultiplyBlending:
  13184. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13185. break;
  13186. default:
  13187. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13188. break;
  13189. }
  13190. }
  13191. currentBlendSrc = null;
  13192. currentBlendDst = null;
  13193. currentBlendSrcAlpha = null;
  13194. currentBlendDstAlpha = null;
  13195. currentBlending = blending;
  13196. currentPremultipledAlpha = premultipliedAlpha;
  13197. }
  13198. return;
  13199. }
  13200. // custom blending
  13201. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13202. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13203. blendDstAlpha = blendDstAlpha || blendDst;
  13204. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13205. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13206. currentBlendEquation = blendEquation;
  13207. currentBlendEquationAlpha = blendEquationAlpha;
  13208. }
  13209. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13210. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13211. currentBlendSrc = blendSrc;
  13212. currentBlendDst = blendDst;
  13213. currentBlendSrcAlpha = blendSrcAlpha;
  13214. currentBlendDstAlpha = blendDstAlpha;
  13215. }
  13216. currentBlending = blending;
  13217. currentPremultipledAlpha = false;
  13218. }
  13219. function setMaterial( material, frontFaceCW ) {
  13220. material.side === DoubleSide
  13221. ? disable( gl.CULL_FACE )
  13222. : enable( gl.CULL_FACE );
  13223. let flipSided = ( material.side === BackSide );
  13224. if ( frontFaceCW ) flipSided = ! flipSided;
  13225. setFlipSided( flipSided );
  13226. ( material.blending === NormalBlending && material.transparent === false )
  13227. ? setBlending( NoBlending )
  13228. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13229. depthBuffer.setFunc( material.depthFunc );
  13230. depthBuffer.setTest( material.depthTest );
  13231. depthBuffer.setMask( material.depthWrite );
  13232. colorBuffer.setMask( material.colorWrite );
  13233. const stencilWrite = material.stencilWrite;
  13234. stencilBuffer.setTest( stencilWrite );
  13235. if ( stencilWrite ) {
  13236. stencilBuffer.setMask( material.stencilWriteMask );
  13237. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13238. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13239. }
  13240. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13241. material.alphaToCoverage === true
  13242. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13243. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13244. }
  13245. //
  13246. function setFlipSided( flipSided ) {
  13247. if ( currentFlipSided !== flipSided ) {
  13248. if ( flipSided ) {
  13249. gl.frontFace( gl.CW );
  13250. } else {
  13251. gl.frontFace( gl.CCW );
  13252. }
  13253. currentFlipSided = flipSided;
  13254. }
  13255. }
  13256. function setCullFace( cullFace ) {
  13257. if ( cullFace !== CullFaceNone ) {
  13258. enable( gl.CULL_FACE );
  13259. if ( cullFace !== currentCullFace ) {
  13260. if ( cullFace === CullFaceBack ) {
  13261. gl.cullFace( gl.BACK );
  13262. } else if ( cullFace === CullFaceFront ) {
  13263. gl.cullFace( gl.FRONT );
  13264. } else {
  13265. gl.cullFace( gl.FRONT_AND_BACK );
  13266. }
  13267. }
  13268. } else {
  13269. disable( gl.CULL_FACE );
  13270. }
  13271. currentCullFace = cullFace;
  13272. }
  13273. function setLineWidth( width ) {
  13274. if ( width !== currentLineWidth ) {
  13275. if ( lineWidthAvailable ) gl.lineWidth( width );
  13276. currentLineWidth = width;
  13277. }
  13278. }
  13279. function setPolygonOffset( polygonOffset, factor, units ) {
  13280. if ( polygonOffset ) {
  13281. enable( gl.POLYGON_OFFSET_FILL );
  13282. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13283. gl.polygonOffset( factor, units );
  13284. currentPolygonOffsetFactor = factor;
  13285. currentPolygonOffsetUnits = units;
  13286. }
  13287. } else {
  13288. disable( gl.POLYGON_OFFSET_FILL );
  13289. }
  13290. }
  13291. function setScissorTest( scissorTest ) {
  13292. if ( scissorTest ) {
  13293. enable( gl.SCISSOR_TEST );
  13294. } else {
  13295. disable( gl.SCISSOR_TEST );
  13296. }
  13297. }
  13298. // texture
  13299. function activeTexture( webglSlot ) {
  13300. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13301. if ( currentTextureSlot !== webglSlot ) {
  13302. gl.activeTexture( webglSlot );
  13303. currentTextureSlot = webglSlot;
  13304. }
  13305. }
  13306. function bindTexture( webglType, webglTexture, webglSlot ) {
  13307. if ( webglSlot === undefined ) {
  13308. if ( currentTextureSlot === null ) {
  13309. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13310. } else {
  13311. webglSlot = currentTextureSlot;
  13312. }
  13313. }
  13314. let boundTexture = currentBoundTextures[ webglSlot ];
  13315. if ( boundTexture === undefined ) {
  13316. boundTexture = { type: undefined, texture: undefined };
  13317. currentBoundTextures[ webglSlot ] = boundTexture;
  13318. }
  13319. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13320. if ( currentTextureSlot !== webglSlot ) {
  13321. gl.activeTexture( webglSlot );
  13322. currentTextureSlot = webglSlot;
  13323. }
  13324. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13325. boundTexture.type = webglType;
  13326. boundTexture.texture = webglTexture;
  13327. }
  13328. }
  13329. function unbindTexture() {
  13330. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13331. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13332. gl.bindTexture( boundTexture.type, null );
  13333. boundTexture.type = undefined;
  13334. boundTexture.texture = undefined;
  13335. }
  13336. }
  13337. function compressedTexImage2D() {
  13338. try {
  13339. gl.compressedTexImage2D.apply( gl, arguments );
  13340. } catch ( error ) {
  13341. console.error( 'THREE.WebGLState:', error );
  13342. }
  13343. }
  13344. function compressedTexImage3D() {
  13345. try {
  13346. gl.compressedTexImage3D.apply( gl, arguments );
  13347. } catch ( error ) {
  13348. console.error( 'THREE.WebGLState:', error );
  13349. }
  13350. }
  13351. function texSubImage2D() {
  13352. try {
  13353. gl.texSubImage2D.apply( gl, arguments );
  13354. } catch ( error ) {
  13355. console.error( 'THREE.WebGLState:', error );
  13356. }
  13357. }
  13358. function texSubImage3D() {
  13359. try {
  13360. gl.texSubImage3D.apply( gl, arguments );
  13361. } catch ( error ) {
  13362. console.error( 'THREE.WebGLState:', error );
  13363. }
  13364. }
  13365. function compressedTexSubImage2D() {
  13366. try {
  13367. gl.compressedTexSubImage2D.apply( gl, arguments );
  13368. } catch ( error ) {
  13369. console.error( 'THREE.WebGLState:', error );
  13370. }
  13371. }
  13372. function compressedTexSubImage3D() {
  13373. try {
  13374. gl.compressedTexSubImage3D.apply( gl, arguments );
  13375. } catch ( error ) {
  13376. console.error( 'THREE.WebGLState:', error );
  13377. }
  13378. }
  13379. function texStorage2D() {
  13380. try {
  13381. gl.texStorage2D.apply( gl, arguments );
  13382. } catch ( error ) {
  13383. console.error( 'THREE.WebGLState:', error );
  13384. }
  13385. }
  13386. function texStorage3D() {
  13387. try {
  13388. gl.texStorage3D.apply( gl, arguments );
  13389. } catch ( error ) {
  13390. console.error( 'THREE.WebGLState:', error );
  13391. }
  13392. }
  13393. function texImage2D() {
  13394. try {
  13395. gl.texImage2D.apply( gl, arguments );
  13396. } catch ( error ) {
  13397. console.error( 'THREE.WebGLState:', error );
  13398. }
  13399. }
  13400. function texImage3D() {
  13401. try {
  13402. gl.texImage3D.apply( gl, arguments );
  13403. } catch ( error ) {
  13404. console.error( 'THREE.WebGLState:', error );
  13405. }
  13406. }
  13407. //
  13408. function scissor( scissor ) {
  13409. if ( currentScissor.equals( scissor ) === false ) {
  13410. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13411. currentScissor.copy( scissor );
  13412. }
  13413. }
  13414. function viewport( viewport ) {
  13415. if ( currentViewport.equals( viewport ) === false ) {
  13416. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13417. currentViewport.copy( viewport );
  13418. }
  13419. }
  13420. function updateUBOMapping( uniformsGroup, program ) {
  13421. let mapping = uboProgramMap.get( program );
  13422. if ( mapping === undefined ) {
  13423. mapping = new WeakMap();
  13424. uboProgramMap.set( program, mapping );
  13425. }
  13426. let blockIndex = mapping.get( uniformsGroup );
  13427. if ( blockIndex === undefined ) {
  13428. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13429. mapping.set( uniformsGroup, blockIndex );
  13430. }
  13431. }
  13432. function uniformBlockBinding( uniformsGroup, program ) {
  13433. const mapping = uboProgramMap.get( program );
  13434. const blockIndex = mapping.get( uniformsGroup );
  13435. if ( uboBindings.get( program ) !== blockIndex ) {
  13436. // bind shader specific block index to global block point
  13437. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13438. uboBindings.set( program, blockIndex );
  13439. }
  13440. }
  13441. //
  13442. function reset() {
  13443. // reset state
  13444. gl.disable( gl.BLEND );
  13445. gl.disable( gl.CULL_FACE );
  13446. gl.disable( gl.DEPTH_TEST );
  13447. gl.disable( gl.POLYGON_OFFSET_FILL );
  13448. gl.disable( gl.SCISSOR_TEST );
  13449. gl.disable( gl.STENCIL_TEST );
  13450. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13451. gl.blendEquation( gl.FUNC_ADD );
  13452. gl.blendFunc( gl.ONE, gl.ZERO );
  13453. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  13454. gl.colorMask( true, true, true, true );
  13455. gl.clearColor( 0, 0, 0, 0 );
  13456. gl.depthMask( true );
  13457. gl.depthFunc( gl.LESS );
  13458. gl.clearDepth( 1 );
  13459. gl.stencilMask( 0xffffffff );
  13460. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  13461. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  13462. gl.clearStencil( 0 );
  13463. gl.cullFace( gl.BACK );
  13464. gl.frontFace( gl.CCW );
  13465. gl.polygonOffset( 0, 0 );
  13466. gl.activeTexture( gl.TEXTURE0 );
  13467. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  13468. if ( isWebGL2 === true ) {
  13469. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  13470. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  13471. }
  13472. gl.useProgram( null );
  13473. gl.lineWidth( 1 );
  13474. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13475. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13476. // reset internals
  13477. enabledCapabilities = {};
  13478. currentTextureSlot = null;
  13479. currentBoundTextures = {};
  13480. currentBoundFramebuffers = {};
  13481. currentDrawbuffers = new WeakMap();
  13482. defaultDrawbuffers = [];
  13483. currentProgram = null;
  13484. currentBlendingEnabled = false;
  13485. currentBlending = null;
  13486. currentBlendEquation = null;
  13487. currentBlendSrc = null;
  13488. currentBlendDst = null;
  13489. currentBlendEquationAlpha = null;
  13490. currentBlendSrcAlpha = null;
  13491. currentBlendDstAlpha = null;
  13492. currentPremultipledAlpha = false;
  13493. currentFlipSided = null;
  13494. currentCullFace = null;
  13495. currentLineWidth = null;
  13496. currentPolygonOffsetFactor = null;
  13497. currentPolygonOffsetUnits = null;
  13498. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13499. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13500. colorBuffer.reset();
  13501. depthBuffer.reset();
  13502. stencilBuffer.reset();
  13503. }
  13504. return {
  13505. buffers: {
  13506. color: colorBuffer,
  13507. depth: depthBuffer,
  13508. stencil: stencilBuffer
  13509. },
  13510. enable: enable,
  13511. disable: disable,
  13512. bindFramebuffer: bindFramebuffer,
  13513. drawBuffers: drawBuffers,
  13514. useProgram: useProgram,
  13515. setBlending: setBlending,
  13516. setMaterial: setMaterial,
  13517. setFlipSided: setFlipSided,
  13518. setCullFace: setCullFace,
  13519. setLineWidth: setLineWidth,
  13520. setPolygonOffset: setPolygonOffset,
  13521. setScissorTest: setScissorTest,
  13522. activeTexture: activeTexture,
  13523. bindTexture: bindTexture,
  13524. unbindTexture: unbindTexture,
  13525. compressedTexImage2D: compressedTexImage2D,
  13526. compressedTexImage3D: compressedTexImage3D,
  13527. texImage2D: texImage2D,
  13528. texImage3D: texImage3D,
  13529. updateUBOMapping: updateUBOMapping,
  13530. uniformBlockBinding: uniformBlockBinding,
  13531. texStorage2D: texStorage2D,
  13532. texStorage3D: texStorage3D,
  13533. texSubImage2D: texSubImage2D,
  13534. texSubImage3D: texSubImage3D,
  13535. compressedTexSubImage2D: compressedTexSubImage2D,
  13536. compressedTexSubImage3D: compressedTexSubImage3D,
  13537. scissor: scissor,
  13538. viewport: viewport,
  13539. reset: reset
  13540. };
  13541. }
  13542. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13543. const isWebGL2 = capabilities.isWebGL2;
  13544. const maxTextures = capabilities.maxTextures;
  13545. const maxCubemapSize = capabilities.maxCubemapSize;
  13546. const maxTextureSize = capabilities.maxTextureSize;
  13547. const maxSamples = capabilities.maxSamples;
  13548. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13549. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13550. const _videoTextures = new WeakMap();
  13551. let _canvas;
  13552. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13553. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13554. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13555. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13556. let useOffscreenCanvas = false;
  13557. try {
  13558. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13559. // eslint-disable-next-line compat/compat
  13560. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13561. } catch ( err ) {
  13562. // Ignore any errors
  13563. }
  13564. function createCanvas( width, height ) {
  13565. // Use OffscreenCanvas when available. Specially needed in web workers
  13566. return useOffscreenCanvas ?
  13567. // eslint-disable-next-line compat/compat
  13568. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13569. }
  13570. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13571. let scale = 1;
  13572. // handle case if texture exceeds max size
  13573. if ( image.width > maxSize || image.height > maxSize ) {
  13574. scale = maxSize / Math.max( image.width, image.height );
  13575. }
  13576. // only perform resize if necessary
  13577. if ( scale < 1 || needsPowerOfTwo === true ) {
  13578. // only perform resize for certain image types
  13579. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13580. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13581. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13582. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13583. const width = floor( scale * image.width );
  13584. const height = floor( scale * image.height );
  13585. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13586. // cube textures can't reuse the same canvas
  13587. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13588. canvas.width = width;
  13589. canvas.height = height;
  13590. const context = canvas.getContext( '2d' );
  13591. context.drawImage( image, 0, 0, width, height );
  13592. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13593. return canvas;
  13594. } else {
  13595. if ( 'data' in image ) {
  13596. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13597. }
  13598. return image;
  13599. }
  13600. }
  13601. return image;
  13602. }
  13603. function isPowerOfTwo$1( image ) {
  13604. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13605. }
  13606. function textureNeedsPowerOfTwo( texture ) {
  13607. if ( isWebGL2 ) return false;
  13608. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13609. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13610. }
  13611. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13612. return texture.generateMipmaps && supportsMips &&
  13613. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13614. }
  13615. function generateMipmap( target ) {
  13616. _gl.generateMipmap( target );
  13617. }
  13618. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13619. if ( isWebGL2 === false ) return glFormat;
  13620. if ( internalFormatName !== null ) {
  13621. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13622. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13623. }
  13624. let internalFormat = glFormat;
  13625. if ( glFormat === _gl.RED ) {
  13626. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  13627. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  13628. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  13629. }
  13630. if ( glFormat === _gl.RG ) {
  13631. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  13632. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  13633. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  13634. }
  13635. if ( glFormat === _gl.RGBA ) {
  13636. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  13637. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  13638. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13639. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  13640. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  13641. }
  13642. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  13643. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  13644. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  13645. extensions.get( 'EXT_color_buffer_float' );
  13646. }
  13647. return internalFormat;
  13648. }
  13649. function getMipLevels( texture, image, supportsMips ) {
  13650. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13651. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13652. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13653. // user-defined mipmaps
  13654. return texture.mipmaps.length;
  13655. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13656. return image.mipmaps.length;
  13657. } else {
  13658. // texture without mipmaps (only base level)
  13659. return 1;
  13660. }
  13661. }
  13662. // Fallback filters for non-power-of-2 textures
  13663. function filterFallback( f ) {
  13664. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13665. return _gl.NEAREST;
  13666. }
  13667. return _gl.LINEAR;
  13668. }
  13669. //
  13670. function onTextureDispose( event ) {
  13671. const texture = event.target;
  13672. texture.removeEventListener( 'dispose', onTextureDispose );
  13673. deallocateTexture( texture );
  13674. if ( texture.isVideoTexture ) {
  13675. _videoTextures.delete( texture );
  13676. }
  13677. }
  13678. function onRenderTargetDispose( event ) {
  13679. const renderTarget = event.target;
  13680. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13681. deallocateRenderTarget( renderTarget );
  13682. }
  13683. //
  13684. function deallocateTexture( texture ) {
  13685. const textureProperties = properties.get( texture );
  13686. if ( textureProperties.__webglInit === undefined ) return;
  13687. // check if it's necessary to remove the WebGLTexture object
  13688. const source = texture.source;
  13689. const webglTextures = _sources.get( source );
  13690. if ( webglTextures ) {
  13691. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13692. webglTexture.usedTimes --;
  13693. // the WebGLTexture object is not used anymore, remove it
  13694. if ( webglTexture.usedTimes === 0 ) {
  13695. deleteTexture( texture );
  13696. }
  13697. // remove the weak map entry if no WebGLTexture uses the source anymore
  13698. if ( Object.keys( webglTextures ).length === 0 ) {
  13699. _sources.delete( source );
  13700. }
  13701. }
  13702. properties.remove( texture );
  13703. }
  13704. function deleteTexture( texture ) {
  13705. const textureProperties = properties.get( texture );
  13706. _gl.deleteTexture( textureProperties.__webglTexture );
  13707. const source = texture.source;
  13708. const webglTextures = _sources.get( source );
  13709. delete webglTextures[ textureProperties.__cacheKey ];
  13710. info.memory.textures --;
  13711. }
  13712. function deallocateRenderTarget( renderTarget ) {
  13713. const texture = renderTarget.texture;
  13714. const renderTargetProperties = properties.get( renderTarget );
  13715. const textureProperties = properties.get( texture );
  13716. if ( textureProperties.__webglTexture !== undefined ) {
  13717. _gl.deleteTexture( textureProperties.__webglTexture );
  13718. info.memory.textures --;
  13719. }
  13720. if ( renderTarget.depthTexture ) {
  13721. renderTarget.depthTexture.dispose();
  13722. }
  13723. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13724. for ( let i = 0; i < 6; i ++ ) {
  13725. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13726. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13727. }
  13728. } else {
  13729. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13730. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13731. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13732. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13733. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13734. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13735. }
  13736. }
  13737. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13738. }
  13739. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13740. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13741. const attachmentProperties = properties.get( texture[ i ] );
  13742. if ( attachmentProperties.__webglTexture ) {
  13743. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13744. info.memory.textures --;
  13745. }
  13746. properties.remove( texture[ i ] );
  13747. }
  13748. }
  13749. properties.remove( texture );
  13750. properties.remove( renderTarget );
  13751. }
  13752. //
  13753. let textureUnits = 0;
  13754. function resetTextureUnits() {
  13755. textureUnits = 0;
  13756. }
  13757. function allocateTextureUnit() {
  13758. const textureUnit = textureUnits;
  13759. if ( textureUnit >= maxTextures ) {
  13760. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13761. }
  13762. textureUnits += 1;
  13763. return textureUnit;
  13764. }
  13765. function getTextureCacheKey( texture ) {
  13766. const array = [];
  13767. array.push( texture.wrapS );
  13768. array.push( texture.wrapT );
  13769. array.push( texture.wrapR || 0 );
  13770. array.push( texture.magFilter );
  13771. array.push( texture.minFilter );
  13772. array.push( texture.anisotropy );
  13773. array.push( texture.internalFormat );
  13774. array.push( texture.format );
  13775. array.push( texture.type );
  13776. array.push( texture.generateMipmaps );
  13777. array.push( texture.premultiplyAlpha );
  13778. array.push( texture.flipY );
  13779. array.push( texture.unpackAlignment );
  13780. array.push( texture.encoding );
  13781. return array.join();
  13782. }
  13783. //
  13784. function setTexture2D( texture, slot ) {
  13785. const textureProperties = properties.get( texture );
  13786. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13787. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13788. const image = texture.image;
  13789. if ( image === null ) {
  13790. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13791. } else if ( image.complete === false ) {
  13792. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13793. } else {
  13794. uploadTexture( textureProperties, texture, slot );
  13795. return;
  13796. }
  13797. }
  13798. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13799. }
  13800. function setTexture2DArray( texture, slot ) {
  13801. const textureProperties = properties.get( texture );
  13802. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13803. uploadTexture( textureProperties, texture, slot );
  13804. return;
  13805. }
  13806. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13807. }
  13808. function setTexture3D( texture, slot ) {
  13809. const textureProperties = properties.get( texture );
  13810. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13811. uploadTexture( textureProperties, texture, slot );
  13812. return;
  13813. }
  13814. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13815. }
  13816. function setTextureCube( texture, slot ) {
  13817. const textureProperties = properties.get( texture );
  13818. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13819. uploadCubeTexture( textureProperties, texture, slot );
  13820. return;
  13821. }
  13822. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13823. }
  13824. const wrappingToGL = {
  13825. [ RepeatWrapping ]: _gl.REPEAT,
  13826. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  13827. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  13828. };
  13829. const filterToGL = {
  13830. [ NearestFilter ]: _gl.NEAREST,
  13831. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  13832. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  13833. [ LinearFilter ]: _gl.LINEAR,
  13834. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  13835. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  13836. };
  13837. function setTextureParameters( textureType, texture, supportsMips ) {
  13838. if ( supportsMips ) {
  13839. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  13840. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  13841. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  13842. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  13843. }
  13844. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  13845. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  13846. } else {
  13847. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13848. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13849. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  13850. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  13851. }
  13852. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13853. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13854. }
  13855. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13856. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13857. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13858. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13859. }
  13860. }
  13861. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13862. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13863. if ( texture.magFilter === NearestFilter ) return;
  13864. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  13865. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13866. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13867. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13868. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13869. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13870. }
  13871. }
  13872. }
  13873. function initTexture( textureProperties, texture ) {
  13874. let forceUpload = false;
  13875. if ( textureProperties.__webglInit === undefined ) {
  13876. textureProperties.__webglInit = true;
  13877. texture.addEventListener( 'dispose', onTextureDispose );
  13878. }
  13879. // create Source <-> WebGLTextures mapping if necessary
  13880. const source = texture.source;
  13881. let webglTextures = _sources.get( source );
  13882. if ( webglTextures === undefined ) {
  13883. webglTextures = {};
  13884. _sources.set( source, webglTextures );
  13885. }
  13886. // check if there is already a WebGLTexture object for the given texture parameters
  13887. const textureCacheKey = getTextureCacheKey( texture );
  13888. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13889. // if not, create a new instance of WebGLTexture
  13890. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13891. // create new entry
  13892. webglTextures[ textureCacheKey ] = {
  13893. texture: _gl.createTexture(),
  13894. usedTimes: 0
  13895. };
  13896. info.memory.textures ++;
  13897. // when a new instance of WebGLTexture was created, a texture upload is required
  13898. // even if the image contents are identical
  13899. forceUpload = true;
  13900. }
  13901. webglTextures[ textureCacheKey ].usedTimes ++;
  13902. // every time the texture cache key changes, it's necessary to check if an instance of
  13903. // WebGLTexture can be deleted in order to avoid a memory leak.
  13904. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13905. if ( webglTexture !== undefined ) {
  13906. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13907. if ( webglTexture.usedTimes === 0 ) {
  13908. deleteTexture( texture );
  13909. }
  13910. }
  13911. // store references to cache key and WebGLTexture object
  13912. textureProperties.__cacheKey = textureCacheKey;
  13913. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13914. }
  13915. return forceUpload;
  13916. }
  13917. function uploadTexture( textureProperties, texture, slot ) {
  13918. let textureType = _gl.TEXTURE_2D;
  13919. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  13920. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  13921. const forceUpload = initTexture( textureProperties, texture );
  13922. const source = texture.source;
  13923. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13924. const sourceProperties = properties.get( source );
  13925. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  13926. state.activeTexture( _gl.TEXTURE0 + slot );
  13927. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13928. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13929. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13930. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  13931. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13932. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13933. image = verifyColorSpace( texture, image );
  13934. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13935. glFormat = utils.convert( texture.format, texture.encoding );
  13936. let glType = utils.convert( texture.type ),
  13937. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13938. setTextureParameters( textureType, texture, supportsMips );
  13939. let mipmap;
  13940. const mipmaps = texture.mipmaps;
  13941. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13942. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  13943. const levels = getMipLevels( texture, image, supportsMips );
  13944. if ( texture.isDepthTexture ) {
  13945. // populate depth texture with dummy data
  13946. glInternalFormat = _gl.DEPTH_COMPONENT;
  13947. if ( isWebGL2 ) {
  13948. if ( texture.type === FloatType ) {
  13949. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13950. } else if ( texture.type === UnsignedIntType ) {
  13951. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13952. } else if ( texture.type === UnsignedInt248Type ) {
  13953. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13954. } else {
  13955. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13956. }
  13957. } else {
  13958. if ( texture.type === FloatType ) {
  13959. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13960. }
  13961. }
  13962. // validation checks for WebGL 1
  13963. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  13964. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13965. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13966. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13967. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13968. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13969. texture.type = UnsignedIntType;
  13970. glType = utils.convert( texture.type );
  13971. }
  13972. }
  13973. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  13974. // Depth stencil textures need the DEPTH_STENCIL internal format
  13975. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13976. glInternalFormat = _gl.DEPTH_STENCIL;
  13977. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13978. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13979. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13980. if ( texture.type !== UnsignedInt248Type ) {
  13981. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13982. texture.type = UnsignedInt248Type;
  13983. glType = utils.convert( texture.type );
  13984. }
  13985. }
  13986. //
  13987. if ( allocateMemory ) {
  13988. if ( useTexStorage ) {
  13989. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  13990. } else {
  13991. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13992. }
  13993. }
  13994. } else if ( texture.isDataTexture ) {
  13995. // use manually created mipmaps if available
  13996. // if there are no manual mipmaps
  13997. // set 0 level mipmap and then use GL to generate other mipmap levels
  13998. if ( mipmaps.length > 0 && supportsMips ) {
  13999. if ( useTexStorage && allocateMemory ) {
  14000. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14001. }
  14002. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14003. mipmap = mipmaps[ i ];
  14004. if ( useTexStorage ) {
  14005. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14006. } else {
  14007. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14008. }
  14009. }
  14010. texture.generateMipmaps = false;
  14011. } else {
  14012. if ( useTexStorage ) {
  14013. if ( allocateMemory ) {
  14014. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14015. }
  14016. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14017. } else {
  14018. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14019. }
  14020. }
  14021. } else if ( texture.isCompressedTexture ) {
  14022. if ( texture.isCompressedArrayTexture ) {
  14023. if ( useTexStorage && allocateMemory ) {
  14024. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14025. }
  14026. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14027. mipmap = mipmaps[ i ];
  14028. if ( texture.format !== RGBAFormat ) {
  14029. if ( glFormat !== null ) {
  14030. if ( useTexStorage ) {
  14031. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14032. } else {
  14033. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14034. }
  14035. } else {
  14036. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14037. }
  14038. } else {
  14039. if ( useTexStorage ) {
  14040. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14041. } else {
  14042. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14043. }
  14044. }
  14045. }
  14046. } else {
  14047. if ( useTexStorage && allocateMemory ) {
  14048. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14049. }
  14050. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14051. mipmap = mipmaps[ i ];
  14052. if ( texture.format !== RGBAFormat ) {
  14053. if ( glFormat !== null ) {
  14054. if ( useTexStorage ) {
  14055. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14056. } else {
  14057. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14058. }
  14059. } else {
  14060. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14061. }
  14062. } else {
  14063. if ( useTexStorage ) {
  14064. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14065. } else {
  14066. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14067. }
  14068. }
  14069. }
  14070. }
  14071. } else if ( texture.isDataArrayTexture ) {
  14072. if ( useTexStorage ) {
  14073. if ( allocateMemory ) {
  14074. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14075. }
  14076. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14077. } else {
  14078. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14079. }
  14080. } else if ( texture.isData3DTexture ) {
  14081. if ( useTexStorage ) {
  14082. if ( allocateMemory ) {
  14083. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14084. }
  14085. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14086. } else {
  14087. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14088. }
  14089. } else if ( texture.isFramebufferTexture ) {
  14090. if ( allocateMemory ) {
  14091. if ( useTexStorage ) {
  14092. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14093. } else {
  14094. let width = image.width, height = image.height;
  14095. for ( let i = 0; i < levels; i ++ ) {
  14096. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14097. width >>= 1;
  14098. height >>= 1;
  14099. }
  14100. }
  14101. }
  14102. } else {
  14103. // regular Texture (image, video, canvas)
  14104. // use manually created mipmaps if available
  14105. // if there are no manual mipmaps
  14106. // set 0 level mipmap and then use GL to generate other mipmap levels
  14107. if ( mipmaps.length > 0 && supportsMips ) {
  14108. if ( useTexStorage && allocateMemory ) {
  14109. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14110. }
  14111. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14112. mipmap = mipmaps[ i ];
  14113. if ( useTexStorage ) {
  14114. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14115. } else {
  14116. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14117. }
  14118. }
  14119. texture.generateMipmaps = false;
  14120. } else {
  14121. if ( useTexStorage ) {
  14122. if ( allocateMemory ) {
  14123. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14124. }
  14125. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14126. } else {
  14127. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14128. }
  14129. }
  14130. }
  14131. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14132. generateMipmap( textureType );
  14133. }
  14134. sourceProperties.__version = source.version;
  14135. if ( texture.onUpdate ) texture.onUpdate( texture );
  14136. }
  14137. textureProperties.__version = texture.version;
  14138. }
  14139. function uploadCubeTexture( textureProperties, texture, slot ) {
  14140. if ( texture.image.length !== 6 ) return;
  14141. const forceUpload = initTexture( textureProperties, texture );
  14142. const source = texture.source;
  14143. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14144. const sourceProperties = properties.get( source );
  14145. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14146. state.activeTexture( _gl.TEXTURE0 + slot );
  14147. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14148. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14149. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14150. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14151. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14152. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14153. const cubeImage = [];
  14154. for ( let i = 0; i < 6; i ++ ) {
  14155. if ( ! isCompressed && ! isDataTexture ) {
  14156. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14157. } else {
  14158. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14159. }
  14160. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14161. }
  14162. const image = cubeImage[ 0 ],
  14163. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14164. glFormat = utils.convert( texture.format, texture.encoding ),
  14165. glType = utils.convert( texture.type ),
  14166. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14167. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14168. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14169. let levels = getMipLevels( texture, image, supportsMips );
  14170. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14171. let mipmaps;
  14172. if ( isCompressed ) {
  14173. if ( useTexStorage && allocateMemory ) {
  14174. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14175. }
  14176. for ( let i = 0; i < 6; i ++ ) {
  14177. mipmaps = cubeImage[ i ].mipmaps;
  14178. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14179. const mipmap = mipmaps[ j ];
  14180. if ( texture.format !== RGBAFormat ) {
  14181. if ( glFormat !== null ) {
  14182. if ( useTexStorage ) {
  14183. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14184. } else {
  14185. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14186. }
  14187. } else {
  14188. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14189. }
  14190. } else {
  14191. if ( useTexStorage ) {
  14192. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14193. } else {
  14194. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14195. }
  14196. }
  14197. }
  14198. }
  14199. } else {
  14200. mipmaps = texture.mipmaps;
  14201. if ( useTexStorage && allocateMemory ) {
  14202. // TODO: Uniformly handle mipmap definitions
  14203. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14204. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14205. if ( mipmaps.length > 0 ) levels ++;
  14206. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14207. }
  14208. for ( let i = 0; i < 6; i ++ ) {
  14209. if ( isDataTexture ) {
  14210. if ( useTexStorage ) {
  14211. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14212. } else {
  14213. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14214. }
  14215. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14216. const mipmap = mipmaps[ j ];
  14217. const mipmapImage = mipmap.image[ i ].image;
  14218. if ( useTexStorage ) {
  14219. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14220. } else {
  14221. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14222. }
  14223. }
  14224. } else {
  14225. if ( useTexStorage ) {
  14226. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14227. } else {
  14228. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14229. }
  14230. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14231. const mipmap = mipmaps[ j ];
  14232. if ( useTexStorage ) {
  14233. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14234. } else {
  14235. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14236. }
  14237. }
  14238. }
  14239. }
  14240. }
  14241. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14242. // We assume images for cube map have the same size.
  14243. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14244. }
  14245. sourceProperties.__version = source.version;
  14246. if ( texture.onUpdate ) texture.onUpdate( texture );
  14247. }
  14248. textureProperties.__version = texture.version;
  14249. }
  14250. // Render targets
  14251. // Setup storage for target texture and bind it to correct framebuffer
  14252. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14253. const glFormat = utils.convert( texture.format, texture.encoding );
  14254. const glType = utils.convert( texture.type );
  14255. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14256. const renderTargetProperties = properties.get( renderTarget );
  14257. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14258. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14259. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14260. } else {
  14261. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14262. }
  14263. }
  14264. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14265. if ( useMultisampledRTT( renderTarget ) ) {
  14266. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14267. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14268. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14269. }
  14270. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14271. }
  14272. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14273. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14274. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14275. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14276. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14277. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14278. const depthTexture = renderTarget.depthTexture;
  14279. if ( depthTexture && depthTexture.isDepthTexture ) {
  14280. if ( depthTexture.type === FloatType ) {
  14281. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14282. } else if ( depthTexture.type === UnsignedIntType ) {
  14283. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14284. }
  14285. }
  14286. const samples = getRenderTargetSamples( renderTarget );
  14287. if ( useMultisampledRTT( renderTarget ) ) {
  14288. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14289. } else {
  14290. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14291. }
  14292. } else {
  14293. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14294. }
  14295. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14296. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14297. const samples = getRenderTargetSamples( renderTarget );
  14298. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14299. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14300. } else if ( useMultisampledRTT( renderTarget ) ) {
  14301. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14302. } else {
  14303. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14304. }
  14305. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14306. } else {
  14307. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14308. for ( let i = 0; i < textures.length; i ++ ) {
  14309. const texture = textures[ i ];
  14310. const glFormat = utils.convert( texture.format, texture.encoding );
  14311. const glType = utils.convert( texture.type );
  14312. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14313. const samples = getRenderTargetSamples( renderTarget );
  14314. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14315. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14316. } else if ( useMultisampledRTT( renderTarget ) ) {
  14317. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14318. } else {
  14319. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14320. }
  14321. }
  14322. }
  14323. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14324. }
  14325. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14326. function setupDepthTexture( framebuffer, renderTarget ) {
  14327. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14328. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14329. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14330. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14331. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14332. }
  14333. // upload an empty depth texture with framebuffer size
  14334. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14335. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14336. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14337. renderTarget.depthTexture.image.width = renderTarget.width;
  14338. renderTarget.depthTexture.image.height = renderTarget.height;
  14339. renderTarget.depthTexture.needsUpdate = true;
  14340. }
  14341. setTexture2D( renderTarget.depthTexture, 0 );
  14342. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14343. const samples = getRenderTargetSamples( renderTarget );
  14344. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14345. if ( useMultisampledRTT( renderTarget ) ) {
  14346. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14347. } else {
  14348. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14349. }
  14350. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14351. if ( useMultisampledRTT( renderTarget ) ) {
  14352. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14353. } else {
  14354. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14355. }
  14356. } else {
  14357. throw new Error( 'Unknown depthTexture format' );
  14358. }
  14359. }
  14360. // Setup GL resources for a non-texture depth buffer
  14361. function setupDepthRenderbuffer( renderTarget ) {
  14362. const renderTargetProperties = properties.get( renderTarget );
  14363. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14364. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14365. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14366. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14367. } else {
  14368. if ( isCube ) {
  14369. renderTargetProperties.__webglDepthbuffer = [];
  14370. for ( let i = 0; i < 6; i ++ ) {
  14371. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14372. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14373. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14374. }
  14375. } else {
  14376. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14377. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14378. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14379. }
  14380. }
  14381. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14382. }
  14383. // rebind framebuffer with external textures
  14384. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14385. const renderTargetProperties = properties.get( renderTarget );
  14386. if ( colorTexture !== undefined ) {
  14387. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14388. }
  14389. if ( depthTexture !== undefined ) {
  14390. setupDepthRenderbuffer( renderTarget );
  14391. }
  14392. }
  14393. // Set up GL resources for the render target
  14394. function setupRenderTarget( renderTarget ) {
  14395. const texture = renderTarget.texture;
  14396. const renderTargetProperties = properties.get( renderTarget );
  14397. const textureProperties = properties.get( texture );
  14398. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14399. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14400. if ( textureProperties.__webglTexture === undefined ) {
  14401. textureProperties.__webglTexture = _gl.createTexture();
  14402. }
  14403. textureProperties.__version = texture.version;
  14404. info.memory.textures ++;
  14405. }
  14406. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14407. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14408. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14409. // Setup framebuffer
  14410. if ( isCube ) {
  14411. renderTargetProperties.__webglFramebuffer = [];
  14412. for ( let i = 0; i < 6; i ++ ) {
  14413. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14414. }
  14415. } else {
  14416. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14417. if ( isMultipleRenderTargets ) {
  14418. if ( capabilities.drawBuffers ) {
  14419. const textures = renderTarget.texture;
  14420. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14421. const attachmentProperties = properties.get( textures[ i ] );
  14422. if ( attachmentProperties.__webglTexture === undefined ) {
  14423. attachmentProperties.__webglTexture = _gl.createTexture();
  14424. info.memory.textures ++;
  14425. }
  14426. }
  14427. } else {
  14428. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14429. }
  14430. }
  14431. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14432. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14433. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14434. renderTargetProperties.__webglColorRenderbuffer = [];
  14435. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14436. for ( let i = 0; i < textures.length; i ++ ) {
  14437. const texture = textures[ i ];
  14438. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14439. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14440. const glFormat = utils.convert( texture.format, texture.encoding );
  14441. const glType = utils.convert( texture.type );
  14442. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14443. const samples = getRenderTargetSamples( renderTarget );
  14444. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14445. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14446. }
  14447. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14448. if ( renderTarget.depthBuffer ) {
  14449. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14450. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14451. }
  14452. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14453. }
  14454. }
  14455. // Setup color buffer
  14456. if ( isCube ) {
  14457. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  14458. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14459. for ( let i = 0; i < 6; i ++ ) {
  14460. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14461. }
  14462. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14463. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14464. }
  14465. state.unbindTexture();
  14466. } else if ( isMultipleRenderTargets ) {
  14467. const textures = renderTarget.texture;
  14468. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14469. const attachment = textures[ i ];
  14470. const attachmentProperties = properties.get( attachment );
  14471. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  14472. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  14473. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  14474. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14475. generateMipmap( _gl.TEXTURE_2D );
  14476. }
  14477. }
  14478. state.unbindTexture();
  14479. } else {
  14480. let glTextureType = _gl.TEXTURE_2D;
  14481. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14482. if ( isWebGL2 ) {
  14483. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14484. } else {
  14485. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14486. }
  14487. }
  14488. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14489. setTextureParameters( glTextureType, texture, supportsMips );
  14490. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  14491. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14492. generateMipmap( glTextureType );
  14493. }
  14494. state.unbindTexture();
  14495. }
  14496. // Setup depth and stencil buffers
  14497. if ( renderTarget.depthBuffer ) {
  14498. setupDepthRenderbuffer( renderTarget );
  14499. }
  14500. }
  14501. function updateRenderTargetMipmap( renderTarget ) {
  14502. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14503. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14504. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14505. const texture = textures[ i ];
  14506. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14507. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14508. const webglTexture = properties.get( texture ).__webglTexture;
  14509. state.bindTexture( target, webglTexture );
  14510. generateMipmap( target );
  14511. state.unbindTexture();
  14512. }
  14513. }
  14514. }
  14515. function updateMultisampleRenderTarget( renderTarget ) {
  14516. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14517. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14518. const width = renderTarget.width;
  14519. const height = renderTarget.height;
  14520. let mask = _gl.COLOR_BUFFER_BIT;
  14521. const invalidationArray = [];
  14522. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14523. const renderTargetProperties = properties.get( renderTarget );
  14524. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14525. // If MRT we need to remove FBO attachments
  14526. if ( isMultipleRenderTargets ) {
  14527. for ( let i = 0; i < textures.length; i ++ ) {
  14528. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14529. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  14530. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14531. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  14532. }
  14533. }
  14534. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14535. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14536. for ( let i = 0; i < textures.length; i ++ ) {
  14537. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  14538. if ( renderTarget.depthBuffer ) {
  14539. invalidationArray.push( depthStyle );
  14540. }
  14541. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14542. if ( ignoreDepthValues === false ) {
  14543. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  14544. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  14545. }
  14546. if ( isMultipleRenderTargets ) {
  14547. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14548. }
  14549. if ( ignoreDepthValues === true ) {
  14550. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  14551. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  14552. }
  14553. if ( isMultipleRenderTargets ) {
  14554. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14555. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  14556. }
  14557. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  14558. if ( supportsInvalidateFramebuffer ) {
  14559. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  14560. }
  14561. }
  14562. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  14563. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  14564. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14565. if ( isMultipleRenderTargets ) {
  14566. for ( let i = 0; i < textures.length; i ++ ) {
  14567. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14568. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14569. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14570. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14571. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  14572. }
  14573. }
  14574. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14575. }
  14576. }
  14577. function getRenderTargetSamples( renderTarget ) {
  14578. return Math.min( maxSamples, renderTarget.samples );
  14579. }
  14580. function useMultisampledRTT( renderTarget ) {
  14581. const renderTargetProperties = properties.get( renderTarget );
  14582. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14583. }
  14584. function updateVideoTexture( texture ) {
  14585. const frame = info.render.frame;
  14586. // Check the last frame we updated the VideoTexture
  14587. if ( _videoTextures.get( texture ) !== frame ) {
  14588. _videoTextures.set( texture, frame );
  14589. texture.update();
  14590. }
  14591. }
  14592. function verifyColorSpace( texture, image ) {
  14593. const encoding = texture.encoding;
  14594. const format = texture.format;
  14595. const type = texture.type;
  14596. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14597. if ( encoding !== LinearEncoding ) {
  14598. // sRGB
  14599. if ( encoding === sRGBEncoding ) {
  14600. if ( isWebGL2 === false ) {
  14601. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14602. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14603. texture.format = _SRGBAFormat;
  14604. // it's not possible to generate mips in WebGL 1 with this extension
  14605. texture.minFilter = LinearFilter;
  14606. texture.generateMipmaps = false;
  14607. } else {
  14608. // slow fallback (CPU decode)
  14609. image = ImageUtils.sRGBToLinear( image );
  14610. }
  14611. } else {
  14612. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14613. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14614. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14615. }
  14616. }
  14617. } else {
  14618. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14619. }
  14620. }
  14621. return image;
  14622. }
  14623. //
  14624. this.allocateTextureUnit = allocateTextureUnit;
  14625. this.resetTextureUnits = resetTextureUnits;
  14626. this.setTexture2D = setTexture2D;
  14627. this.setTexture2DArray = setTexture2DArray;
  14628. this.setTexture3D = setTexture3D;
  14629. this.setTextureCube = setTextureCube;
  14630. this.rebindTextures = rebindTextures;
  14631. this.setupRenderTarget = setupRenderTarget;
  14632. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14633. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14634. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14635. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14636. this.useMultisampledRTT = useMultisampledRTT;
  14637. }
  14638. function WebGLUtils( gl, extensions, capabilities ) {
  14639. const isWebGL2 = capabilities.isWebGL2;
  14640. function convert( p, encoding = null ) {
  14641. let extension;
  14642. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  14643. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  14644. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  14645. if ( p === ByteType ) return gl.BYTE;
  14646. if ( p === ShortType ) return gl.SHORT;
  14647. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  14648. if ( p === IntType ) return gl.INT;
  14649. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  14650. if ( p === FloatType ) return gl.FLOAT;
  14651. if ( p === HalfFloatType ) {
  14652. if ( isWebGL2 ) return gl.HALF_FLOAT;
  14653. extension = extensions.get( 'OES_texture_half_float' );
  14654. if ( extension !== null ) {
  14655. return extension.HALF_FLOAT_OES;
  14656. } else {
  14657. return null;
  14658. }
  14659. }
  14660. if ( p === AlphaFormat ) return gl.ALPHA;
  14661. if ( p === RGBAFormat ) return gl.RGBA;
  14662. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  14663. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  14664. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  14665. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  14666. // WebGL 1 sRGB fallback
  14667. if ( p === _SRGBAFormat ) {
  14668. extension = extensions.get( 'EXT_sRGB' );
  14669. if ( extension !== null ) {
  14670. return extension.SRGB_ALPHA_EXT;
  14671. } else {
  14672. return null;
  14673. }
  14674. }
  14675. // WebGL2 formats.
  14676. if ( p === RedFormat ) return gl.RED;
  14677. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  14678. if ( p === RGFormat ) return gl.RG;
  14679. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  14680. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  14681. // S3TC
  14682. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14683. if ( encoding === sRGBEncoding ) {
  14684. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14685. if ( extension !== null ) {
  14686. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14687. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14688. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14689. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14690. } else {
  14691. return null;
  14692. }
  14693. } else {
  14694. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14695. if ( extension !== null ) {
  14696. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14697. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14698. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14699. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14700. } else {
  14701. return null;
  14702. }
  14703. }
  14704. }
  14705. // PVRTC
  14706. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14707. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14708. if ( extension !== null ) {
  14709. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14710. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14711. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14712. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14713. } else {
  14714. return null;
  14715. }
  14716. }
  14717. // ETC1
  14718. if ( p === RGB_ETC1_Format ) {
  14719. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14720. if ( extension !== null ) {
  14721. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14722. } else {
  14723. return null;
  14724. }
  14725. }
  14726. // ETC2
  14727. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14728. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14729. if ( extension !== null ) {
  14730. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14731. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14732. } else {
  14733. return null;
  14734. }
  14735. }
  14736. // ASTC
  14737. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14738. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14739. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14740. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14741. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14742. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14743. if ( extension !== null ) {
  14744. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14745. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14746. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14747. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14748. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14749. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14750. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14751. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14752. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14753. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14754. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14755. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14756. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14757. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14758. } else {
  14759. return null;
  14760. }
  14761. }
  14762. // BPTC
  14763. if ( p === RGBA_BPTC_Format ) {
  14764. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14765. if ( extension !== null ) {
  14766. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14767. } else {
  14768. return null;
  14769. }
  14770. }
  14771. // RGTC
  14772. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  14773. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  14774. if ( extension !== null ) {
  14775. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  14776. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  14777. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  14778. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  14779. } else {
  14780. return null;
  14781. }
  14782. }
  14783. //
  14784. if ( p === UnsignedInt248Type ) {
  14785. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  14786. extension = extensions.get( 'WEBGL_depth_texture' );
  14787. if ( extension !== null ) {
  14788. return extension.UNSIGNED_INT_24_8_WEBGL;
  14789. } else {
  14790. return null;
  14791. }
  14792. }
  14793. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14794. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14795. }
  14796. return { convert: convert };
  14797. }
  14798. class ArrayCamera extends PerspectiveCamera {
  14799. constructor( array = [] ) {
  14800. super();
  14801. this.isArrayCamera = true;
  14802. this.cameras = array;
  14803. }
  14804. }
  14805. class Group extends Object3D {
  14806. constructor() {
  14807. super();
  14808. this.isGroup = true;
  14809. this.type = 'Group';
  14810. }
  14811. }
  14812. const _moveEvent = { type: 'move' };
  14813. class WebXRController {
  14814. constructor() {
  14815. this._targetRay = null;
  14816. this._grip = null;
  14817. this._hand = null;
  14818. }
  14819. getHandSpace() {
  14820. if ( this._hand === null ) {
  14821. this._hand = new Group();
  14822. this._hand.matrixAutoUpdate = false;
  14823. this._hand.visible = false;
  14824. this._hand.joints = {};
  14825. this._hand.inputState = { pinching: false };
  14826. }
  14827. return this._hand;
  14828. }
  14829. getTargetRaySpace() {
  14830. if ( this._targetRay === null ) {
  14831. this._targetRay = new Group();
  14832. this._targetRay.matrixAutoUpdate = false;
  14833. this._targetRay.visible = false;
  14834. this._targetRay.hasLinearVelocity = false;
  14835. this._targetRay.linearVelocity = new Vector3();
  14836. this._targetRay.hasAngularVelocity = false;
  14837. this._targetRay.angularVelocity = new Vector3();
  14838. }
  14839. return this._targetRay;
  14840. }
  14841. getGripSpace() {
  14842. if ( this._grip === null ) {
  14843. this._grip = new Group();
  14844. this._grip.matrixAutoUpdate = false;
  14845. this._grip.visible = false;
  14846. this._grip.hasLinearVelocity = false;
  14847. this._grip.linearVelocity = new Vector3();
  14848. this._grip.hasAngularVelocity = false;
  14849. this._grip.angularVelocity = new Vector3();
  14850. }
  14851. return this._grip;
  14852. }
  14853. dispatchEvent( event ) {
  14854. if ( this._targetRay !== null ) {
  14855. this._targetRay.dispatchEvent( event );
  14856. }
  14857. if ( this._grip !== null ) {
  14858. this._grip.dispatchEvent( event );
  14859. }
  14860. if ( this._hand !== null ) {
  14861. this._hand.dispatchEvent( event );
  14862. }
  14863. return this;
  14864. }
  14865. connect( inputSource ) {
  14866. if ( inputSource && inputSource.hand ) {
  14867. const hand = this._hand;
  14868. if ( hand ) {
  14869. for ( const inputjoint of inputSource.hand.values() ) {
  14870. // Initialize hand with joints when connected
  14871. this._getHandJoint( hand, inputjoint );
  14872. }
  14873. }
  14874. }
  14875. this.dispatchEvent( { type: 'connected', data: inputSource } );
  14876. return this;
  14877. }
  14878. disconnect( inputSource ) {
  14879. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14880. if ( this._targetRay !== null ) {
  14881. this._targetRay.visible = false;
  14882. }
  14883. if ( this._grip !== null ) {
  14884. this._grip.visible = false;
  14885. }
  14886. if ( this._hand !== null ) {
  14887. this._hand.visible = false;
  14888. }
  14889. return this;
  14890. }
  14891. update( inputSource, frame, referenceSpace ) {
  14892. let inputPose = null;
  14893. let gripPose = null;
  14894. let handPose = null;
  14895. const targetRay = this._targetRay;
  14896. const grip = this._grip;
  14897. const hand = this._hand;
  14898. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14899. if ( hand && inputSource.hand ) {
  14900. handPose = true;
  14901. for ( const inputjoint of inputSource.hand.values() ) {
  14902. // Update the joints groups with the XRJoint poses
  14903. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14904. // The transform of this joint will be updated with the joint pose on each frame
  14905. const joint = this._getHandJoint( hand, inputjoint );
  14906. if ( jointPose !== null ) {
  14907. joint.matrix.fromArray( jointPose.transform.matrix );
  14908. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14909. joint.jointRadius = jointPose.radius;
  14910. }
  14911. joint.visible = jointPose !== null;
  14912. }
  14913. // Custom events
  14914. // Check pinchz
  14915. const indexTip = hand.joints[ 'index-finger-tip' ];
  14916. const thumbTip = hand.joints[ 'thumb-tip' ];
  14917. const distance = indexTip.position.distanceTo( thumbTip.position );
  14918. const distanceToPinch = 0.02;
  14919. const threshold = 0.005;
  14920. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14921. hand.inputState.pinching = false;
  14922. this.dispatchEvent( {
  14923. type: 'pinchend',
  14924. handedness: inputSource.handedness,
  14925. target: this
  14926. } );
  14927. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14928. hand.inputState.pinching = true;
  14929. this.dispatchEvent( {
  14930. type: 'pinchstart',
  14931. handedness: inputSource.handedness,
  14932. target: this
  14933. } );
  14934. }
  14935. } else {
  14936. if ( grip !== null && inputSource.gripSpace ) {
  14937. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14938. if ( gripPose !== null ) {
  14939. grip.matrix.fromArray( gripPose.transform.matrix );
  14940. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14941. if ( gripPose.linearVelocity ) {
  14942. grip.hasLinearVelocity = true;
  14943. grip.linearVelocity.copy( gripPose.linearVelocity );
  14944. } else {
  14945. grip.hasLinearVelocity = false;
  14946. }
  14947. if ( gripPose.angularVelocity ) {
  14948. grip.hasAngularVelocity = true;
  14949. grip.angularVelocity.copy( gripPose.angularVelocity );
  14950. } else {
  14951. grip.hasAngularVelocity = false;
  14952. }
  14953. }
  14954. }
  14955. }
  14956. if ( targetRay !== null ) {
  14957. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14958. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14959. if ( inputPose === null && gripPose !== null ) {
  14960. inputPose = gripPose;
  14961. }
  14962. if ( inputPose !== null ) {
  14963. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14964. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14965. if ( inputPose.linearVelocity ) {
  14966. targetRay.hasLinearVelocity = true;
  14967. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14968. } else {
  14969. targetRay.hasLinearVelocity = false;
  14970. }
  14971. if ( inputPose.angularVelocity ) {
  14972. targetRay.hasAngularVelocity = true;
  14973. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14974. } else {
  14975. targetRay.hasAngularVelocity = false;
  14976. }
  14977. this.dispatchEvent( _moveEvent );
  14978. }
  14979. }
  14980. }
  14981. if ( targetRay !== null ) {
  14982. targetRay.visible = ( inputPose !== null );
  14983. }
  14984. if ( grip !== null ) {
  14985. grip.visible = ( gripPose !== null );
  14986. }
  14987. if ( hand !== null ) {
  14988. hand.visible = ( handPose !== null );
  14989. }
  14990. return this;
  14991. }
  14992. // private method
  14993. _getHandJoint( hand, inputjoint ) {
  14994. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14995. const joint = new Group();
  14996. joint.matrixAutoUpdate = false;
  14997. joint.visible = false;
  14998. hand.joints[ inputjoint.jointName ] = joint;
  14999. hand.add( joint );
  15000. }
  15001. return hand.joints[ inputjoint.jointName ];
  15002. }
  15003. }
  15004. class DepthTexture extends Texture {
  15005. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15006. format = format !== undefined ? format : DepthFormat;
  15007. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15008. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15009. }
  15010. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15011. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15012. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15013. this.isDepthTexture = true;
  15014. this.image = { width: width, height: height };
  15015. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15016. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15017. this.flipY = false;
  15018. this.generateMipmaps = false;
  15019. }
  15020. }
  15021. class WebXRManager extends EventDispatcher {
  15022. constructor( renderer, gl ) {
  15023. super();
  15024. const scope = this;
  15025. let session = null;
  15026. let framebufferScaleFactor = 1.0;
  15027. let referenceSpace = null;
  15028. let referenceSpaceType = 'local-floor';
  15029. // Set default foveation to maximum.
  15030. let foveation = 1.0;
  15031. let customReferenceSpace = null;
  15032. let pose = null;
  15033. let glBinding = null;
  15034. let glProjLayer = null;
  15035. let glBaseLayer = null;
  15036. let xrFrame = null;
  15037. const attributes = gl.getContextAttributes();
  15038. let initialRenderTarget = null;
  15039. let newRenderTarget = null;
  15040. const controllers = [];
  15041. const controllerInputSources = [];
  15042. const planes = new Set();
  15043. const planesLastChangedTimes = new Map();
  15044. //
  15045. const cameraL = new PerspectiveCamera();
  15046. cameraL.layers.enable( 1 );
  15047. cameraL.viewport = new Vector4();
  15048. const cameraR = new PerspectiveCamera();
  15049. cameraR.layers.enable( 2 );
  15050. cameraR.viewport = new Vector4();
  15051. const cameras = [ cameraL, cameraR ];
  15052. const cameraVR = new ArrayCamera();
  15053. cameraVR.layers.enable( 1 );
  15054. cameraVR.layers.enable( 2 );
  15055. let _currentDepthNear = null;
  15056. let _currentDepthFar = null;
  15057. //
  15058. this.cameraAutoUpdate = true;
  15059. this.enabled = false;
  15060. this.isPresenting = false;
  15061. this.getController = function ( index ) {
  15062. let controller = controllers[ index ];
  15063. if ( controller === undefined ) {
  15064. controller = new WebXRController();
  15065. controllers[ index ] = controller;
  15066. }
  15067. return controller.getTargetRaySpace();
  15068. };
  15069. this.getControllerGrip = function ( index ) {
  15070. let controller = controllers[ index ];
  15071. if ( controller === undefined ) {
  15072. controller = new WebXRController();
  15073. controllers[ index ] = controller;
  15074. }
  15075. return controller.getGripSpace();
  15076. };
  15077. this.getHand = function ( index ) {
  15078. let controller = controllers[ index ];
  15079. if ( controller === undefined ) {
  15080. controller = new WebXRController();
  15081. controllers[ index ] = controller;
  15082. }
  15083. return controller.getHandSpace();
  15084. };
  15085. //
  15086. function onSessionEvent( event ) {
  15087. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15088. if ( controllerIndex === - 1 ) {
  15089. return;
  15090. }
  15091. const controller = controllers[ controllerIndex ];
  15092. if ( controller !== undefined ) {
  15093. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15094. }
  15095. }
  15096. function onSessionEnd() {
  15097. session.removeEventListener( 'select', onSessionEvent );
  15098. session.removeEventListener( 'selectstart', onSessionEvent );
  15099. session.removeEventListener( 'selectend', onSessionEvent );
  15100. session.removeEventListener( 'squeeze', onSessionEvent );
  15101. session.removeEventListener( 'squeezestart', onSessionEvent );
  15102. session.removeEventListener( 'squeezeend', onSessionEvent );
  15103. session.removeEventListener( 'end', onSessionEnd );
  15104. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15105. for ( let i = 0; i < controllers.length; i ++ ) {
  15106. const inputSource = controllerInputSources[ i ];
  15107. if ( inputSource === null ) continue;
  15108. controllerInputSources[ i ] = null;
  15109. controllers[ i ].disconnect( inputSource );
  15110. }
  15111. _currentDepthNear = null;
  15112. _currentDepthFar = null;
  15113. // restore framebuffer/rendering state
  15114. renderer.setRenderTarget( initialRenderTarget );
  15115. glBaseLayer = null;
  15116. glProjLayer = null;
  15117. glBinding = null;
  15118. session = null;
  15119. newRenderTarget = null;
  15120. //
  15121. animation.stop();
  15122. scope.isPresenting = false;
  15123. scope.dispatchEvent( { type: 'sessionend' } );
  15124. }
  15125. this.setFramebufferScaleFactor = function ( value ) {
  15126. framebufferScaleFactor = value;
  15127. if ( scope.isPresenting === true ) {
  15128. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15129. }
  15130. };
  15131. this.setReferenceSpaceType = function ( value ) {
  15132. referenceSpaceType = value;
  15133. if ( scope.isPresenting === true ) {
  15134. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15135. }
  15136. };
  15137. this.getReferenceSpace = function () {
  15138. return customReferenceSpace || referenceSpace;
  15139. };
  15140. this.setReferenceSpace = function ( space ) {
  15141. customReferenceSpace = space;
  15142. };
  15143. this.getBaseLayer = function () {
  15144. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15145. };
  15146. this.getBinding = function () {
  15147. return glBinding;
  15148. };
  15149. this.getFrame = function () {
  15150. return xrFrame;
  15151. };
  15152. this.getSession = function () {
  15153. return session;
  15154. };
  15155. this.setSession = async function ( value ) {
  15156. session = value;
  15157. if ( session !== null ) {
  15158. initialRenderTarget = renderer.getRenderTarget();
  15159. session.addEventListener( 'select', onSessionEvent );
  15160. session.addEventListener( 'selectstart', onSessionEvent );
  15161. session.addEventListener( 'selectend', onSessionEvent );
  15162. session.addEventListener( 'squeeze', onSessionEvent );
  15163. session.addEventListener( 'squeezestart', onSessionEvent );
  15164. session.addEventListener( 'squeezeend', onSessionEvent );
  15165. session.addEventListener( 'end', onSessionEnd );
  15166. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15167. if ( attributes.xrCompatible !== true ) {
  15168. await gl.makeXRCompatible();
  15169. }
  15170. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15171. const layerInit = {
  15172. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15173. alpha: attributes.alpha,
  15174. depth: attributes.depth,
  15175. stencil: attributes.stencil,
  15176. framebufferScaleFactor: framebufferScaleFactor
  15177. };
  15178. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15179. session.updateRenderState( { baseLayer: glBaseLayer } );
  15180. newRenderTarget = new WebGLRenderTarget(
  15181. glBaseLayer.framebufferWidth,
  15182. glBaseLayer.framebufferHeight,
  15183. {
  15184. format: RGBAFormat,
  15185. type: UnsignedByteType,
  15186. encoding: renderer.outputEncoding,
  15187. stencilBuffer: attributes.stencil
  15188. }
  15189. );
  15190. } else {
  15191. let depthFormat = null;
  15192. let depthType = null;
  15193. let glDepthFormat = null;
  15194. if ( attributes.depth ) {
  15195. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15196. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15197. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15198. }
  15199. const projectionlayerInit = {
  15200. colorFormat: gl.RGBA8,
  15201. depthFormat: glDepthFormat,
  15202. scaleFactor: framebufferScaleFactor
  15203. };
  15204. glBinding = new XRWebGLBinding( session, gl );
  15205. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15206. session.updateRenderState( { layers: [ glProjLayer ] } );
  15207. newRenderTarget = new WebGLRenderTarget(
  15208. glProjLayer.textureWidth,
  15209. glProjLayer.textureHeight,
  15210. {
  15211. format: RGBAFormat,
  15212. type: UnsignedByteType,
  15213. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15214. stencilBuffer: attributes.stencil,
  15215. encoding: renderer.outputEncoding,
  15216. samples: attributes.antialias ? 4 : 0
  15217. } );
  15218. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15219. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15220. }
  15221. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15222. this.setFoveation( foveation );
  15223. customReferenceSpace = null;
  15224. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15225. animation.setContext( session );
  15226. animation.start();
  15227. scope.isPresenting = true;
  15228. scope.dispatchEvent( { type: 'sessionstart' } );
  15229. }
  15230. };
  15231. function onInputSourcesChange( event ) {
  15232. // Notify disconnected
  15233. for ( let i = 0; i < event.removed.length; i ++ ) {
  15234. const inputSource = event.removed[ i ];
  15235. const index = controllerInputSources.indexOf( inputSource );
  15236. if ( index >= 0 ) {
  15237. controllerInputSources[ index ] = null;
  15238. controllers[ index ].disconnect( inputSource );
  15239. }
  15240. }
  15241. // Notify connected
  15242. for ( let i = 0; i < event.added.length; i ++ ) {
  15243. const inputSource = event.added[ i ];
  15244. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15245. if ( controllerIndex === - 1 ) {
  15246. // Assign input source a controller that currently has no input source
  15247. for ( let i = 0; i < controllers.length; i ++ ) {
  15248. if ( i >= controllerInputSources.length ) {
  15249. controllerInputSources.push( inputSource );
  15250. controllerIndex = i;
  15251. break;
  15252. } else if ( controllerInputSources[ i ] === null ) {
  15253. controllerInputSources[ i ] = inputSource;
  15254. controllerIndex = i;
  15255. break;
  15256. }
  15257. }
  15258. // If all controllers do currently receive input we ignore new ones
  15259. if ( controllerIndex === - 1 ) break;
  15260. }
  15261. const controller = controllers[ controllerIndex ];
  15262. if ( controller ) {
  15263. controller.connect( inputSource );
  15264. }
  15265. }
  15266. }
  15267. //
  15268. const cameraLPos = new Vector3();
  15269. const cameraRPos = new Vector3();
  15270. /**
  15271. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15272. * the cameras' projection and world matrices have already been set.
  15273. * And that near and far planes are identical for both cameras.
  15274. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15275. */
  15276. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15277. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15278. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15279. const ipd = cameraLPos.distanceTo( cameraRPos );
  15280. const projL = cameraL.projectionMatrix.elements;
  15281. const projR = cameraR.projectionMatrix.elements;
  15282. // VR systems will have identical far and near planes, and
  15283. // most likely identical top and bottom frustum extents.
  15284. // Use the left camera for these values.
  15285. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15286. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15287. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15288. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15289. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15290. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15291. const left = near * leftFov;
  15292. const right = near * rightFov;
  15293. // Calculate the new camera's position offset from the
  15294. // left camera. xOffset should be roughly half `ipd`.
  15295. const zOffset = ipd / ( - leftFov + rightFov );
  15296. const xOffset = zOffset * - leftFov;
  15297. // TODO: Better way to apply this offset?
  15298. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15299. camera.translateX( xOffset );
  15300. camera.translateZ( zOffset );
  15301. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15302. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15303. // Find the union of the frustum values of the cameras and scale
  15304. // the values so that the near plane's position does not change in world space,
  15305. // although must now be relative to the new union camera.
  15306. const near2 = near + zOffset;
  15307. const far2 = far + zOffset;
  15308. const left2 = left - xOffset;
  15309. const right2 = right + ( ipd - xOffset );
  15310. const top2 = topFov * far / far2 * near2;
  15311. const bottom2 = bottomFov * far / far2 * near2;
  15312. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15313. }
  15314. function updateCamera( camera, parent ) {
  15315. if ( parent === null ) {
  15316. camera.matrixWorld.copy( camera.matrix );
  15317. } else {
  15318. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15319. }
  15320. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15321. }
  15322. this.updateCamera = function ( camera ) {
  15323. if ( session === null ) return;
  15324. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15325. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15326. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15327. // Note that the new renderState won't apply until the next frame. See #18320
  15328. session.updateRenderState( {
  15329. depthNear: cameraVR.near,
  15330. depthFar: cameraVR.far
  15331. } );
  15332. _currentDepthNear = cameraVR.near;
  15333. _currentDepthFar = cameraVR.far;
  15334. }
  15335. const parent = camera.parent;
  15336. const cameras = cameraVR.cameras;
  15337. updateCamera( cameraVR, parent );
  15338. for ( let i = 0; i < cameras.length; i ++ ) {
  15339. updateCamera( cameras[ i ], parent );
  15340. }
  15341. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15342. // update user camera and its children
  15343. camera.matrix.copy( cameraVR.matrix );
  15344. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15345. const children = camera.children;
  15346. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15347. children[ i ].updateMatrixWorld( true );
  15348. }
  15349. // update projection matrix for proper view frustum culling
  15350. if ( cameras.length === 2 ) {
  15351. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15352. } else {
  15353. // assume single camera setup (AR)
  15354. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15355. }
  15356. };
  15357. this.getCamera = function () {
  15358. return cameraVR;
  15359. };
  15360. this.getFoveation = function () {
  15361. if ( glProjLayer === null && glBaseLayer === null ) {
  15362. return undefined;
  15363. }
  15364. return foveation;
  15365. };
  15366. this.setFoveation = function ( value ) {
  15367. // 0 = no foveation = full resolution
  15368. // 1 = maximum foveation = the edges render at lower resolution
  15369. foveation = value;
  15370. if ( glProjLayer !== null ) {
  15371. glProjLayer.fixedFoveation = value;
  15372. }
  15373. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15374. glBaseLayer.fixedFoveation = value;
  15375. }
  15376. };
  15377. this.getPlanes = function () {
  15378. return planes;
  15379. };
  15380. // Animation Loop
  15381. let onAnimationFrameCallback = null;
  15382. function onAnimationFrame( time, frame ) {
  15383. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15384. xrFrame = frame;
  15385. if ( pose !== null ) {
  15386. const views = pose.views;
  15387. if ( glBaseLayer !== null ) {
  15388. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15389. renderer.setRenderTarget( newRenderTarget );
  15390. }
  15391. let cameraVRNeedsUpdate = false;
  15392. // check if it's necessary to rebuild cameraVR's camera list
  15393. if ( views.length !== cameraVR.cameras.length ) {
  15394. cameraVR.cameras.length = 0;
  15395. cameraVRNeedsUpdate = true;
  15396. }
  15397. for ( let i = 0; i < views.length; i ++ ) {
  15398. const view = views[ i ];
  15399. let viewport = null;
  15400. if ( glBaseLayer !== null ) {
  15401. viewport = glBaseLayer.getViewport( view );
  15402. } else {
  15403. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15404. viewport = glSubImage.viewport;
  15405. // For side-by-side projection, we only produce a single texture for both eyes.
  15406. if ( i === 0 ) {
  15407. renderer.setRenderTargetTextures(
  15408. newRenderTarget,
  15409. glSubImage.colorTexture,
  15410. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15411. renderer.setRenderTarget( newRenderTarget );
  15412. }
  15413. }
  15414. let camera = cameras[ i ];
  15415. if ( camera === undefined ) {
  15416. camera = new PerspectiveCamera();
  15417. camera.layers.enable( i );
  15418. camera.viewport = new Vector4();
  15419. cameras[ i ] = camera;
  15420. }
  15421. camera.matrix.fromArray( view.transform.matrix );
  15422. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15423. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15424. if ( i === 0 ) {
  15425. cameraVR.matrix.copy( camera.matrix );
  15426. }
  15427. if ( cameraVRNeedsUpdate === true ) {
  15428. cameraVR.cameras.push( camera );
  15429. }
  15430. }
  15431. }
  15432. //
  15433. for ( let i = 0; i < controllers.length; i ++ ) {
  15434. const inputSource = controllerInputSources[ i ];
  15435. const controller = controllers[ i ];
  15436. if ( inputSource !== null && controller !== undefined ) {
  15437. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15438. }
  15439. }
  15440. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15441. if ( frame.detectedPlanes ) {
  15442. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15443. let planesToRemove = null;
  15444. for ( const plane of planes ) {
  15445. if ( ! frame.detectedPlanes.has( plane ) ) {
  15446. if ( planesToRemove === null ) {
  15447. planesToRemove = [];
  15448. }
  15449. planesToRemove.push( plane );
  15450. }
  15451. }
  15452. if ( planesToRemove !== null ) {
  15453. for ( const plane of planesToRemove ) {
  15454. planes.delete( plane );
  15455. planesLastChangedTimes.delete( plane );
  15456. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15457. }
  15458. }
  15459. for ( const plane of frame.detectedPlanes ) {
  15460. if ( ! planes.has( plane ) ) {
  15461. planes.add( plane );
  15462. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15463. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15464. } else {
  15465. const lastKnownTime = planesLastChangedTimes.get( plane );
  15466. if ( plane.lastChangedTime > lastKnownTime ) {
  15467. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15468. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15469. }
  15470. }
  15471. }
  15472. }
  15473. xrFrame = null;
  15474. }
  15475. const animation = new WebGLAnimation();
  15476. animation.setAnimationLoop( onAnimationFrame );
  15477. this.setAnimationLoop = function ( callback ) {
  15478. onAnimationFrameCallback = callback;
  15479. };
  15480. this.dispose = function () {};
  15481. }
  15482. }
  15483. function WebGLMaterials( renderer, properties ) {
  15484. function refreshFogUniforms( uniforms, fog ) {
  15485. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15486. if ( fog.isFog ) {
  15487. uniforms.fogNear.value = fog.near;
  15488. uniforms.fogFar.value = fog.far;
  15489. } else if ( fog.isFogExp2 ) {
  15490. uniforms.fogDensity.value = fog.density;
  15491. }
  15492. }
  15493. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15494. if ( material.isMeshBasicMaterial ) {
  15495. refreshUniformsCommon( uniforms, material );
  15496. } else if ( material.isMeshLambertMaterial ) {
  15497. refreshUniformsCommon( uniforms, material );
  15498. } else if ( material.isMeshToonMaterial ) {
  15499. refreshUniformsCommon( uniforms, material );
  15500. refreshUniformsToon( uniforms, material );
  15501. } else if ( material.isMeshPhongMaterial ) {
  15502. refreshUniformsCommon( uniforms, material );
  15503. refreshUniformsPhong( uniforms, material );
  15504. } else if ( material.isMeshStandardMaterial ) {
  15505. refreshUniformsCommon( uniforms, material );
  15506. refreshUniformsStandard( uniforms, material );
  15507. if ( material.isMeshPhysicalMaterial ) {
  15508. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15509. }
  15510. } else if ( material.isMeshMatcapMaterial ) {
  15511. refreshUniformsCommon( uniforms, material );
  15512. refreshUniformsMatcap( uniforms, material );
  15513. } else if ( material.isMeshDepthMaterial ) {
  15514. refreshUniformsCommon( uniforms, material );
  15515. } else if ( material.isMeshDistanceMaterial ) {
  15516. refreshUniformsCommon( uniforms, material );
  15517. refreshUniformsDistance( uniforms, material );
  15518. } else if ( material.isMeshNormalMaterial ) {
  15519. refreshUniformsCommon( uniforms, material );
  15520. } else if ( material.isLineBasicMaterial ) {
  15521. refreshUniformsLine( uniforms, material );
  15522. if ( material.isLineDashedMaterial ) {
  15523. refreshUniformsDash( uniforms, material );
  15524. }
  15525. } else if ( material.isPointsMaterial ) {
  15526. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15527. } else if ( material.isSpriteMaterial ) {
  15528. refreshUniformsSprites( uniforms, material );
  15529. } else if ( material.isShadowMaterial ) {
  15530. uniforms.color.value.copy( material.color );
  15531. uniforms.opacity.value = material.opacity;
  15532. } else if ( material.isShaderMaterial ) {
  15533. material.uniformsNeedUpdate = false; // #15581
  15534. }
  15535. }
  15536. function refreshUniformsCommon( uniforms, material ) {
  15537. uniforms.opacity.value = material.opacity;
  15538. if ( material.color ) {
  15539. uniforms.diffuse.value.copy( material.color );
  15540. }
  15541. if ( material.emissive ) {
  15542. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15543. }
  15544. if ( material.map ) {
  15545. uniforms.map.value = material.map;
  15546. }
  15547. if ( material.alphaMap ) {
  15548. uniforms.alphaMap.value = material.alphaMap;
  15549. }
  15550. if ( material.bumpMap ) {
  15551. uniforms.bumpMap.value = material.bumpMap;
  15552. uniforms.bumpScale.value = material.bumpScale;
  15553. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15554. }
  15555. if ( material.displacementMap ) {
  15556. uniforms.displacementMap.value = material.displacementMap;
  15557. uniforms.displacementScale.value = material.displacementScale;
  15558. uniforms.displacementBias.value = material.displacementBias;
  15559. }
  15560. if ( material.emissiveMap ) {
  15561. uniforms.emissiveMap.value = material.emissiveMap;
  15562. }
  15563. if ( material.normalMap ) {
  15564. uniforms.normalMap.value = material.normalMap;
  15565. uniforms.normalScale.value.copy( material.normalScale );
  15566. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15567. }
  15568. if ( material.specularMap ) {
  15569. uniforms.specularMap.value = material.specularMap;
  15570. }
  15571. if ( material.alphaTest > 0 ) {
  15572. uniforms.alphaTest.value = material.alphaTest;
  15573. }
  15574. const envMap = properties.get( material ).envMap;
  15575. if ( envMap ) {
  15576. uniforms.envMap.value = envMap;
  15577. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15578. uniforms.reflectivity.value = material.reflectivity;
  15579. uniforms.ior.value = material.ior;
  15580. uniforms.refractionRatio.value = material.refractionRatio;
  15581. }
  15582. if ( material.lightMap ) {
  15583. uniforms.lightMap.value = material.lightMap;
  15584. // artist-friendly light intensity scaling factor
  15585. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15586. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15587. }
  15588. if ( material.aoMap ) {
  15589. uniforms.aoMap.value = material.aoMap;
  15590. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15591. }
  15592. // uv repeat and offset setting priorities
  15593. // 1. color map
  15594. // 2. specular map
  15595. // 3. displacementMap map
  15596. // 4. normal map
  15597. // 5. bump map
  15598. // 6. roughnessMap map
  15599. // 7. metalnessMap map
  15600. // 8. alphaMap map
  15601. // 9. emissiveMap map
  15602. // 10. clearcoat map
  15603. // 11. clearcoat normal map
  15604. // 12. clearcoat roughnessMap map
  15605. // 13. iridescence map
  15606. // 14. iridescence thickness map
  15607. // 15. specular intensity map
  15608. // 16. specular tint map
  15609. // 17. transmission map
  15610. // 18. thickness map
  15611. let uvScaleMap;
  15612. if ( material.map ) {
  15613. uvScaleMap = material.map;
  15614. } else if ( material.specularMap ) {
  15615. uvScaleMap = material.specularMap;
  15616. } else if ( material.displacementMap ) {
  15617. uvScaleMap = material.displacementMap;
  15618. } else if ( material.normalMap ) {
  15619. uvScaleMap = material.normalMap;
  15620. } else if ( material.bumpMap ) {
  15621. uvScaleMap = material.bumpMap;
  15622. } else if ( material.roughnessMap ) {
  15623. uvScaleMap = material.roughnessMap;
  15624. } else if ( material.metalnessMap ) {
  15625. uvScaleMap = material.metalnessMap;
  15626. } else if ( material.alphaMap ) {
  15627. uvScaleMap = material.alphaMap;
  15628. } else if ( material.emissiveMap ) {
  15629. uvScaleMap = material.emissiveMap;
  15630. } else if ( material.clearcoatMap ) {
  15631. uvScaleMap = material.clearcoatMap;
  15632. } else if ( material.clearcoatNormalMap ) {
  15633. uvScaleMap = material.clearcoatNormalMap;
  15634. } else if ( material.clearcoatRoughnessMap ) {
  15635. uvScaleMap = material.clearcoatRoughnessMap;
  15636. } else if ( material.iridescenceMap ) {
  15637. uvScaleMap = material.iridescenceMap;
  15638. } else if ( material.iridescenceThicknessMap ) {
  15639. uvScaleMap = material.iridescenceThicknessMap;
  15640. } else if ( material.specularIntensityMap ) {
  15641. uvScaleMap = material.specularIntensityMap;
  15642. } else if ( material.specularColorMap ) {
  15643. uvScaleMap = material.specularColorMap;
  15644. } else if ( material.transmissionMap ) {
  15645. uvScaleMap = material.transmissionMap;
  15646. } else if ( material.thicknessMap ) {
  15647. uvScaleMap = material.thicknessMap;
  15648. } else if ( material.sheenColorMap ) {
  15649. uvScaleMap = material.sheenColorMap;
  15650. } else if ( material.sheenRoughnessMap ) {
  15651. uvScaleMap = material.sheenRoughnessMap;
  15652. }
  15653. if ( uvScaleMap !== undefined ) {
  15654. // backwards compatibility
  15655. if ( uvScaleMap.isWebGLRenderTarget ) {
  15656. uvScaleMap = uvScaleMap.texture;
  15657. }
  15658. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15659. uvScaleMap.updateMatrix();
  15660. }
  15661. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15662. }
  15663. // uv repeat and offset setting priorities for uv2
  15664. // 1. ao map
  15665. // 2. light map
  15666. let uv2ScaleMap;
  15667. if ( material.aoMap ) {
  15668. uv2ScaleMap = material.aoMap;
  15669. } else if ( material.lightMap ) {
  15670. uv2ScaleMap = material.lightMap;
  15671. }
  15672. if ( uv2ScaleMap !== undefined ) {
  15673. // backwards compatibility
  15674. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15675. uv2ScaleMap = uv2ScaleMap.texture;
  15676. }
  15677. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15678. uv2ScaleMap.updateMatrix();
  15679. }
  15680. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15681. }
  15682. }
  15683. function refreshUniformsLine( uniforms, material ) {
  15684. uniforms.diffuse.value.copy( material.color );
  15685. uniforms.opacity.value = material.opacity;
  15686. }
  15687. function refreshUniformsDash( uniforms, material ) {
  15688. uniforms.dashSize.value = material.dashSize;
  15689. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15690. uniforms.scale.value = material.scale;
  15691. }
  15692. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15693. uniforms.diffuse.value.copy( material.color );
  15694. uniforms.opacity.value = material.opacity;
  15695. uniforms.size.value = material.size * pixelRatio;
  15696. uniforms.scale.value = height * 0.5;
  15697. if ( material.map ) {
  15698. uniforms.map.value = material.map;
  15699. }
  15700. if ( material.alphaMap ) {
  15701. uniforms.alphaMap.value = material.alphaMap;
  15702. }
  15703. if ( material.alphaTest > 0 ) {
  15704. uniforms.alphaTest.value = material.alphaTest;
  15705. }
  15706. // uv repeat and offset setting priorities
  15707. // 1. color map
  15708. // 2. alpha map
  15709. let uvScaleMap;
  15710. if ( material.map ) {
  15711. uvScaleMap = material.map;
  15712. } else if ( material.alphaMap ) {
  15713. uvScaleMap = material.alphaMap;
  15714. }
  15715. if ( uvScaleMap !== undefined ) {
  15716. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15717. uvScaleMap.updateMatrix();
  15718. }
  15719. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15720. }
  15721. }
  15722. function refreshUniformsSprites( uniforms, material ) {
  15723. uniforms.diffuse.value.copy( material.color );
  15724. uniforms.opacity.value = material.opacity;
  15725. uniforms.rotation.value = material.rotation;
  15726. if ( material.map ) {
  15727. uniforms.map.value = material.map;
  15728. }
  15729. if ( material.alphaMap ) {
  15730. uniforms.alphaMap.value = material.alphaMap;
  15731. }
  15732. if ( material.alphaTest > 0 ) {
  15733. uniforms.alphaTest.value = material.alphaTest;
  15734. }
  15735. // uv repeat and offset setting priorities
  15736. // 1. color map
  15737. // 2. alpha map
  15738. let uvScaleMap;
  15739. if ( material.map ) {
  15740. uvScaleMap = material.map;
  15741. } else if ( material.alphaMap ) {
  15742. uvScaleMap = material.alphaMap;
  15743. }
  15744. if ( uvScaleMap !== undefined ) {
  15745. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15746. uvScaleMap.updateMatrix();
  15747. }
  15748. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15749. }
  15750. }
  15751. function refreshUniformsPhong( uniforms, material ) {
  15752. uniforms.specular.value.copy( material.specular );
  15753. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15754. }
  15755. function refreshUniformsToon( uniforms, material ) {
  15756. if ( material.gradientMap ) {
  15757. uniforms.gradientMap.value = material.gradientMap;
  15758. }
  15759. }
  15760. function refreshUniformsStandard( uniforms, material ) {
  15761. uniforms.roughness.value = material.roughness;
  15762. uniforms.metalness.value = material.metalness;
  15763. if ( material.roughnessMap ) {
  15764. uniforms.roughnessMap.value = material.roughnessMap;
  15765. }
  15766. if ( material.metalnessMap ) {
  15767. uniforms.metalnessMap.value = material.metalnessMap;
  15768. }
  15769. const envMap = properties.get( material ).envMap;
  15770. if ( envMap ) {
  15771. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15772. uniforms.envMapIntensity.value = material.envMapIntensity;
  15773. }
  15774. }
  15775. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15776. uniforms.ior.value = material.ior; // also part of uniforms common
  15777. if ( material.sheen > 0 ) {
  15778. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15779. uniforms.sheenRoughness.value = material.sheenRoughness;
  15780. if ( material.sheenColorMap ) {
  15781. uniforms.sheenColorMap.value = material.sheenColorMap;
  15782. }
  15783. if ( material.sheenRoughnessMap ) {
  15784. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15785. }
  15786. }
  15787. if ( material.clearcoat > 0 ) {
  15788. uniforms.clearcoat.value = material.clearcoat;
  15789. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15790. if ( material.clearcoatMap ) {
  15791. uniforms.clearcoatMap.value = material.clearcoatMap;
  15792. }
  15793. if ( material.clearcoatRoughnessMap ) {
  15794. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15795. }
  15796. if ( material.clearcoatNormalMap ) {
  15797. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15798. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15799. if ( material.side === BackSide ) {
  15800. uniforms.clearcoatNormalScale.value.negate();
  15801. }
  15802. }
  15803. }
  15804. if ( material.iridescence > 0 ) {
  15805. uniforms.iridescence.value = material.iridescence;
  15806. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15807. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15808. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15809. if ( material.iridescenceMap ) {
  15810. uniforms.iridescenceMap.value = material.iridescenceMap;
  15811. }
  15812. if ( material.iridescenceThicknessMap ) {
  15813. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15814. }
  15815. }
  15816. if ( material.transmission > 0 ) {
  15817. uniforms.transmission.value = material.transmission;
  15818. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15819. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15820. if ( material.transmissionMap ) {
  15821. uniforms.transmissionMap.value = material.transmissionMap;
  15822. }
  15823. uniforms.thickness.value = material.thickness;
  15824. if ( material.thicknessMap ) {
  15825. uniforms.thicknessMap.value = material.thicknessMap;
  15826. }
  15827. uniforms.attenuationDistance.value = material.attenuationDistance;
  15828. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15829. }
  15830. uniforms.specularIntensity.value = material.specularIntensity;
  15831. uniforms.specularColor.value.copy( material.specularColor );
  15832. if ( material.specularIntensityMap ) {
  15833. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15834. }
  15835. if ( material.specularColorMap ) {
  15836. uniforms.specularColorMap.value = material.specularColorMap;
  15837. }
  15838. }
  15839. function refreshUniformsMatcap( uniforms, material ) {
  15840. if ( material.matcap ) {
  15841. uniforms.matcap.value = material.matcap;
  15842. }
  15843. }
  15844. function refreshUniformsDistance( uniforms, material ) {
  15845. uniforms.referencePosition.value.copy( material.referencePosition );
  15846. uniforms.nearDistance.value = material.nearDistance;
  15847. uniforms.farDistance.value = material.farDistance;
  15848. }
  15849. return {
  15850. refreshFogUniforms: refreshFogUniforms,
  15851. refreshMaterialUniforms: refreshMaterialUniforms
  15852. };
  15853. }
  15854. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15855. let buffers = {};
  15856. let updateList = {};
  15857. let allocatedBindingPoints = [];
  15858. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  15859. function bind( uniformsGroup, program ) {
  15860. const webglProgram = program.program;
  15861. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15862. }
  15863. function update( uniformsGroup, program ) {
  15864. let buffer = buffers[ uniformsGroup.id ];
  15865. if ( buffer === undefined ) {
  15866. prepareUniformsGroup( uniformsGroup );
  15867. buffer = createBuffer( uniformsGroup );
  15868. buffers[ uniformsGroup.id ] = buffer;
  15869. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15870. }
  15871. // ensure to update the binding points/block indices mapping for this program
  15872. const webglProgram = program.program;
  15873. state.updateUBOMapping( uniformsGroup, webglProgram );
  15874. // update UBO once per frame
  15875. const frame = info.render.frame;
  15876. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15877. updateBufferData( uniformsGroup );
  15878. updateList[ uniformsGroup.id ] = frame;
  15879. }
  15880. }
  15881. function createBuffer( uniformsGroup ) {
  15882. // the setup of an UBO is independent of a particular shader program but global
  15883. const bindingPointIndex = allocateBindingPointIndex();
  15884. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15885. const buffer = gl.createBuffer();
  15886. const size = uniformsGroup.__size;
  15887. const usage = uniformsGroup.usage;
  15888. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  15889. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  15890. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  15891. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  15892. return buffer;
  15893. }
  15894. function allocateBindingPointIndex() {
  15895. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15896. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15897. allocatedBindingPoints.push( i );
  15898. return i;
  15899. }
  15900. }
  15901. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15902. return 0;
  15903. }
  15904. function updateBufferData( uniformsGroup ) {
  15905. const buffer = buffers[ uniformsGroup.id ];
  15906. const uniforms = uniformsGroup.uniforms;
  15907. const cache = uniformsGroup.__cache;
  15908. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  15909. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15910. const uniform = uniforms[ i ];
  15911. // partly update the buffer if necessary
  15912. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15913. const offset = uniform.__offset;
  15914. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15915. let arrayOffset = 0;
  15916. for ( let i = 0; i < values.length; i ++ ) {
  15917. const value = values[ i ];
  15918. const info = getUniformSize( value );
  15919. if ( typeof value === 'number' ) {
  15920. uniform.__data[ 0 ] = value;
  15921. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  15922. } else if ( value.isMatrix3 ) {
  15923. // manually converting 3x3 to 3x4
  15924. uniform.__data[ 0 ] = value.elements[ 0 ];
  15925. uniform.__data[ 1 ] = value.elements[ 1 ];
  15926. uniform.__data[ 2 ] = value.elements[ 2 ];
  15927. uniform.__data[ 3 ] = value.elements[ 0 ];
  15928. uniform.__data[ 4 ] = value.elements[ 3 ];
  15929. uniform.__data[ 5 ] = value.elements[ 4 ];
  15930. uniform.__data[ 6 ] = value.elements[ 5 ];
  15931. uniform.__data[ 7 ] = value.elements[ 0 ];
  15932. uniform.__data[ 8 ] = value.elements[ 6 ];
  15933. uniform.__data[ 9 ] = value.elements[ 7 ];
  15934. uniform.__data[ 10 ] = value.elements[ 8 ];
  15935. uniform.__data[ 11 ] = value.elements[ 0 ];
  15936. } else {
  15937. value.toArray( uniform.__data, arrayOffset );
  15938. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  15939. }
  15940. }
  15941. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  15942. }
  15943. }
  15944. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  15945. }
  15946. function hasUniformChanged( uniform, index, cache ) {
  15947. const value = uniform.value;
  15948. if ( cache[ index ] === undefined ) {
  15949. // cache entry does not exist so far
  15950. if ( typeof value === 'number' ) {
  15951. cache[ index ] = value;
  15952. } else {
  15953. const values = Array.isArray( value ) ? value : [ value ];
  15954. const tempValues = [];
  15955. for ( let i = 0; i < values.length; i ++ ) {
  15956. tempValues.push( values[ i ].clone() );
  15957. }
  15958. cache[ index ] = tempValues;
  15959. }
  15960. return true;
  15961. } else {
  15962. // compare current value with cached entry
  15963. if ( typeof value === 'number' ) {
  15964. if ( cache[ index ] !== value ) {
  15965. cache[ index ] = value;
  15966. return true;
  15967. }
  15968. } else {
  15969. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  15970. const values = Array.isArray( value ) ? value : [ value ];
  15971. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  15972. const cachedObject = cachedObjects[ i ];
  15973. if ( cachedObject.equals( values[ i ] ) === false ) {
  15974. cachedObject.copy( values[ i ] );
  15975. return true;
  15976. }
  15977. }
  15978. }
  15979. }
  15980. return false;
  15981. }
  15982. function prepareUniformsGroup( uniformsGroup ) {
  15983. // determine total buffer size according to the STD140 layout
  15984. // Hint: STD140 is the only supported layout in WebGL 2
  15985. const uniforms = uniformsGroup.uniforms;
  15986. let offset = 0; // global buffer offset in bytes
  15987. const chunkSize = 16; // size of a chunk in bytes
  15988. let chunkOffset = 0; // offset within a single chunk in bytes
  15989. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  15990. const uniform = uniforms[ i ];
  15991. const infos = {
  15992. boundary: 0, // bytes
  15993. storage: 0 // bytes
  15994. };
  15995. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15996. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  15997. const value = values[ j ];
  15998. const info = getUniformSize( value );
  15999. infos.boundary += info.boundary;
  16000. infos.storage += info.storage;
  16001. }
  16002. // the following two properties will be used for partial buffer updates
  16003. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16004. uniform.__offset = offset;
  16005. //
  16006. if ( i > 0 ) {
  16007. chunkOffset = offset % chunkSize;
  16008. const remainingSizeInChunk = chunkSize - chunkOffset;
  16009. // check for chunk overflow
  16010. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16011. // add padding and adjust offset
  16012. offset += ( chunkSize - chunkOffset );
  16013. uniform.__offset = offset;
  16014. }
  16015. }
  16016. offset += infos.storage;
  16017. }
  16018. // ensure correct final padding
  16019. chunkOffset = offset % chunkSize;
  16020. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16021. //
  16022. uniformsGroup.__size = offset;
  16023. uniformsGroup.__cache = {};
  16024. return this;
  16025. }
  16026. function getUniformSize( value ) {
  16027. const info = {
  16028. boundary: 0, // bytes
  16029. storage: 0 // bytes
  16030. };
  16031. // determine sizes according to STD140
  16032. if ( typeof value === 'number' ) {
  16033. // float/int
  16034. info.boundary = 4;
  16035. info.storage = 4;
  16036. } else if ( value.isVector2 ) {
  16037. // vec2
  16038. info.boundary = 8;
  16039. info.storage = 8;
  16040. } else if ( value.isVector3 || value.isColor ) {
  16041. // vec3
  16042. info.boundary = 16;
  16043. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16044. } else if ( value.isVector4 ) {
  16045. // vec4
  16046. info.boundary = 16;
  16047. info.storage = 16;
  16048. } else if ( value.isMatrix3 ) {
  16049. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16050. info.boundary = 48;
  16051. info.storage = 48;
  16052. } else if ( value.isMatrix4 ) {
  16053. // mat4
  16054. info.boundary = 64;
  16055. info.storage = 64;
  16056. } else if ( value.isTexture ) {
  16057. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16058. } else {
  16059. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16060. }
  16061. return info;
  16062. }
  16063. function onUniformsGroupsDispose( event ) {
  16064. const uniformsGroup = event.target;
  16065. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16066. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16067. allocatedBindingPoints.splice( index, 1 );
  16068. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16069. delete buffers[ uniformsGroup.id ];
  16070. delete updateList[ uniformsGroup.id ];
  16071. }
  16072. function dispose() {
  16073. for ( const id in buffers ) {
  16074. gl.deleteBuffer( buffers[ id ] );
  16075. }
  16076. allocatedBindingPoints = [];
  16077. buffers = {};
  16078. updateList = {};
  16079. }
  16080. return {
  16081. bind: bind,
  16082. update: update,
  16083. dispose: dispose
  16084. };
  16085. }
  16086. function createCanvasElement() {
  16087. const canvas = createElementNS( 'canvas' );
  16088. canvas.style.display = 'block';
  16089. return canvas;
  16090. }
  16091. function WebGLRenderer( parameters = {} ) {
  16092. this.isWebGLRenderer = true;
  16093. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16094. _context = parameters.context !== undefined ? parameters.context : null,
  16095. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16096. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16097. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16098. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16099. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16100. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16101. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16102. let _alpha;
  16103. if ( _context !== null ) {
  16104. _alpha = _context.getContextAttributes().alpha;
  16105. } else {
  16106. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16107. }
  16108. let currentRenderList = null;
  16109. let currentRenderState = null;
  16110. // render() can be called from within a callback triggered by another render.
  16111. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16112. const renderListStack = [];
  16113. const renderStateStack = [];
  16114. // public properties
  16115. this.domElement = _canvas;
  16116. // Debug configuration container
  16117. this.debug = {
  16118. /**
  16119. * Enables error checking and reporting when shader programs are being compiled
  16120. * @type {boolean}
  16121. */
  16122. checkShaderErrors: true
  16123. };
  16124. // clearing
  16125. this.autoClear = true;
  16126. this.autoClearColor = true;
  16127. this.autoClearDepth = true;
  16128. this.autoClearStencil = true;
  16129. // scene graph
  16130. this.sortObjects = true;
  16131. // user-defined clipping
  16132. this.clippingPlanes = [];
  16133. this.localClippingEnabled = false;
  16134. // physically based shading
  16135. this.outputEncoding = LinearEncoding;
  16136. // physical lights
  16137. this.physicallyCorrectLights = false;
  16138. // tone mapping
  16139. this.toneMapping = NoToneMapping;
  16140. this.toneMappingExposure = 1.0;
  16141. // internal properties
  16142. const _this = this;
  16143. let _isContextLost = false;
  16144. // internal state cache
  16145. let _currentActiveCubeFace = 0;
  16146. let _currentActiveMipmapLevel = 0;
  16147. let _currentRenderTarget = null;
  16148. let _currentMaterialId = - 1;
  16149. let _currentCamera = null;
  16150. const _currentViewport = new Vector4();
  16151. const _currentScissor = new Vector4();
  16152. let _currentScissorTest = null;
  16153. //
  16154. let _width = _canvas.width;
  16155. let _height = _canvas.height;
  16156. let _pixelRatio = 1;
  16157. let _opaqueSort = null;
  16158. let _transparentSort = null;
  16159. const _viewport = new Vector4( 0, 0, _width, _height );
  16160. const _scissor = new Vector4( 0, 0, _width, _height );
  16161. let _scissorTest = false;
  16162. // frustum
  16163. const _frustum = new Frustum();
  16164. // clipping
  16165. let _clippingEnabled = false;
  16166. let _localClippingEnabled = false;
  16167. // transmission
  16168. let _transmissionRenderTarget = null;
  16169. // camera matrices cache
  16170. const _projScreenMatrix = new Matrix4();
  16171. const _vector2 = new Vector2();
  16172. const _vector3 = new Vector3();
  16173. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16174. function getTargetPixelRatio() {
  16175. return _currentRenderTarget === null ? _pixelRatio : 1;
  16176. }
  16177. // initialize
  16178. let _gl = _context;
  16179. function getContext( contextNames, contextAttributes ) {
  16180. for ( let i = 0; i < contextNames.length; i ++ ) {
  16181. const contextName = contextNames[ i ];
  16182. const context = _canvas.getContext( contextName, contextAttributes );
  16183. if ( context !== null ) return context;
  16184. }
  16185. return null;
  16186. }
  16187. try {
  16188. const contextAttributes = {
  16189. alpha: true,
  16190. depth: _depth,
  16191. stencil: _stencil,
  16192. antialias: _antialias,
  16193. premultipliedAlpha: _premultipliedAlpha,
  16194. preserveDrawingBuffer: _preserveDrawingBuffer,
  16195. powerPreference: _powerPreference,
  16196. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16197. };
  16198. // OffscreenCanvas does not have setAttribute, see #22811
  16199. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16200. // event listeners must be registered before WebGL context is created, see #12753
  16201. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16202. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16203. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16204. if ( _gl === null ) {
  16205. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16206. if ( _this.isWebGL1Renderer === true ) {
  16207. contextNames.shift();
  16208. }
  16209. _gl = getContext( contextNames, contextAttributes );
  16210. if ( _gl === null ) {
  16211. if ( getContext( contextNames ) ) {
  16212. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16213. } else {
  16214. throw new Error( 'Error creating WebGL context.' );
  16215. }
  16216. }
  16217. }
  16218. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16219. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16220. _gl.getShaderPrecisionFormat = function () {
  16221. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16222. };
  16223. }
  16224. } catch ( error ) {
  16225. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16226. throw error;
  16227. }
  16228. let extensions, capabilities, state, info;
  16229. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16230. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16231. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16232. let utils, bindingStates, uniformsGroups;
  16233. function initGLContext() {
  16234. extensions = new WebGLExtensions( _gl );
  16235. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16236. extensions.init( capabilities );
  16237. utils = new WebGLUtils( _gl, extensions, capabilities );
  16238. state = new WebGLState( _gl, extensions, capabilities );
  16239. info = new WebGLInfo( _gl );
  16240. properties = new WebGLProperties();
  16241. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16242. cubemaps = new WebGLCubeMaps( _this );
  16243. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16244. attributes = new WebGLAttributes( _gl, capabilities );
  16245. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16246. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16247. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16248. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16249. clipping = new WebGLClipping( properties );
  16250. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16251. materials = new WebGLMaterials( _this, properties );
  16252. renderLists = new WebGLRenderLists();
  16253. renderStates = new WebGLRenderStates( extensions, capabilities );
  16254. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16255. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16256. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16257. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16258. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16259. info.programs = programCache.programs;
  16260. _this.capabilities = capabilities;
  16261. _this.extensions = extensions;
  16262. _this.properties = properties;
  16263. _this.renderLists = renderLists;
  16264. _this.shadowMap = shadowMap;
  16265. _this.state = state;
  16266. _this.info = info;
  16267. }
  16268. initGLContext();
  16269. // xr
  16270. const xr = new WebXRManager( _this, _gl );
  16271. this.xr = xr;
  16272. // API
  16273. this.getContext = function () {
  16274. return _gl;
  16275. };
  16276. this.getContextAttributes = function () {
  16277. return _gl.getContextAttributes();
  16278. };
  16279. this.forceContextLoss = function () {
  16280. const extension = extensions.get( 'WEBGL_lose_context' );
  16281. if ( extension ) extension.loseContext();
  16282. };
  16283. this.forceContextRestore = function () {
  16284. const extension = extensions.get( 'WEBGL_lose_context' );
  16285. if ( extension ) extension.restoreContext();
  16286. };
  16287. this.getPixelRatio = function () {
  16288. return _pixelRatio;
  16289. };
  16290. this.setPixelRatio = function ( value ) {
  16291. if ( value === undefined ) return;
  16292. _pixelRatio = value;
  16293. this.setSize( _width, _height, false );
  16294. };
  16295. this.getSize = function ( target ) {
  16296. return target.set( _width, _height );
  16297. };
  16298. this.setSize = function ( width, height, updateStyle ) {
  16299. if ( xr.isPresenting ) {
  16300. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16301. return;
  16302. }
  16303. _width = width;
  16304. _height = height;
  16305. _canvas.width = Math.floor( width * _pixelRatio );
  16306. _canvas.height = Math.floor( height * _pixelRatio );
  16307. if ( updateStyle !== false ) {
  16308. _canvas.style.width = width + 'px';
  16309. _canvas.style.height = height + 'px';
  16310. }
  16311. this.setViewport( 0, 0, width, height );
  16312. };
  16313. this.getDrawingBufferSize = function ( target ) {
  16314. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16315. };
  16316. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16317. _width = width;
  16318. _height = height;
  16319. _pixelRatio = pixelRatio;
  16320. _canvas.width = Math.floor( width * pixelRatio );
  16321. _canvas.height = Math.floor( height * pixelRatio );
  16322. this.setViewport( 0, 0, width, height );
  16323. };
  16324. this.getCurrentViewport = function ( target ) {
  16325. return target.copy( _currentViewport );
  16326. };
  16327. this.getViewport = function ( target ) {
  16328. return target.copy( _viewport );
  16329. };
  16330. this.setViewport = function ( x, y, width, height ) {
  16331. if ( x.isVector4 ) {
  16332. _viewport.set( x.x, x.y, x.z, x.w );
  16333. } else {
  16334. _viewport.set( x, y, width, height );
  16335. }
  16336. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16337. };
  16338. this.getScissor = function ( target ) {
  16339. return target.copy( _scissor );
  16340. };
  16341. this.setScissor = function ( x, y, width, height ) {
  16342. if ( x.isVector4 ) {
  16343. _scissor.set( x.x, x.y, x.z, x.w );
  16344. } else {
  16345. _scissor.set( x, y, width, height );
  16346. }
  16347. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16348. };
  16349. this.getScissorTest = function () {
  16350. return _scissorTest;
  16351. };
  16352. this.setScissorTest = function ( boolean ) {
  16353. state.setScissorTest( _scissorTest = boolean );
  16354. };
  16355. this.setOpaqueSort = function ( method ) {
  16356. _opaqueSort = method;
  16357. };
  16358. this.setTransparentSort = function ( method ) {
  16359. _transparentSort = method;
  16360. };
  16361. // Clearing
  16362. this.getClearColor = function ( target ) {
  16363. return target.copy( background.getClearColor() );
  16364. };
  16365. this.setClearColor = function () {
  16366. background.setClearColor.apply( background, arguments );
  16367. };
  16368. this.getClearAlpha = function () {
  16369. return background.getClearAlpha();
  16370. };
  16371. this.setClearAlpha = function () {
  16372. background.setClearAlpha.apply( background, arguments );
  16373. };
  16374. this.clear = function ( color = true, depth = true, stencil = true ) {
  16375. let bits = 0;
  16376. if ( color ) bits |= _gl.COLOR_BUFFER_BIT;
  16377. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16378. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16379. _gl.clear( bits );
  16380. };
  16381. this.clearColor = function () {
  16382. this.clear( true, false, false );
  16383. };
  16384. this.clearDepth = function () {
  16385. this.clear( false, true, false );
  16386. };
  16387. this.clearStencil = function () {
  16388. this.clear( false, false, true );
  16389. };
  16390. //
  16391. this.dispose = function () {
  16392. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16393. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16394. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16395. renderLists.dispose();
  16396. renderStates.dispose();
  16397. properties.dispose();
  16398. cubemaps.dispose();
  16399. cubeuvmaps.dispose();
  16400. objects.dispose();
  16401. bindingStates.dispose();
  16402. uniformsGroups.dispose();
  16403. programCache.dispose();
  16404. xr.dispose();
  16405. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16406. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16407. if ( _transmissionRenderTarget ) {
  16408. _transmissionRenderTarget.dispose();
  16409. _transmissionRenderTarget = null;
  16410. }
  16411. animation.stop();
  16412. };
  16413. // Events
  16414. function onContextLost( event ) {
  16415. event.preventDefault();
  16416. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16417. _isContextLost = true;
  16418. }
  16419. function onContextRestore( /* event */ ) {
  16420. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16421. _isContextLost = false;
  16422. const infoAutoReset = info.autoReset;
  16423. const shadowMapEnabled = shadowMap.enabled;
  16424. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16425. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16426. const shadowMapType = shadowMap.type;
  16427. initGLContext();
  16428. info.autoReset = infoAutoReset;
  16429. shadowMap.enabled = shadowMapEnabled;
  16430. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16431. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16432. shadowMap.type = shadowMapType;
  16433. }
  16434. function onContextCreationError( event ) {
  16435. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16436. }
  16437. function onMaterialDispose( event ) {
  16438. const material = event.target;
  16439. material.removeEventListener( 'dispose', onMaterialDispose );
  16440. deallocateMaterial( material );
  16441. }
  16442. // Buffer deallocation
  16443. function deallocateMaterial( material ) {
  16444. releaseMaterialProgramReferences( material );
  16445. properties.remove( material );
  16446. }
  16447. function releaseMaterialProgramReferences( material ) {
  16448. const programs = properties.get( material ).programs;
  16449. if ( programs !== undefined ) {
  16450. programs.forEach( function ( program ) {
  16451. programCache.releaseProgram( program );
  16452. } );
  16453. if ( material.isShaderMaterial ) {
  16454. programCache.releaseShaderCache( material );
  16455. }
  16456. }
  16457. }
  16458. // Buffer rendering
  16459. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16460. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16461. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16462. const program = setProgram( camera, scene, geometry, material, object );
  16463. state.setMaterial( material, frontFaceCW );
  16464. //
  16465. let index = geometry.index;
  16466. let rangeFactor = 1;
  16467. if ( material.wireframe === true ) {
  16468. index = geometries.getWireframeAttribute( geometry );
  16469. rangeFactor = 2;
  16470. }
  16471. //
  16472. const drawRange = geometry.drawRange;
  16473. const position = geometry.attributes.position;
  16474. let drawStart = drawRange.start * rangeFactor;
  16475. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16476. if ( group !== null ) {
  16477. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16478. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16479. }
  16480. if ( index !== null ) {
  16481. drawStart = Math.max( drawStart, 0 );
  16482. drawEnd = Math.min( drawEnd, index.count );
  16483. } else if ( position !== undefined && position !== null ) {
  16484. drawStart = Math.max( drawStart, 0 );
  16485. drawEnd = Math.min( drawEnd, position.count );
  16486. }
  16487. const drawCount = drawEnd - drawStart;
  16488. if ( drawCount < 0 || drawCount === Infinity ) return;
  16489. //
  16490. bindingStates.setup( object, material, program, geometry, index );
  16491. let attribute;
  16492. let renderer = bufferRenderer;
  16493. if ( index !== null ) {
  16494. attribute = attributes.get( index );
  16495. renderer = indexedBufferRenderer;
  16496. renderer.setIndex( attribute );
  16497. }
  16498. //
  16499. if ( object.isMesh ) {
  16500. if ( material.wireframe === true ) {
  16501. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16502. renderer.setMode( _gl.LINES );
  16503. } else {
  16504. renderer.setMode( _gl.TRIANGLES );
  16505. }
  16506. } else if ( object.isLine ) {
  16507. let lineWidth = material.linewidth;
  16508. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16509. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16510. if ( object.isLineSegments ) {
  16511. renderer.setMode( _gl.LINES );
  16512. } else if ( object.isLineLoop ) {
  16513. renderer.setMode( _gl.LINE_LOOP );
  16514. } else {
  16515. renderer.setMode( _gl.LINE_STRIP );
  16516. }
  16517. } else if ( object.isPoints ) {
  16518. renderer.setMode( _gl.POINTS );
  16519. } else if ( object.isSprite ) {
  16520. renderer.setMode( _gl.TRIANGLES );
  16521. }
  16522. if ( object.isInstancedMesh ) {
  16523. renderer.renderInstances( drawStart, drawCount, object.count );
  16524. } else if ( geometry.isInstancedBufferGeometry ) {
  16525. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16526. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16527. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16528. } else {
  16529. renderer.render( drawStart, drawCount );
  16530. }
  16531. };
  16532. // Compile
  16533. this.compile = function ( scene, camera ) {
  16534. function prepare( material, scene, object ) {
  16535. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16536. material.side = BackSide;
  16537. material.needsUpdate = true;
  16538. getProgram( material, scene, object );
  16539. material.side = FrontSide;
  16540. material.needsUpdate = true;
  16541. getProgram( material, scene, object );
  16542. material.side = DoubleSide;
  16543. } else {
  16544. getProgram( material, scene, object );
  16545. }
  16546. }
  16547. currentRenderState = renderStates.get( scene );
  16548. currentRenderState.init();
  16549. renderStateStack.push( currentRenderState );
  16550. scene.traverseVisible( function ( object ) {
  16551. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16552. currentRenderState.pushLight( object );
  16553. if ( object.castShadow ) {
  16554. currentRenderState.pushShadow( object );
  16555. }
  16556. }
  16557. } );
  16558. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16559. scene.traverse( function ( object ) {
  16560. const material = object.material;
  16561. if ( material ) {
  16562. if ( Array.isArray( material ) ) {
  16563. for ( let i = 0; i < material.length; i ++ ) {
  16564. const material2 = material[ i ];
  16565. prepare( material2, scene, object );
  16566. }
  16567. } else {
  16568. prepare( material, scene, object );
  16569. }
  16570. }
  16571. } );
  16572. renderStateStack.pop();
  16573. currentRenderState = null;
  16574. };
  16575. // Animation Loop
  16576. let onAnimationFrameCallback = null;
  16577. function onAnimationFrame( time ) {
  16578. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16579. }
  16580. function onXRSessionStart() {
  16581. animation.stop();
  16582. }
  16583. function onXRSessionEnd() {
  16584. animation.start();
  16585. }
  16586. const animation = new WebGLAnimation();
  16587. animation.setAnimationLoop( onAnimationFrame );
  16588. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16589. this.setAnimationLoop = function ( callback ) {
  16590. onAnimationFrameCallback = callback;
  16591. xr.setAnimationLoop( callback );
  16592. ( callback === null ) ? animation.stop() : animation.start();
  16593. };
  16594. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16595. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16596. // Rendering
  16597. this.render = function ( scene, camera ) {
  16598. if ( camera !== undefined && camera.isCamera !== true ) {
  16599. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16600. return;
  16601. }
  16602. if ( _isContextLost === true ) return;
  16603. // update scene graph
  16604. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16605. // update camera matrices and frustum
  16606. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16607. if ( xr.enabled === true && xr.isPresenting === true ) {
  16608. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16609. camera = xr.getCamera(); // use XR camera for rendering
  16610. }
  16611. //
  16612. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16613. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16614. currentRenderState.init();
  16615. renderStateStack.push( currentRenderState );
  16616. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16617. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16618. _localClippingEnabled = this.localClippingEnabled;
  16619. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16620. currentRenderList = renderLists.get( scene, renderListStack.length );
  16621. currentRenderList.init();
  16622. renderListStack.push( currentRenderList );
  16623. projectObject( scene, camera, 0, _this.sortObjects );
  16624. currentRenderList.finish();
  16625. if ( _this.sortObjects === true ) {
  16626. currentRenderList.sort( _opaqueSort, _transparentSort );
  16627. }
  16628. //
  16629. if ( _clippingEnabled === true ) clipping.beginShadows();
  16630. const shadowsArray = currentRenderState.state.shadowsArray;
  16631. shadowMap.render( shadowsArray, scene, camera );
  16632. if ( _clippingEnabled === true ) clipping.endShadows();
  16633. //
  16634. if ( this.info.autoReset === true ) this.info.reset();
  16635. //
  16636. background.render( currentRenderList, scene );
  16637. // render scene
  16638. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16639. if ( camera.isArrayCamera ) {
  16640. const cameras = camera.cameras;
  16641. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16642. const camera2 = cameras[ i ];
  16643. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16644. }
  16645. } else {
  16646. renderScene( currentRenderList, scene, camera );
  16647. }
  16648. //
  16649. if ( _currentRenderTarget !== null ) {
  16650. // resolve multisample renderbuffers to a single-sample texture if necessary
  16651. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16652. // Generate mipmap if we're using any kind of mipmap filtering
  16653. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16654. }
  16655. //
  16656. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16657. // _gl.finish();
  16658. bindingStates.resetDefaultState();
  16659. _currentMaterialId = - 1;
  16660. _currentCamera = null;
  16661. renderStateStack.pop();
  16662. if ( renderStateStack.length > 0 ) {
  16663. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16664. } else {
  16665. currentRenderState = null;
  16666. }
  16667. renderListStack.pop();
  16668. if ( renderListStack.length > 0 ) {
  16669. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16670. } else {
  16671. currentRenderList = null;
  16672. }
  16673. };
  16674. function projectObject( object, camera, groupOrder, sortObjects ) {
  16675. if ( object.visible === false ) return;
  16676. const visible = object.layers.test( camera.layers );
  16677. if ( visible ) {
  16678. if ( object.isGroup ) {
  16679. groupOrder = object.renderOrder;
  16680. } else if ( object.isLOD ) {
  16681. if ( object.autoUpdate === true ) object.update( camera );
  16682. } else if ( object.isLight ) {
  16683. currentRenderState.pushLight( object );
  16684. if ( object.castShadow ) {
  16685. currentRenderState.pushShadow( object );
  16686. }
  16687. } else if ( object.isSprite ) {
  16688. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16689. if ( sortObjects ) {
  16690. _vector3.setFromMatrixPosition( object.matrixWorld )
  16691. .applyMatrix4( _projScreenMatrix );
  16692. }
  16693. const geometry = objects.update( object );
  16694. const material = object.material;
  16695. if ( material.visible ) {
  16696. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16697. }
  16698. }
  16699. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16700. if ( object.isSkinnedMesh ) {
  16701. // update skeleton only once in a frame
  16702. if ( object.skeleton.frame !== info.render.frame ) {
  16703. object.skeleton.update();
  16704. object.skeleton.frame = info.render.frame;
  16705. }
  16706. }
  16707. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16708. if ( sortObjects ) {
  16709. _vector3.setFromMatrixPosition( object.matrixWorld )
  16710. .applyMatrix4( _projScreenMatrix );
  16711. }
  16712. const geometry = objects.update( object );
  16713. const material = object.material;
  16714. if ( Array.isArray( material ) ) {
  16715. const groups = geometry.groups;
  16716. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16717. const group = groups[ i ];
  16718. const groupMaterial = material[ group.materialIndex ];
  16719. if ( groupMaterial && groupMaterial.visible ) {
  16720. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16721. }
  16722. }
  16723. } else if ( material.visible ) {
  16724. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16725. }
  16726. }
  16727. }
  16728. }
  16729. const children = object.children;
  16730. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16731. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16732. }
  16733. }
  16734. function renderScene( currentRenderList, scene, camera, viewport ) {
  16735. const opaqueObjects = currentRenderList.opaque;
  16736. const transmissiveObjects = currentRenderList.transmissive;
  16737. const transparentObjects = currentRenderList.transparent;
  16738. currentRenderState.setupLightsView( camera );
  16739. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16740. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16741. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16742. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16743. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16744. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16745. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16746. state.buffers.depth.setTest( true );
  16747. state.buffers.depth.setMask( true );
  16748. state.buffers.color.setMask( true );
  16749. state.setPolygonOffset( false );
  16750. }
  16751. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16752. const isWebGL2 = capabilities.isWebGL2;
  16753. if ( _transmissionRenderTarget === null ) {
  16754. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16755. generateMipmaps: true,
  16756. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16757. minFilter: LinearMipmapLinearFilter,
  16758. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16759. } );
  16760. }
  16761. _this.getDrawingBufferSize( _vector2 );
  16762. if ( isWebGL2 ) {
  16763. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16764. } else {
  16765. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16766. }
  16767. //
  16768. const currentRenderTarget = _this.getRenderTarget();
  16769. _this.setRenderTarget( _transmissionRenderTarget );
  16770. _this.clear();
  16771. // Turn off the features which can affect the frag color for opaque objects pass.
  16772. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16773. const currentToneMapping = _this.toneMapping;
  16774. _this.toneMapping = NoToneMapping;
  16775. renderObjects( opaqueObjects, scene, camera );
  16776. _this.toneMapping = currentToneMapping;
  16777. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16778. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16779. _this.setRenderTarget( currentRenderTarget );
  16780. }
  16781. function renderObjects( renderList, scene, camera ) {
  16782. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16783. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16784. const renderItem = renderList[ i ];
  16785. const object = renderItem.object;
  16786. const geometry = renderItem.geometry;
  16787. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16788. const group = renderItem.group;
  16789. if ( object.layers.test( camera.layers ) ) {
  16790. renderObject( object, scene, camera, geometry, material, group );
  16791. }
  16792. }
  16793. }
  16794. function renderObject( object, scene, camera, geometry, material, group ) {
  16795. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16796. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16797. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16798. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16799. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16800. material.side = BackSide;
  16801. material.needsUpdate = true;
  16802. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16803. material.side = FrontSide;
  16804. material.needsUpdate = true;
  16805. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16806. material.side = DoubleSide;
  16807. } else {
  16808. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16809. }
  16810. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16811. }
  16812. function getProgram( material, scene, object ) {
  16813. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16814. const materialProperties = properties.get( material );
  16815. const lights = currentRenderState.state.lights;
  16816. const shadowsArray = currentRenderState.state.shadowsArray;
  16817. const lightsStateVersion = lights.state.version;
  16818. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16819. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16820. let programs = materialProperties.programs;
  16821. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16822. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16823. materialProperties.fog = scene.fog;
  16824. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16825. if ( programs === undefined ) {
  16826. // new material
  16827. material.addEventListener( 'dispose', onMaterialDispose );
  16828. programs = new Map();
  16829. materialProperties.programs = programs;
  16830. }
  16831. let program = programs.get( programCacheKey );
  16832. if ( program !== undefined ) {
  16833. // early out if program and light state is identical
  16834. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16835. updateCommonMaterialProperties( material, parameters );
  16836. return program;
  16837. }
  16838. } else {
  16839. parameters.uniforms = programCache.getUniforms( material );
  16840. material.onBuild( object, parameters, _this );
  16841. material.onBeforeCompile( parameters, _this );
  16842. program = programCache.acquireProgram( parameters, programCacheKey );
  16843. programs.set( programCacheKey, program );
  16844. materialProperties.uniforms = parameters.uniforms;
  16845. }
  16846. const uniforms = materialProperties.uniforms;
  16847. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16848. uniforms.clippingPlanes = clipping.uniform;
  16849. }
  16850. updateCommonMaterialProperties( material, parameters );
  16851. // store the light setup it was created for
  16852. materialProperties.needsLights = materialNeedsLights( material );
  16853. materialProperties.lightsStateVersion = lightsStateVersion;
  16854. if ( materialProperties.needsLights ) {
  16855. // wire up the material to this renderer's lighting state
  16856. uniforms.ambientLightColor.value = lights.state.ambient;
  16857. uniforms.lightProbe.value = lights.state.probe;
  16858. uniforms.directionalLights.value = lights.state.directional;
  16859. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16860. uniforms.spotLights.value = lights.state.spot;
  16861. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16862. uniforms.rectAreaLights.value = lights.state.rectArea;
  16863. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16864. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16865. uniforms.pointLights.value = lights.state.point;
  16866. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16867. uniforms.hemisphereLights.value = lights.state.hemi;
  16868. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16869. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16870. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16871. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16872. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16873. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16874. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16875. // TODO (abelnation): add area lights shadow info to uniforms
  16876. }
  16877. const progUniforms = program.getUniforms();
  16878. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16879. materialProperties.currentProgram = program;
  16880. materialProperties.uniformsList = uniformsList;
  16881. return program;
  16882. }
  16883. function updateCommonMaterialProperties( material, parameters ) {
  16884. const materialProperties = properties.get( material );
  16885. materialProperties.outputEncoding = parameters.outputEncoding;
  16886. materialProperties.instancing = parameters.instancing;
  16887. materialProperties.skinning = parameters.skinning;
  16888. materialProperties.morphTargets = parameters.morphTargets;
  16889. materialProperties.morphNormals = parameters.morphNormals;
  16890. materialProperties.morphColors = parameters.morphColors;
  16891. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16892. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16893. materialProperties.numIntersection = parameters.numClipIntersection;
  16894. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16895. materialProperties.vertexTangents = parameters.vertexTangents;
  16896. materialProperties.toneMapping = parameters.toneMapping;
  16897. }
  16898. function setProgram( camera, scene, geometry, material, object ) {
  16899. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16900. textures.resetTextureUnits();
  16901. const fog = scene.fog;
  16902. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16903. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16904. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16905. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16906. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16907. const morphTargets = !! geometry.morphAttributes.position;
  16908. const morphNormals = !! geometry.morphAttributes.normal;
  16909. const morphColors = !! geometry.morphAttributes.color;
  16910. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16911. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16912. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16913. const materialProperties = properties.get( material );
  16914. const lights = currentRenderState.state.lights;
  16915. if ( _clippingEnabled === true ) {
  16916. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16917. const useCache =
  16918. camera === _currentCamera &&
  16919. material.id === _currentMaterialId;
  16920. // we might want to call this function with some ClippingGroup
  16921. // object instead of the material, once it becomes feasible
  16922. // (#8465, #8379)
  16923. clipping.setState( material, camera, useCache );
  16924. }
  16925. }
  16926. //
  16927. let needsProgramChange = false;
  16928. if ( material.version === materialProperties.__version ) {
  16929. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16930. needsProgramChange = true;
  16931. } else if ( materialProperties.outputEncoding !== encoding ) {
  16932. needsProgramChange = true;
  16933. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16934. needsProgramChange = true;
  16935. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16936. needsProgramChange = true;
  16937. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16938. needsProgramChange = true;
  16939. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16940. needsProgramChange = true;
  16941. } else if ( materialProperties.envMap !== envMap ) {
  16942. needsProgramChange = true;
  16943. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16944. needsProgramChange = true;
  16945. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16946. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16947. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16948. needsProgramChange = true;
  16949. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16950. needsProgramChange = true;
  16951. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16952. needsProgramChange = true;
  16953. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16954. needsProgramChange = true;
  16955. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16956. needsProgramChange = true;
  16957. } else if ( materialProperties.morphColors !== morphColors ) {
  16958. needsProgramChange = true;
  16959. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16960. needsProgramChange = true;
  16961. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16962. needsProgramChange = true;
  16963. }
  16964. } else {
  16965. needsProgramChange = true;
  16966. materialProperties.__version = material.version;
  16967. }
  16968. //
  16969. let program = materialProperties.currentProgram;
  16970. if ( needsProgramChange === true ) {
  16971. program = getProgram( material, scene, object );
  16972. }
  16973. let refreshProgram = false;
  16974. let refreshMaterial = false;
  16975. let refreshLights = false;
  16976. const p_uniforms = program.getUniforms(),
  16977. m_uniforms = materialProperties.uniforms;
  16978. if ( state.useProgram( program.program ) ) {
  16979. refreshProgram = true;
  16980. refreshMaterial = true;
  16981. refreshLights = true;
  16982. }
  16983. if ( material.id !== _currentMaterialId ) {
  16984. _currentMaterialId = material.id;
  16985. refreshMaterial = true;
  16986. }
  16987. if ( refreshProgram || _currentCamera !== camera ) {
  16988. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16989. if ( capabilities.logarithmicDepthBuffer ) {
  16990. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16991. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16992. }
  16993. if ( _currentCamera !== camera ) {
  16994. _currentCamera = camera;
  16995. // lighting uniforms depend on the camera so enforce an update
  16996. // now, in case this material supports lights - or later, when
  16997. // the next material that does gets activated:
  16998. refreshMaterial = true; // set to true on material change
  16999. refreshLights = true; // remains set until update done
  17000. }
  17001. // load material specific uniforms
  17002. // (shader material also gets them for the sake of genericity)
  17003. if ( material.isShaderMaterial ||
  17004. material.isMeshPhongMaterial ||
  17005. material.isMeshToonMaterial ||
  17006. material.isMeshStandardMaterial ||
  17007. material.envMap ) {
  17008. const uCamPos = p_uniforms.map.cameraPosition;
  17009. if ( uCamPos !== undefined ) {
  17010. uCamPos.setValue( _gl,
  17011. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17012. }
  17013. }
  17014. if ( material.isMeshPhongMaterial ||
  17015. material.isMeshToonMaterial ||
  17016. material.isMeshLambertMaterial ||
  17017. material.isMeshBasicMaterial ||
  17018. material.isMeshStandardMaterial ||
  17019. material.isShaderMaterial ) {
  17020. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17021. }
  17022. if ( material.isMeshPhongMaterial ||
  17023. material.isMeshToonMaterial ||
  17024. material.isMeshLambertMaterial ||
  17025. material.isMeshBasicMaterial ||
  17026. material.isMeshStandardMaterial ||
  17027. material.isShaderMaterial ||
  17028. material.isShadowMaterial ||
  17029. object.isSkinnedMesh ) {
  17030. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17031. }
  17032. }
  17033. // skinning and morph target uniforms must be set even if material didn't change
  17034. // auto-setting of texture unit for bone and morph texture must go before other textures
  17035. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17036. if ( object.isSkinnedMesh ) {
  17037. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17038. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17039. const skeleton = object.skeleton;
  17040. if ( skeleton ) {
  17041. if ( capabilities.floatVertexTextures ) {
  17042. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17043. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17044. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17045. } else {
  17046. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17047. }
  17048. }
  17049. }
  17050. const morphAttributes = geometry.morphAttributes;
  17051. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17052. morphtargets.update( object, geometry, material, program );
  17053. }
  17054. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17055. materialProperties.receiveShadow = object.receiveShadow;
  17056. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17057. }
  17058. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17059. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17060. m_uniforms.envMap.value = envMap;
  17061. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17062. }
  17063. if ( refreshMaterial ) {
  17064. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17065. if ( materialProperties.needsLights ) {
  17066. // the current material requires lighting info
  17067. // note: all lighting uniforms are always set correctly
  17068. // they simply reference the renderer's state for their
  17069. // values
  17070. //
  17071. // use the current material's .needsUpdate flags to set
  17072. // the GL state when required
  17073. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17074. }
  17075. // refresh uniforms common to several materials
  17076. if ( fog && material.fog === true ) {
  17077. materials.refreshFogUniforms( m_uniforms, fog );
  17078. }
  17079. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17080. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17081. }
  17082. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17083. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17084. material.uniformsNeedUpdate = false;
  17085. }
  17086. if ( material.isSpriteMaterial ) {
  17087. p_uniforms.setValue( _gl, 'center', object.center );
  17088. }
  17089. // common matrices
  17090. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17091. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17092. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17093. // UBOs
  17094. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17095. const groups = material.uniformsGroups;
  17096. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17097. if ( capabilities.isWebGL2 ) {
  17098. const group = groups[ i ];
  17099. uniformsGroups.update( group, program );
  17100. uniformsGroups.bind( group, program );
  17101. } else {
  17102. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17103. }
  17104. }
  17105. }
  17106. return program;
  17107. }
  17108. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17109. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17110. uniforms.ambientLightColor.needsUpdate = value;
  17111. uniforms.lightProbe.needsUpdate = value;
  17112. uniforms.directionalLights.needsUpdate = value;
  17113. uniforms.directionalLightShadows.needsUpdate = value;
  17114. uniforms.pointLights.needsUpdate = value;
  17115. uniforms.pointLightShadows.needsUpdate = value;
  17116. uniforms.spotLights.needsUpdate = value;
  17117. uniforms.spotLightShadows.needsUpdate = value;
  17118. uniforms.rectAreaLights.needsUpdate = value;
  17119. uniforms.hemisphereLights.needsUpdate = value;
  17120. }
  17121. function materialNeedsLights( material ) {
  17122. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17123. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17124. ( material.isShaderMaterial && material.lights === true );
  17125. }
  17126. this.getActiveCubeFace = function () {
  17127. return _currentActiveCubeFace;
  17128. };
  17129. this.getActiveMipmapLevel = function () {
  17130. return _currentActiveMipmapLevel;
  17131. };
  17132. this.getRenderTarget = function () {
  17133. return _currentRenderTarget;
  17134. };
  17135. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17136. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17137. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17138. const renderTargetProperties = properties.get( renderTarget );
  17139. renderTargetProperties.__hasExternalTextures = true;
  17140. if ( renderTargetProperties.__hasExternalTextures ) {
  17141. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17142. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17143. // The multisample_render_to_texture extension doesn't work properly if there
  17144. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17145. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17146. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17147. renderTargetProperties.__useRenderToTexture = false;
  17148. }
  17149. }
  17150. }
  17151. };
  17152. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17153. const renderTargetProperties = properties.get( renderTarget );
  17154. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17155. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17156. };
  17157. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17158. _currentRenderTarget = renderTarget;
  17159. _currentActiveCubeFace = activeCubeFace;
  17160. _currentActiveMipmapLevel = activeMipmapLevel;
  17161. let useDefaultFramebuffer = true;
  17162. let framebuffer = null;
  17163. let isCube = false;
  17164. let isRenderTarget3D = false;
  17165. if ( renderTarget ) {
  17166. const renderTargetProperties = properties.get( renderTarget );
  17167. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17168. // We need to make sure to rebind the framebuffer.
  17169. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17170. useDefaultFramebuffer = false;
  17171. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17172. textures.setupRenderTarget( renderTarget );
  17173. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17174. // Color and depth texture must be rebound in order for the swapchain to update.
  17175. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17176. }
  17177. const texture = renderTarget.texture;
  17178. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17179. isRenderTarget3D = true;
  17180. }
  17181. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17182. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17183. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17184. isCube = true;
  17185. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17186. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17187. } else {
  17188. framebuffer = __webglFramebuffer;
  17189. }
  17190. _currentViewport.copy( renderTarget.viewport );
  17191. _currentScissor.copy( renderTarget.scissor );
  17192. _currentScissorTest = renderTarget.scissorTest;
  17193. } else {
  17194. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17195. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17196. _currentScissorTest = _scissorTest;
  17197. }
  17198. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17199. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17200. state.drawBuffers( renderTarget, framebuffer );
  17201. }
  17202. state.viewport( _currentViewport );
  17203. state.scissor( _currentScissor );
  17204. state.setScissorTest( _currentScissorTest );
  17205. if ( isCube ) {
  17206. const textureProperties = properties.get( renderTarget.texture );
  17207. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17208. } else if ( isRenderTarget3D ) {
  17209. const textureProperties = properties.get( renderTarget.texture );
  17210. const layer = activeCubeFace || 0;
  17211. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17212. }
  17213. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17214. };
  17215. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17216. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17217. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17218. return;
  17219. }
  17220. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17221. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17222. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17223. }
  17224. if ( framebuffer ) {
  17225. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17226. try {
  17227. const texture = renderTarget.texture;
  17228. const textureFormat = texture.format;
  17229. const textureType = texture.type;
  17230. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17231. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17232. return;
  17233. }
  17234. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17235. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17236. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17237. ! halfFloatSupportedByExt ) {
  17238. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17239. return;
  17240. }
  17241. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17242. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17243. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17244. }
  17245. } finally {
  17246. // restore framebuffer of current render target if necessary
  17247. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17248. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17249. }
  17250. }
  17251. };
  17252. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17253. const levelScale = Math.pow( 2, - level );
  17254. const width = Math.floor( texture.image.width * levelScale );
  17255. const height = Math.floor( texture.image.height * levelScale );
  17256. textures.setTexture2D( texture, 0 );
  17257. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17258. state.unbindTexture();
  17259. };
  17260. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17261. const width = srcTexture.image.width;
  17262. const height = srcTexture.image.height;
  17263. const glFormat = utils.convert( dstTexture.format );
  17264. const glType = utils.convert( dstTexture.type );
  17265. textures.setTexture2D( dstTexture, 0 );
  17266. // As another texture upload may have changed pixelStorei
  17267. // parameters, make sure they are correct for the dstTexture
  17268. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17269. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17270. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17271. if ( srcTexture.isDataTexture ) {
  17272. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17273. } else {
  17274. if ( srcTexture.isCompressedTexture ) {
  17275. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17276. } else {
  17277. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17278. }
  17279. }
  17280. // Generate mipmaps only when copying level 0
  17281. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17282. state.unbindTexture();
  17283. };
  17284. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17285. if ( _this.isWebGL1Renderer ) {
  17286. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17287. return;
  17288. }
  17289. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17290. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17291. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17292. const glFormat = utils.convert( dstTexture.format );
  17293. const glType = utils.convert( dstTexture.type );
  17294. let glTarget;
  17295. if ( dstTexture.isData3DTexture ) {
  17296. textures.setTexture3D( dstTexture, 0 );
  17297. glTarget = _gl.TEXTURE_3D;
  17298. } else if ( dstTexture.isDataArrayTexture ) {
  17299. textures.setTexture2DArray( dstTexture, 0 );
  17300. glTarget = _gl.TEXTURE_2D_ARRAY;
  17301. } else {
  17302. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17303. return;
  17304. }
  17305. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17306. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17307. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17308. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17309. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17310. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17311. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17312. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17313. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17314. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17315. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17316. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17317. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17318. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17319. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17320. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17321. } else {
  17322. if ( srcTexture.isCompressedArrayTexture ) {
  17323. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17324. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17325. } else {
  17326. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17327. }
  17328. }
  17329. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17330. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17331. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17332. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17333. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17334. // Generate mipmaps only when copying level 0
  17335. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17336. state.unbindTexture();
  17337. };
  17338. this.initTexture = function ( texture ) {
  17339. if ( texture.isCubeTexture ) {
  17340. textures.setTextureCube( texture, 0 );
  17341. } else if ( texture.isData3DTexture ) {
  17342. textures.setTexture3D( texture, 0 );
  17343. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17344. textures.setTexture2DArray( texture, 0 );
  17345. } else {
  17346. textures.setTexture2D( texture, 0 );
  17347. }
  17348. state.unbindTexture();
  17349. };
  17350. this.resetState = function () {
  17351. _currentActiveCubeFace = 0;
  17352. _currentActiveMipmapLevel = 0;
  17353. _currentRenderTarget = null;
  17354. state.reset();
  17355. bindingStates.reset();
  17356. };
  17357. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17358. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17359. }
  17360. }
  17361. class WebGL1Renderer extends WebGLRenderer {}
  17362. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17363. class FogExp2 {
  17364. constructor( color, density = 0.00025 ) {
  17365. this.isFogExp2 = true;
  17366. this.name = '';
  17367. this.color = new Color( color );
  17368. this.density = density;
  17369. }
  17370. clone() {
  17371. return new FogExp2( this.color, this.density );
  17372. }
  17373. toJSON( /* meta */ ) {
  17374. return {
  17375. type: 'FogExp2',
  17376. color: this.color.getHex(),
  17377. density: this.density
  17378. };
  17379. }
  17380. }
  17381. class Fog {
  17382. constructor( color, near = 1, far = 1000 ) {
  17383. this.isFog = true;
  17384. this.name = '';
  17385. this.color = new Color( color );
  17386. this.near = near;
  17387. this.far = far;
  17388. }
  17389. clone() {
  17390. return new Fog( this.color, this.near, this.far );
  17391. }
  17392. toJSON( /* meta */ ) {
  17393. return {
  17394. type: 'Fog',
  17395. color: this.color.getHex(),
  17396. near: this.near,
  17397. far: this.far
  17398. };
  17399. }
  17400. }
  17401. class Scene extends Object3D {
  17402. constructor() {
  17403. super();
  17404. this.isScene = true;
  17405. this.type = 'Scene';
  17406. this.background = null;
  17407. this.environment = null;
  17408. this.fog = null;
  17409. this.backgroundBlurriness = 0;
  17410. this.backgroundIntensity = 1;
  17411. this.overrideMaterial = null;
  17412. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17413. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17414. }
  17415. }
  17416. copy( source, recursive ) {
  17417. super.copy( source, recursive );
  17418. if ( source.background !== null ) this.background = source.background.clone();
  17419. if ( source.environment !== null ) this.environment = source.environment.clone();
  17420. if ( source.fog !== null ) this.fog = source.fog.clone();
  17421. this.backgroundBlurriness = source.backgroundBlurriness;
  17422. this.backgroundIntensity = source.backgroundIntensity;
  17423. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17424. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17425. return this;
  17426. }
  17427. toJSON( meta ) {
  17428. const data = super.toJSON( meta );
  17429. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17430. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17431. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17432. return data;
  17433. }
  17434. // @deprecated
  17435. get autoUpdate() {
  17436. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17437. return this.matrixWorldAutoUpdate;
  17438. }
  17439. set autoUpdate( value ) {
  17440. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17441. this.matrixWorldAutoUpdate = value;
  17442. }
  17443. }
  17444. class InterleavedBuffer {
  17445. constructor( array, stride ) {
  17446. this.isInterleavedBuffer = true;
  17447. this.array = array;
  17448. this.stride = stride;
  17449. this.count = array !== undefined ? array.length / stride : 0;
  17450. this.usage = StaticDrawUsage;
  17451. this.updateRange = { offset: 0, count: - 1 };
  17452. this.version = 0;
  17453. this.uuid = generateUUID();
  17454. }
  17455. onUploadCallback() {}
  17456. set needsUpdate( value ) {
  17457. if ( value === true ) this.version ++;
  17458. }
  17459. setUsage( value ) {
  17460. this.usage = value;
  17461. return this;
  17462. }
  17463. copy( source ) {
  17464. this.array = new source.array.constructor( source.array );
  17465. this.count = source.count;
  17466. this.stride = source.stride;
  17467. this.usage = source.usage;
  17468. return this;
  17469. }
  17470. copyAt( index1, attribute, index2 ) {
  17471. index1 *= this.stride;
  17472. index2 *= attribute.stride;
  17473. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17474. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17475. }
  17476. return this;
  17477. }
  17478. set( value, offset = 0 ) {
  17479. this.array.set( value, offset );
  17480. return this;
  17481. }
  17482. clone( data ) {
  17483. if ( data.arrayBuffers === undefined ) {
  17484. data.arrayBuffers = {};
  17485. }
  17486. if ( this.array.buffer._uuid === undefined ) {
  17487. this.array.buffer._uuid = generateUUID();
  17488. }
  17489. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17490. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17491. }
  17492. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17493. const ib = new this.constructor( array, this.stride );
  17494. ib.setUsage( this.usage );
  17495. return ib;
  17496. }
  17497. onUpload( callback ) {
  17498. this.onUploadCallback = callback;
  17499. return this;
  17500. }
  17501. toJSON( data ) {
  17502. if ( data.arrayBuffers === undefined ) {
  17503. data.arrayBuffers = {};
  17504. }
  17505. // generate UUID for array buffer if necessary
  17506. if ( this.array.buffer._uuid === undefined ) {
  17507. this.array.buffer._uuid = generateUUID();
  17508. }
  17509. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17510. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17511. }
  17512. //
  17513. return {
  17514. uuid: this.uuid,
  17515. buffer: this.array.buffer._uuid,
  17516. type: this.array.constructor.name,
  17517. stride: this.stride
  17518. };
  17519. }
  17520. }
  17521. const _vector$6 = /*@__PURE__*/ new Vector3();
  17522. class InterleavedBufferAttribute {
  17523. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17524. this.isInterleavedBufferAttribute = true;
  17525. this.name = '';
  17526. this.data = interleavedBuffer;
  17527. this.itemSize = itemSize;
  17528. this.offset = offset;
  17529. this.normalized = normalized;
  17530. }
  17531. get count() {
  17532. return this.data.count;
  17533. }
  17534. get array() {
  17535. return this.data.array;
  17536. }
  17537. set needsUpdate( value ) {
  17538. this.data.needsUpdate = value;
  17539. }
  17540. applyMatrix4( m ) {
  17541. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17542. _vector$6.fromBufferAttribute( this, i );
  17543. _vector$6.applyMatrix4( m );
  17544. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17545. }
  17546. return this;
  17547. }
  17548. applyNormalMatrix( m ) {
  17549. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17550. _vector$6.fromBufferAttribute( this, i );
  17551. _vector$6.applyNormalMatrix( m );
  17552. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17553. }
  17554. return this;
  17555. }
  17556. transformDirection( m ) {
  17557. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17558. _vector$6.fromBufferAttribute( this, i );
  17559. _vector$6.transformDirection( m );
  17560. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17561. }
  17562. return this;
  17563. }
  17564. setX( index, x ) {
  17565. if ( this.normalized ) x = normalize( x, this.array );
  17566. this.data.array[ index * this.data.stride + this.offset ] = x;
  17567. return this;
  17568. }
  17569. setY( index, y ) {
  17570. if ( this.normalized ) y = normalize( y, this.array );
  17571. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17572. return this;
  17573. }
  17574. setZ( index, z ) {
  17575. if ( this.normalized ) z = normalize( z, this.array );
  17576. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17577. return this;
  17578. }
  17579. setW( index, w ) {
  17580. if ( this.normalized ) w = normalize( w, this.array );
  17581. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17582. return this;
  17583. }
  17584. getX( index ) {
  17585. let x = this.data.array[ index * this.data.stride + this.offset ];
  17586. if ( this.normalized ) x = denormalize( x, this.array );
  17587. return x;
  17588. }
  17589. getY( index ) {
  17590. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17591. if ( this.normalized ) y = denormalize( y, this.array );
  17592. return y;
  17593. }
  17594. getZ( index ) {
  17595. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17596. if ( this.normalized ) z = denormalize( z, this.array );
  17597. return z;
  17598. }
  17599. getW( index ) {
  17600. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17601. if ( this.normalized ) w = denormalize( w, this.array );
  17602. return w;
  17603. }
  17604. setXY( index, x, y ) {
  17605. index = index * this.data.stride + this.offset;
  17606. if ( this.normalized ) {
  17607. x = normalize( x, this.array );
  17608. y = normalize( y, this.array );
  17609. }
  17610. this.data.array[ index + 0 ] = x;
  17611. this.data.array[ index + 1 ] = y;
  17612. return this;
  17613. }
  17614. setXYZ( index, x, y, z ) {
  17615. index = index * this.data.stride + this.offset;
  17616. if ( this.normalized ) {
  17617. x = normalize( x, this.array );
  17618. y = normalize( y, this.array );
  17619. z = normalize( z, this.array );
  17620. }
  17621. this.data.array[ index + 0 ] = x;
  17622. this.data.array[ index + 1 ] = y;
  17623. this.data.array[ index + 2 ] = z;
  17624. return this;
  17625. }
  17626. setXYZW( index, x, y, z, w ) {
  17627. index = index * this.data.stride + this.offset;
  17628. if ( this.normalized ) {
  17629. x = normalize( x, this.array );
  17630. y = normalize( y, this.array );
  17631. z = normalize( z, this.array );
  17632. w = normalize( w, this.array );
  17633. }
  17634. this.data.array[ index + 0 ] = x;
  17635. this.data.array[ index + 1 ] = y;
  17636. this.data.array[ index + 2 ] = z;
  17637. this.data.array[ index + 3 ] = w;
  17638. return this;
  17639. }
  17640. clone( data ) {
  17641. if ( data === undefined ) {
  17642. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17643. const array = [];
  17644. for ( let i = 0; i < this.count; i ++ ) {
  17645. const index = i * this.data.stride + this.offset;
  17646. for ( let j = 0; j < this.itemSize; j ++ ) {
  17647. array.push( this.data.array[ index + j ] );
  17648. }
  17649. }
  17650. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17651. } else {
  17652. if ( data.interleavedBuffers === undefined ) {
  17653. data.interleavedBuffers = {};
  17654. }
  17655. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17656. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17657. }
  17658. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17659. }
  17660. }
  17661. toJSON( data ) {
  17662. if ( data === undefined ) {
  17663. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17664. const array = [];
  17665. for ( let i = 0; i < this.count; i ++ ) {
  17666. const index = i * this.data.stride + this.offset;
  17667. for ( let j = 0; j < this.itemSize; j ++ ) {
  17668. array.push( this.data.array[ index + j ] );
  17669. }
  17670. }
  17671. // de-interleave data and save it as an ordinary buffer attribute for now
  17672. return {
  17673. itemSize: this.itemSize,
  17674. type: this.array.constructor.name,
  17675. array: array,
  17676. normalized: this.normalized
  17677. };
  17678. } else {
  17679. // save as true interleaved attribute
  17680. if ( data.interleavedBuffers === undefined ) {
  17681. data.interleavedBuffers = {};
  17682. }
  17683. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17684. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17685. }
  17686. return {
  17687. isInterleavedBufferAttribute: true,
  17688. itemSize: this.itemSize,
  17689. data: this.data.uuid,
  17690. offset: this.offset,
  17691. normalized: this.normalized
  17692. };
  17693. }
  17694. }
  17695. }
  17696. class SpriteMaterial extends Material {
  17697. constructor( parameters ) {
  17698. super();
  17699. this.isSpriteMaterial = true;
  17700. this.type = 'SpriteMaterial';
  17701. this.color = new Color( 0xffffff );
  17702. this.map = null;
  17703. this.alphaMap = null;
  17704. this.rotation = 0;
  17705. this.sizeAttenuation = true;
  17706. this.transparent = true;
  17707. this.fog = true;
  17708. this.setValues( parameters );
  17709. }
  17710. copy( source ) {
  17711. super.copy( source );
  17712. this.color.copy( source.color );
  17713. this.map = source.map;
  17714. this.alphaMap = source.alphaMap;
  17715. this.rotation = source.rotation;
  17716. this.sizeAttenuation = source.sizeAttenuation;
  17717. this.fog = source.fog;
  17718. return this;
  17719. }
  17720. }
  17721. let _geometry;
  17722. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17723. const _worldScale = /*@__PURE__*/ new Vector3();
  17724. const _mvPosition = /*@__PURE__*/ new Vector3();
  17725. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17726. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17727. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17728. const _vA = /*@__PURE__*/ new Vector3();
  17729. const _vB = /*@__PURE__*/ new Vector3();
  17730. const _vC = /*@__PURE__*/ new Vector3();
  17731. const _uvA = /*@__PURE__*/ new Vector2();
  17732. const _uvB = /*@__PURE__*/ new Vector2();
  17733. const _uvC = /*@__PURE__*/ new Vector2();
  17734. class Sprite extends Object3D {
  17735. constructor( material ) {
  17736. super();
  17737. this.isSprite = true;
  17738. this.type = 'Sprite';
  17739. if ( _geometry === undefined ) {
  17740. _geometry = new BufferGeometry();
  17741. const float32Array = new Float32Array( [
  17742. - 0.5, - 0.5, 0, 0, 0,
  17743. 0.5, - 0.5, 0, 1, 0,
  17744. 0.5, 0.5, 0, 1, 1,
  17745. - 0.5, 0.5, 0, 0, 1
  17746. ] );
  17747. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17748. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17749. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17750. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17751. }
  17752. this.geometry = _geometry;
  17753. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17754. this.center = new Vector2( 0.5, 0.5 );
  17755. }
  17756. raycast( raycaster, intersects ) {
  17757. if ( raycaster.camera === null ) {
  17758. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17759. }
  17760. _worldScale.setFromMatrixScale( this.matrixWorld );
  17761. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17762. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17763. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17764. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17765. _worldScale.multiplyScalar( - _mvPosition.z );
  17766. }
  17767. const rotation = this.material.rotation;
  17768. let sin, cos;
  17769. if ( rotation !== 0 ) {
  17770. cos = Math.cos( rotation );
  17771. sin = Math.sin( rotation );
  17772. }
  17773. const center = this.center;
  17774. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17775. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17776. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17777. _uvA.set( 0, 0 );
  17778. _uvB.set( 1, 0 );
  17779. _uvC.set( 1, 1 );
  17780. // check first triangle
  17781. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17782. if ( intersect === null ) {
  17783. // check second triangle
  17784. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17785. _uvB.set( 0, 1 );
  17786. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17787. if ( intersect === null ) {
  17788. return;
  17789. }
  17790. }
  17791. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17792. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17793. intersects.push( {
  17794. distance: distance,
  17795. point: _intersectPoint.clone(),
  17796. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17797. face: null,
  17798. object: this
  17799. } );
  17800. }
  17801. copy( source, recursive ) {
  17802. super.copy( source, recursive );
  17803. if ( source.center !== undefined ) this.center.copy( source.center );
  17804. this.material = source.material;
  17805. return this;
  17806. }
  17807. }
  17808. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17809. // compute position in camera space
  17810. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17811. // to check if rotation is not zero
  17812. if ( sin !== undefined ) {
  17813. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17814. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17815. } else {
  17816. _rotatedPosition.copy( _alignedPosition );
  17817. }
  17818. vertexPosition.copy( mvPosition );
  17819. vertexPosition.x += _rotatedPosition.x;
  17820. vertexPosition.y += _rotatedPosition.y;
  17821. // transform to world space
  17822. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17823. }
  17824. const _v1$2 = /*@__PURE__*/ new Vector3();
  17825. const _v2$1 = /*@__PURE__*/ new Vector3();
  17826. class LOD extends Object3D {
  17827. constructor() {
  17828. super();
  17829. this._currentLevel = 0;
  17830. this.type = 'LOD';
  17831. Object.defineProperties( this, {
  17832. levels: {
  17833. enumerable: true,
  17834. value: []
  17835. },
  17836. isLOD: {
  17837. value: true,
  17838. }
  17839. } );
  17840. this.autoUpdate = true;
  17841. }
  17842. copy( source ) {
  17843. super.copy( source, false );
  17844. const levels = source.levels;
  17845. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17846. const level = levels[ i ];
  17847. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17848. }
  17849. this.autoUpdate = source.autoUpdate;
  17850. return this;
  17851. }
  17852. addLevel( object, distance = 0, hysteresis = 0 ) {
  17853. distance = Math.abs( distance );
  17854. const levels = this.levels;
  17855. let l;
  17856. for ( l = 0; l < levels.length; l ++ ) {
  17857. if ( distance < levels[ l ].distance ) {
  17858. break;
  17859. }
  17860. }
  17861. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17862. this.add( object );
  17863. return this;
  17864. }
  17865. getCurrentLevel() {
  17866. return this._currentLevel;
  17867. }
  17868. getObjectForDistance( distance ) {
  17869. const levels = this.levels;
  17870. if ( levels.length > 0 ) {
  17871. let i, l;
  17872. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17873. let levelDistance = levels[ i ].distance;
  17874. if ( levels[ i ].object.visible ) {
  17875. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17876. }
  17877. if ( distance < levelDistance ) {
  17878. break;
  17879. }
  17880. }
  17881. return levels[ i - 1 ].object;
  17882. }
  17883. return null;
  17884. }
  17885. raycast( raycaster, intersects ) {
  17886. const levels = this.levels;
  17887. if ( levels.length > 0 ) {
  17888. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17889. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17890. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17891. }
  17892. }
  17893. update( camera ) {
  17894. const levels = this.levels;
  17895. if ( levels.length > 1 ) {
  17896. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17897. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17898. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17899. levels[ 0 ].object.visible = true;
  17900. let i, l;
  17901. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17902. let levelDistance = levels[ i ].distance;
  17903. if ( levels[ i ].object.visible ) {
  17904. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17905. }
  17906. if ( distance >= levelDistance ) {
  17907. levels[ i - 1 ].object.visible = false;
  17908. levels[ i ].object.visible = true;
  17909. } else {
  17910. break;
  17911. }
  17912. }
  17913. this._currentLevel = i - 1;
  17914. for ( ; i < l; i ++ ) {
  17915. levels[ i ].object.visible = false;
  17916. }
  17917. }
  17918. }
  17919. toJSON( meta ) {
  17920. const data = super.toJSON( meta );
  17921. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17922. data.object.levels = [];
  17923. const levels = this.levels;
  17924. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17925. const level = levels[ i ];
  17926. data.object.levels.push( {
  17927. object: level.object.uuid,
  17928. distance: level.distance,
  17929. hysteresis: level.hysteresis
  17930. } );
  17931. }
  17932. return data;
  17933. }
  17934. }
  17935. const _basePosition = /*@__PURE__*/ new Vector3();
  17936. const _skinIndex = /*@__PURE__*/ new Vector4();
  17937. const _skinWeight = /*@__PURE__*/ new Vector4();
  17938. const _vector$5 = /*@__PURE__*/ new Vector3();
  17939. const _matrix = /*@__PURE__*/ new Matrix4();
  17940. class SkinnedMesh extends Mesh {
  17941. constructor( geometry, material ) {
  17942. super( geometry, material );
  17943. this.isSkinnedMesh = true;
  17944. this.type = 'SkinnedMesh';
  17945. this.bindMode = 'attached';
  17946. this.bindMatrix = new Matrix4();
  17947. this.bindMatrixInverse = new Matrix4();
  17948. }
  17949. copy( source, recursive ) {
  17950. super.copy( source, recursive );
  17951. this.bindMode = source.bindMode;
  17952. this.bindMatrix.copy( source.bindMatrix );
  17953. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17954. this.skeleton = source.skeleton;
  17955. return this;
  17956. }
  17957. bind( skeleton, bindMatrix ) {
  17958. this.skeleton = skeleton;
  17959. if ( bindMatrix === undefined ) {
  17960. this.updateMatrixWorld( true );
  17961. this.skeleton.calculateInverses();
  17962. bindMatrix = this.matrixWorld;
  17963. }
  17964. this.bindMatrix.copy( bindMatrix );
  17965. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17966. }
  17967. pose() {
  17968. this.skeleton.pose();
  17969. }
  17970. normalizeSkinWeights() {
  17971. const vector = new Vector4();
  17972. const skinWeight = this.geometry.attributes.skinWeight;
  17973. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17974. vector.fromBufferAttribute( skinWeight, i );
  17975. const scale = 1.0 / vector.manhattanLength();
  17976. if ( scale !== Infinity ) {
  17977. vector.multiplyScalar( scale );
  17978. } else {
  17979. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17980. }
  17981. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17982. }
  17983. }
  17984. updateMatrixWorld( force ) {
  17985. super.updateMatrixWorld( force );
  17986. if ( this.bindMode === 'attached' ) {
  17987. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17988. } else if ( this.bindMode === 'detached' ) {
  17989. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17990. } else {
  17991. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17992. }
  17993. }
  17994. boneTransform( index, target ) {
  17995. const skeleton = this.skeleton;
  17996. const geometry = this.geometry;
  17997. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17998. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17999. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18000. target.set( 0, 0, 0 );
  18001. for ( let i = 0; i < 4; i ++ ) {
  18002. const weight = _skinWeight.getComponent( i );
  18003. if ( weight !== 0 ) {
  18004. const boneIndex = _skinIndex.getComponent( i );
  18005. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18006. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18007. }
  18008. }
  18009. return target.applyMatrix4( this.bindMatrixInverse );
  18010. }
  18011. }
  18012. class Bone extends Object3D {
  18013. constructor() {
  18014. super();
  18015. this.isBone = true;
  18016. this.type = 'Bone';
  18017. }
  18018. }
  18019. class DataTexture extends Texture {
  18020. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18021. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18022. this.isDataTexture = true;
  18023. this.image = { data: data, width: width, height: height };
  18024. this.generateMipmaps = false;
  18025. this.flipY = false;
  18026. this.unpackAlignment = 1;
  18027. }
  18028. }
  18029. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18030. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18031. class Skeleton {
  18032. constructor( bones = [], boneInverses = [] ) {
  18033. this.uuid = generateUUID();
  18034. this.bones = bones.slice( 0 );
  18035. this.boneInverses = boneInverses;
  18036. this.boneMatrices = null;
  18037. this.boneTexture = null;
  18038. this.boneTextureSize = 0;
  18039. this.frame = - 1;
  18040. this.init();
  18041. }
  18042. init() {
  18043. const bones = this.bones;
  18044. const boneInverses = this.boneInverses;
  18045. this.boneMatrices = new Float32Array( bones.length * 16 );
  18046. // calculate inverse bone matrices if necessary
  18047. if ( boneInverses.length === 0 ) {
  18048. this.calculateInverses();
  18049. } else {
  18050. // handle special case
  18051. if ( bones.length !== boneInverses.length ) {
  18052. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18053. this.boneInverses = [];
  18054. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18055. this.boneInverses.push( new Matrix4() );
  18056. }
  18057. }
  18058. }
  18059. }
  18060. calculateInverses() {
  18061. this.boneInverses.length = 0;
  18062. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18063. const inverse = new Matrix4();
  18064. if ( this.bones[ i ] ) {
  18065. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18066. }
  18067. this.boneInverses.push( inverse );
  18068. }
  18069. }
  18070. pose() {
  18071. // recover the bind-time world matrices
  18072. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18073. const bone = this.bones[ i ];
  18074. if ( bone ) {
  18075. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18076. }
  18077. }
  18078. // compute the local matrices, positions, rotations and scales
  18079. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18080. const bone = this.bones[ i ];
  18081. if ( bone ) {
  18082. if ( bone.parent && bone.parent.isBone ) {
  18083. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18084. bone.matrix.multiply( bone.matrixWorld );
  18085. } else {
  18086. bone.matrix.copy( bone.matrixWorld );
  18087. }
  18088. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18089. }
  18090. }
  18091. }
  18092. update() {
  18093. const bones = this.bones;
  18094. const boneInverses = this.boneInverses;
  18095. const boneMatrices = this.boneMatrices;
  18096. const boneTexture = this.boneTexture;
  18097. // flatten bone matrices to array
  18098. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18099. // compute the offset between the current and the original transform
  18100. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18101. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18102. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18103. }
  18104. if ( boneTexture !== null ) {
  18105. boneTexture.needsUpdate = true;
  18106. }
  18107. }
  18108. clone() {
  18109. return new Skeleton( this.bones, this.boneInverses );
  18110. }
  18111. computeBoneTexture() {
  18112. // layout (1 matrix = 4 pixels)
  18113. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18114. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18115. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18116. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18117. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18118. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18119. size = ceilPowerOfTwo( size );
  18120. size = Math.max( size, 4 );
  18121. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18122. boneMatrices.set( this.boneMatrices ); // copy current values
  18123. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18124. boneTexture.needsUpdate = true;
  18125. this.boneMatrices = boneMatrices;
  18126. this.boneTexture = boneTexture;
  18127. this.boneTextureSize = size;
  18128. return this;
  18129. }
  18130. getBoneByName( name ) {
  18131. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18132. const bone = this.bones[ i ];
  18133. if ( bone.name === name ) {
  18134. return bone;
  18135. }
  18136. }
  18137. return undefined;
  18138. }
  18139. dispose( ) {
  18140. if ( this.boneTexture !== null ) {
  18141. this.boneTexture.dispose();
  18142. this.boneTexture = null;
  18143. }
  18144. }
  18145. fromJSON( json, bones ) {
  18146. this.uuid = json.uuid;
  18147. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18148. const uuid = json.bones[ i ];
  18149. let bone = bones[ uuid ];
  18150. if ( bone === undefined ) {
  18151. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18152. bone = new Bone();
  18153. }
  18154. this.bones.push( bone );
  18155. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18156. }
  18157. this.init();
  18158. return this;
  18159. }
  18160. toJSON() {
  18161. const data = {
  18162. metadata: {
  18163. version: 4.5,
  18164. type: 'Skeleton',
  18165. generator: 'Skeleton.toJSON'
  18166. },
  18167. bones: [],
  18168. boneInverses: []
  18169. };
  18170. data.uuid = this.uuid;
  18171. const bones = this.bones;
  18172. const boneInverses = this.boneInverses;
  18173. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18174. const bone = bones[ i ];
  18175. data.bones.push( bone.uuid );
  18176. const boneInverse = boneInverses[ i ];
  18177. data.boneInverses.push( boneInverse.toArray() );
  18178. }
  18179. return data;
  18180. }
  18181. }
  18182. class InstancedBufferAttribute extends BufferAttribute {
  18183. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18184. super( array, itemSize, normalized );
  18185. this.isInstancedBufferAttribute = true;
  18186. this.meshPerAttribute = meshPerAttribute;
  18187. }
  18188. copy( source ) {
  18189. super.copy( source );
  18190. this.meshPerAttribute = source.meshPerAttribute;
  18191. return this;
  18192. }
  18193. toJSON() {
  18194. const data = super.toJSON();
  18195. data.meshPerAttribute = this.meshPerAttribute;
  18196. data.isInstancedBufferAttribute = true;
  18197. return data;
  18198. }
  18199. }
  18200. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18201. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18202. const _instanceIntersects = [];
  18203. const _identity = /*@__PURE__*/ new Matrix4();
  18204. const _mesh = /*@__PURE__*/ new Mesh();
  18205. class InstancedMesh extends Mesh {
  18206. constructor( geometry, material, count ) {
  18207. super( geometry, material );
  18208. this.isInstancedMesh = true;
  18209. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18210. this.instanceColor = null;
  18211. this.count = count;
  18212. this.frustumCulled = false;
  18213. for ( let i = 0; i < count; i ++ ) {
  18214. this.setMatrixAt( i, _identity );
  18215. }
  18216. }
  18217. copy( source, recursive ) {
  18218. super.copy( source, recursive );
  18219. this.instanceMatrix.copy( source.instanceMatrix );
  18220. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18221. this.count = source.count;
  18222. return this;
  18223. }
  18224. getColorAt( index, color ) {
  18225. color.fromArray( this.instanceColor.array, index * 3 );
  18226. }
  18227. getMatrixAt( index, matrix ) {
  18228. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18229. }
  18230. raycast( raycaster, intersects ) {
  18231. const matrixWorld = this.matrixWorld;
  18232. const raycastTimes = this.count;
  18233. _mesh.geometry = this.geometry;
  18234. _mesh.material = this.material;
  18235. if ( _mesh.material === undefined ) return;
  18236. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18237. // calculate the world matrix for each instance
  18238. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18239. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18240. // the mesh represents this single instance
  18241. _mesh.matrixWorld = _instanceWorldMatrix;
  18242. _mesh.raycast( raycaster, _instanceIntersects );
  18243. // process the result of raycast
  18244. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18245. const intersect = _instanceIntersects[ i ];
  18246. intersect.instanceId = instanceId;
  18247. intersect.object = this;
  18248. intersects.push( intersect );
  18249. }
  18250. _instanceIntersects.length = 0;
  18251. }
  18252. }
  18253. setColorAt( index, color ) {
  18254. if ( this.instanceColor === null ) {
  18255. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18256. }
  18257. color.toArray( this.instanceColor.array, index * 3 );
  18258. }
  18259. setMatrixAt( index, matrix ) {
  18260. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18261. }
  18262. updateMorphTargets() {
  18263. }
  18264. dispose() {
  18265. this.dispatchEvent( { type: 'dispose' } );
  18266. }
  18267. }
  18268. class LineBasicMaterial extends Material {
  18269. constructor( parameters ) {
  18270. super();
  18271. this.isLineBasicMaterial = true;
  18272. this.type = 'LineBasicMaterial';
  18273. this.color = new Color( 0xffffff );
  18274. this.linewidth = 1;
  18275. this.linecap = 'round';
  18276. this.linejoin = 'round';
  18277. this.fog = true;
  18278. this.setValues( parameters );
  18279. }
  18280. copy( source ) {
  18281. super.copy( source );
  18282. this.color.copy( source.color );
  18283. this.linewidth = source.linewidth;
  18284. this.linecap = source.linecap;
  18285. this.linejoin = source.linejoin;
  18286. this.fog = source.fog;
  18287. return this;
  18288. }
  18289. }
  18290. const _start$1 = /*@__PURE__*/ new Vector3();
  18291. const _end$1 = /*@__PURE__*/ new Vector3();
  18292. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18293. const _ray$1 = /*@__PURE__*/ new Ray();
  18294. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18295. class Line extends Object3D {
  18296. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18297. super();
  18298. this.isLine = true;
  18299. this.type = 'Line';
  18300. this.geometry = geometry;
  18301. this.material = material;
  18302. this.updateMorphTargets();
  18303. }
  18304. copy( source, recursive ) {
  18305. super.copy( source, recursive );
  18306. this.material = source.material;
  18307. this.geometry = source.geometry;
  18308. return this;
  18309. }
  18310. computeLineDistances() {
  18311. const geometry = this.geometry;
  18312. // we assume non-indexed geometry
  18313. if ( geometry.index === null ) {
  18314. const positionAttribute = geometry.attributes.position;
  18315. const lineDistances = [ 0 ];
  18316. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18317. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18318. _end$1.fromBufferAttribute( positionAttribute, i );
  18319. lineDistances[ i ] = lineDistances[ i - 1 ];
  18320. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18321. }
  18322. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18323. } else {
  18324. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18325. }
  18326. return this;
  18327. }
  18328. raycast( raycaster, intersects ) {
  18329. const geometry = this.geometry;
  18330. const matrixWorld = this.matrixWorld;
  18331. const threshold = raycaster.params.Line.threshold;
  18332. const drawRange = geometry.drawRange;
  18333. // Checking boundingSphere distance to ray
  18334. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18335. _sphere$1.copy( geometry.boundingSphere );
  18336. _sphere$1.applyMatrix4( matrixWorld );
  18337. _sphere$1.radius += threshold;
  18338. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18339. //
  18340. _inverseMatrix$1.copy( matrixWorld ).invert();
  18341. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18342. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18343. const localThresholdSq = localThreshold * localThreshold;
  18344. const vStart = new Vector3();
  18345. const vEnd = new Vector3();
  18346. const interSegment = new Vector3();
  18347. const interRay = new Vector3();
  18348. const step = this.isLineSegments ? 2 : 1;
  18349. const index = geometry.index;
  18350. const attributes = geometry.attributes;
  18351. const positionAttribute = attributes.position;
  18352. if ( index !== null ) {
  18353. const start = Math.max( 0, drawRange.start );
  18354. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18355. for ( let i = start, l = end - 1; i < l; i += step ) {
  18356. const a = index.getX( i );
  18357. const b = index.getX( i + 1 );
  18358. vStart.fromBufferAttribute( positionAttribute, a );
  18359. vEnd.fromBufferAttribute( positionAttribute, b );
  18360. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18361. if ( distSq > localThresholdSq ) continue;
  18362. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18363. const distance = raycaster.ray.origin.distanceTo( interRay );
  18364. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18365. intersects.push( {
  18366. distance: distance,
  18367. // What do we want? intersection point on the ray or on the segment??
  18368. // point: raycaster.ray.at( distance ),
  18369. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18370. index: i,
  18371. face: null,
  18372. faceIndex: null,
  18373. object: this
  18374. } );
  18375. }
  18376. } else {
  18377. const start = Math.max( 0, drawRange.start );
  18378. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18379. for ( let i = start, l = end - 1; i < l; i += step ) {
  18380. vStart.fromBufferAttribute( positionAttribute, i );
  18381. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18382. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18383. if ( distSq > localThresholdSq ) continue;
  18384. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18385. const distance = raycaster.ray.origin.distanceTo( interRay );
  18386. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18387. intersects.push( {
  18388. distance: distance,
  18389. // What do we want? intersection point on the ray or on the segment??
  18390. // point: raycaster.ray.at( distance ),
  18391. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18392. index: i,
  18393. face: null,
  18394. faceIndex: null,
  18395. object: this
  18396. } );
  18397. }
  18398. }
  18399. }
  18400. updateMorphTargets() {
  18401. const geometry = this.geometry;
  18402. const morphAttributes = geometry.morphAttributes;
  18403. const keys = Object.keys( morphAttributes );
  18404. if ( keys.length > 0 ) {
  18405. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18406. if ( morphAttribute !== undefined ) {
  18407. this.morphTargetInfluences = [];
  18408. this.morphTargetDictionary = {};
  18409. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18410. const name = morphAttribute[ m ].name || String( m );
  18411. this.morphTargetInfluences.push( 0 );
  18412. this.morphTargetDictionary[ name ] = m;
  18413. }
  18414. }
  18415. }
  18416. }
  18417. }
  18418. const _start = /*@__PURE__*/ new Vector3();
  18419. const _end = /*@__PURE__*/ new Vector3();
  18420. class LineSegments extends Line {
  18421. constructor( geometry, material ) {
  18422. super( geometry, material );
  18423. this.isLineSegments = true;
  18424. this.type = 'LineSegments';
  18425. }
  18426. computeLineDistances() {
  18427. const geometry = this.geometry;
  18428. // we assume non-indexed geometry
  18429. if ( geometry.index === null ) {
  18430. const positionAttribute = geometry.attributes.position;
  18431. const lineDistances = [];
  18432. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18433. _start.fromBufferAttribute( positionAttribute, i );
  18434. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18435. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18436. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18437. }
  18438. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18439. } else {
  18440. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18441. }
  18442. return this;
  18443. }
  18444. }
  18445. class LineLoop extends Line {
  18446. constructor( geometry, material ) {
  18447. super( geometry, material );
  18448. this.isLineLoop = true;
  18449. this.type = 'LineLoop';
  18450. }
  18451. }
  18452. class PointsMaterial extends Material {
  18453. constructor( parameters ) {
  18454. super();
  18455. this.isPointsMaterial = true;
  18456. this.type = 'PointsMaterial';
  18457. this.color = new Color( 0xffffff );
  18458. this.map = null;
  18459. this.alphaMap = null;
  18460. this.size = 1;
  18461. this.sizeAttenuation = true;
  18462. this.fog = true;
  18463. this.setValues( parameters );
  18464. }
  18465. copy( source ) {
  18466. super.copy( source );
  18467. this.color.copy( source.color );
  18468. this.map = source.map;
  18469. this.alphaMap = source.alphaMap;
  18470. this.size = source.size;
  18471. this.sizeAttenuation = source.sizeAttenuation;
  18472. this.fog = source.fog;
  18473. return this;
  18474. }
  18475. }
  18476. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18477. const _ray = /*@__PURE__*/ new Ray();
  18478. const _sphere = /*@__PURE__*/ new Sphere();
  18479. const _position$2 = /*@__PURE__*/ new Vector3();
  18480. class Points extends Object3D {
  18481. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18482. super();
  18483. this.isPoints = true;
  18484. this.type = 'Points';
  18485. this.geometry = geometry;
  18486. this.material = material;
  18487. this.updateMorphTargets();
  18488. }
  18489. copy( source, recursive ) {
  18490. super.copy( source, recursive );
  18491. this.material = source.material;
  18492. this.geometry = source.geometry;
  18493. return this;
  18494. }
  18495. raycast( raycaster, intersects ) {
  18496. const geometry = this.geometry;
  18497. const matrixWorld = this.matrixWorld;
  18498. const threshold = raycaster.params.Points.threshold;
  18499. const drawRange = geometry.drawRange;
  18500. // Checking boundingSphere distance to ray
  18501. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18502. _sphere.copy( geometry.boundingSphere );
  18503. _sphere.applyMatrix4( matrixWorld );
  18504. _sphere.radius += threshold;
  18505. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18506. //
  18507. _inverseMatrix.copy( matrixWorld ).invert();
  18508. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18509. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18510. const localThresholdSq = localThreshold * localThreshold;
  18511. const index = geometry.index;
  18512. const attributes = geometry.attributes;
  18513. const positionAttribute = attributes.position;
  18514. if ( index !== null ) {
  18515. const start = Math.max( 0, drawRange.start );
  18516. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18517. for ( let i = start, il = end; i < il; i ++ ) {
  18518. const a = index.getX( i );
  18519. _position$2.fromBufferAttribute( positionAttribute, a );
  18520. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18521. }
  18522. } else {
  18523. const start = Math.max( 0, drawRange.start );
  18524. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18525. for ( let i = start, l = end; i < l; i ++ ) {
  18526. _position$2.fromBufferAttribute( positionAttribute, i );
  18527. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18528. }
  18529. }
  18530. }
  18531. updateMorphTargets() {
  18532. const geometry = this.geometry;
  18533. const morphAttributes = geometry.morphAttributes;
  18534. const keys = Object.keys( morphAttributes );
  18535. if ( keys.length > 0 ) {
  18536. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18537. if ( morphAttribute !== undefined ) {
  18538. this.morphTargetInfluences = [];
  18539. this.morphTargetDictionary = {};
  18540. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18541. const name = morphAttribute[ m ].name || String( m );
  18542. this.morphTargetInfluences.push( 0 );
  18543. this.morphTargetDictionary[ name ] = m;
  18544. }
  18545. }
  18546. }
  18547. }
  18548. }
  18549. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18550. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18551. if ( rayPointDistanceSq < localThresholdSq ) {
  18552. const intersectPoint = new Vector3();
  18553. _ray.closestPointToPoint( point, intersectPoint );
  18554. intersectPoint.applyMatrix4( matrixWorld );
  18555. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18556. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18557. intersects.push( {
  18558. distance: distance,
  18559. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18560. point: intersectPoint,
  18561. index: index,
  18562. face: null,
  18563. object: object
  18564. } );
  18565. }
  18566. }
  18567. class VideoTexture extends Texture {
  18568. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18569. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18570. this.isVideoTexture = true;
  18571. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18572. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18573. this.generateMipmaps = false;
  18574. const scope = this;
  18575. function updateVideo() {
  18576. scope.needsUpdate = true;
  18577. video.requestVideoFrameCallback( updateVideo );
  18578. }
  18579. if ( 'requestVideoFrameCallback' in video ) {
  18580. video.requestVideoFrameCallback( updateVideo );
  18581. }
  18582. }
  18583. clone() {
  18584. return new this.constructor( this.image ).copy( this );
  18585. }
  18586. update() {
  18587. const video = this.image;
  18588. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18589. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18590. this.needsUpdate = true;
  18591. }
  18592. }
  18593. }
  18594. class FramebufferTexture extends Texture {
  18595. constructor( width, height, format ) {
  18596. super( { width, height } );
  18597. this.isFramebufferTexture = true;
  18598. this.format = format;
  18599. this.magFilter = NearestFilter;
  18600. this.minFilter = NearestFilter;
  18601. this.generateMipmaps = false;
  18602. this.needsUpdate = true;
  18603. }
  18604. }
  18605. class CompressedTexture extends Texture {
  18606. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18607. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18608. this.isCompressedTexture = true;
  18609. this.image = { width: width, height: height };
  18610. this.mipmaps = mipmaps;
  18611. // no flipping for cube textures
  18612. // (also flipping doesn't work for compressed textures )
  18613. this.flipY = false;
  18614. // can't generate mipmaps for compressed textures
  18615. // mips must be embedded in DDS files
  18616. this.generateMipmaps = false;
  18617. }
  18618. }
  18619. class CompressedArrayTexture extends CompressedTexture {
  18620. constructor( mipmaps, width, height, depth, format, type ) {
  18621. super( mipmaps, width, height, format, type );
  18622. this.isCompressedArrayTexture = true;
  18623. this.image.depth = depth;
  18624. this.wrapR = ClampToEdgeWrapping;
  18625. }
  18626. }
  18627. class CanvasTexture extends Texture {
  18628. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18629. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18630. this.isCanvasTexture = true;
  18631. this.needsUpdate = true;
  18632. }
  18633. }
  18634. /**
  18635. * Extensible curve object.
  18636. *
  18637. * Some common of curve methods:
  18638. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18639. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18640. * .getPoints(), .getSpacedPoints()
  18641. * .getLength()
  18642. * .updateArcLengths()
  18643. *
  18644. * This following curves inherit from THREE.Curve:
  18645. *
  18646. * -- 2D curves --
  18647. * THREE.ArcCurve
  18648. * THREE.CubicBezierCurve
  18649. * THREE.EllipseCurve
  18650. * THREE.LineCurve
  18651. * THREE.QuadraticBezierCurve
  18652. * THREE.SplineCurve
  18653. *
  18654. * -- 3D curves --
  18655. * THREE.CatmullRomCurve3
  18656. * THREE.CubicBezierCurve3
  18657. * THREE.LineCurve3
  18658. * THREE.QuadraticBezierCurve3
  18659. *
  18660. * A series of curves can be represented as a THREE.CurvePath.
  18661. *
  18662. **/
  18663. class Curve {
  18664. constructor() {
  18665. this.type = 'Curve';
  18666. this.arcLengthDivisions = 200;
  18667. }
  18668. // Virtual base class method to overwrite and implement in subclasses
  18669. // - t [0 .. 1]
  18670. getPoint( /* t, optionalTarget */ ) {
  18671. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18672. return null;
  18673. }
  18674. // Get point at relative position in curve according to arc length
  18675. // - u [0 .. 1]
  18676. getPointAt( u, optionalTarget ) {
  18677. const t = this.getUtoTmapping( u );
  18678. return this.getPoint( t, optionalTarget );
  18679. }
  18680. // Get sequence of points using getPoint( t )
  18681. getPoints( divisions = 5 ) {
  18682. const points = [];
  18683. for ( let d = 0; d <= divisions; d ++ ) {
  18684. points.push( this.getPoint( d / divisions ) );
  18685. }
  18686. return points;
  18687. }
  18688. // Get sequence of points using getPointAt( u )
  18689. getSpacedPoints( divisions = 5 ) {
  18690. const points = [];
  18691. for ( let d = 0; d <= divisions; d ++ ) {
  18692. points.push( this.getPointAt( d / divisions ) );
  18693. }
  18694. return points;
  18695. }
  18696. // Get total curve arc length
  18697. getLength() {
  18698. const lengths = this.getLengths();
  18699. return lengths[ lengths.length - 1 ];
  18700. }
  18701. // Get list of cumulative segment lengths
  18702. getLengths( divisions = this.arcLengthDivisions ) {
  18703. if ( this.cacheArcLengths &&
  18704. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18705. ! this.needsUpdate ) {
  18706. return this.cacheArcLengths;
  18707. }
  18708. this.needsUpdate = false;
  18709. const cache = [];
  18710. let current, last = this.getPoint( 0 );
  18711. let sum = 0;
  18712. cache.push( 0 );
  18713. for ( let p = 1; p <= divisions; p ++ ) {
  18714. current = this.getPoint( p / divisions );
  18715. sum += current.distanceTo( last );
  18716. cache.push( sum );
  18717. last = current;
  18718. }
  18719. this.cacheArcLengths = cache;
  18720. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18721. }
  18722. updateArcLengths() {
  18723. this.needsUpdate = true;
  18724. this.getLengths();
  18725. }
  18726. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18727. getUtoTmapping( u, distance ) {
  18728. const arcLengths = this.getLengths();
  18729. let i = 0;
  18730. const il = arcLengths.length;
  18731. let targetArcLength; // The targeted u distance value to get
  18732. if ( distance ) {
  18733. targetArcLength = distance;
  18734. } else {
  18735. targetArcLength = u * arcLengths[ il - 1 ];
  18736. }
  18737. // binary search for the index with largest value smaller than target u distance
  18738. let low = 0, high = il - 1, comparison;
  18739. while ( low <= high ) {
  18740. 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
  18741. comparison = arcLengths[ i ] - targetArcLength;
  18742. if ( comparison < 0 ) {
  18743. low = i + 1;
  18744. } else if ( comparison > 0 ) {
  18745. high = i - 1;
  18746. } else {
  18747. high = i;
  18748. break;
  18749. // DONE
  18750. }
  18751. }
  18752. i = high;
  18753. if ( arcLengths[ i ] === targetArcLength ) {
  18754. return i / ( il - 1 );
  18755. }
  18756. // we could get finer grain at lengths, or use simple interpolation between two points
  18757. const lengthBefore = arcLengths[ i ];
  18758. const lengthAfter = arcLengths[ i + 1 ];
  18759. const segmentLength = lengthAfter - lengthBefore;
  18760. // determine where we are between the 'before' and 'after' points
  18761. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18762. // add that fractional amount to t
  18763. const t = ( i + segmentFraction ) / ( il - 1 );
  18764. return t;
  18765. }
  18766. // Returns a unit vector tangent at t
  18767. // In case any sub curve does not implement its tangent derivation,
  18768. // 2 points a small delta apart will be used to find its gradient
  18769. // which seems to give a reasonable approximation
  18770. getTangent( t, optionalTarget ) {
  18771. const delta = 0.0001;
  18772. let t1 = t - delta;
  18773. let t2 = t + delta;
  18774. // Capping in case of danger
  18775. if ( t1 < 0 ) t1 = 0;
  18776. if ( t2 > 1 ) t2 = 1;
  18777. const pt1 = this.getPoint( t1 );
  18778. const pt2 = this.getPoint( t2 );
  18779. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18780. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18781. return tangent;
  18782. }
  18783. getTangentAt( u, optionalTarget ) {
  18784. const t = this.getUtoTmapping( u );
  18785. return this.getTangent( t, optionalTarget );
  18786. }
  18787. computeFrenetFrames( segments, closed ) {
  18788. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18789. const normal = new Vector3();
  18790. const tangents = [];
  18791. const normals = [];
  18792. const binormals = [];
  18793. const vec = new Vector3();
  18794. const mat = new Matrix4();
  18795. // compute the tangent vectors for each segment on the curve
  18796. for ( let i = 0; i <= segments; i ++ ) {
  18797. const u = i / segments;
  18798. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18799. }
  18800. // select an initial normal vector perpendicular to the first tangent vector,
  18801. // and in the direction of the minimum tangent xyz component
  18802. normals[ 0 ] = new Vector3();
  18803. binormals[ 0 ] = new Vector3();
  18804. let min = Number.MAX_VALUE;
  18805. const tx = Math.abs( tangents[ 0 ].x );
  18806. const ty = Math.abs( tangents[ 0 ].y );
  18807. const tz = Math.abs( tangents[ 0 ].z );
  18808. if ( tx <= min ) {
  18809. min = tx;
  18810. normal.set( 1, 0, 0 );
  18811. }
  18812. if ( ty <= min ) {
  18813. min = ty;
  18814. normal.set( 0, 1, 0 );
  18815. }
  18816. if ( tz <= min ) {
  18817. normal.set( 0, 0, 1 );
  18818. }
  18819. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18820. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18821. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18822. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18823. for ( let i = 1; i <= segments; i ++ ) {
  18824. normals[ i ] = normals[ i - 1 ].clone();
  18825. binormals[ i ] = binormals[ i - 1 ].clone();
  18826. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18827. if ( vec.length() > Number.EPSILON ) {
  18828. vec.normalize();
  18829. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18830. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18831. }
  18832. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18833. }
  18834. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18835. if ( closed === true ) {
  18836. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18837. theta /= segments;
  18838. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18839. theta = - theta;
  18840. }
  18841. for ( let i = 1; i <= segments; i ++ ) {
  18842. // twist a little...
  18843. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18844. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18845. }
  18846. }
  18847. return {
  18848. tangents: tangents,
  18849. normals: normals,
  18850. binormals: binormals
  18851. };
  18852. }
  18853. clone() {
  18854. return new this.constructor().copy( this );
  18855. }
  18856. copy( source ) {
  18857. this.arcLengthDivisions = source.arcLengthDivisions;
  18858. return this;
  18859. }
  18860. toJSON() {
  18861. const data = {
  18862. metadata: {
  18863. version: 4.5,
  18864. type: 'Curve',
  18865. generator: 'Curve.toJSON'
  18866. }
  18867. };
  18868. data.arcLengthDivisions = this.arcLengthDivisions;
  18869. data.type = this.type;
  18870. return data;
  18871. }
  18872. fromJSON( json ) {
  18873. this.arcLengthDivisions = json.arcLengthDivisions;
  18874. return this;
  18875. }
  18876. }
  18877. class EllipseCurve extends Curve {
  18878. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18879. super();
  18880. this.isEllipseCurve = true;
  18881. this.type = 'EllipseCurve';
  18882. this.aX = aX;
  18883. this.aY = aY;
  18884. this.xRadius = xRadius;
  18885. this.yRadius = yRadius;
  18886. this.aStartAngle = aStartAngle;
  18887. this.aEndAngle = aEndAngle;
  18888. this.aClockwise = aClockwise;
  18889. this.aRotation = aRotation;
  18890. }
  18891. getPoint( t, optionalTarget ) {
  18892. const point = optionalTarget || new Vector2();
  18893. const twoPi = Math.PI * 2;
  18894. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18895. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18896. // ensures that deltaAngle is 0 .. 2 PI
  18897. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18898. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18899. if ( deltaAngle < Number.EPSILON ) {
  18900. if ( samePoints ) {
  18901. deltaAngle = 0;
  18902. } else {
  18903. deltaAngle = twoPi;
  18904. }
  18905. }
  18906. if ( this.aClockwise === true && ! samePoints ) {
  18907. if ( deltaAngle === twoPi ) {
  18908. deltaAngle = - twoPi;
  18909. } else {
  18910. deltaAngle = deltaAngle - twoPi;
  18911. }
  18912. }
  18913. const angle = this.aStartAngle + t * deltaAngle;
  18914. let x = this.aX + this.xRadius * Math.cos( angle );
  18915. let y = this.aY + this.yRadius * Math.sin( angle );
  18916. if ( this.aRotation !== 0 ) {
  18917. const cos = Math.cos( this.aRotation );
  18918. const sin = Math.sin( this.aRotation );
  18919. const tx = x - this.aX;
  18920. const ty = y - this.aY;
  18921. // Rotate the point about the center of the ellipse.
  18922. x = tx * cos - ty * sin + this.aX;
  18923. y = tx * sin + ty * cos + this.aY;
  18924. }
  18925. return point.set( x, y );
  18926. }
  18927. copy( source ) {
  18928. super.copy( source );
  18929. this.aX = source.aX;
  18930. this.aY = source.aY;
  18931. this.xRadius = source.xRadius;
  18932. this.yRadius = source.yRadius;
  18933. this.aStartAngle = source.aStartAngle;
  18934. this.aEndAngle = source.aEndAngle;
  18935. this.aClockwise = source.aClockwise;
  18936. this.aRotation = source.aRotation;
  18937. return this;
  18938. }
  18939. toJSON() {
  18940. const data = super.toJSON();
  18941. data.aX = this.aX;
  18942. data.aY = this.aY;
  18943. data.xRadius = this.xRadius;
  18944. data.yRadius = this.yRadius;
  18945. data.aStartAngle = this.aStartAngle;
  18946. data.aEndAngle = this.aEndAngle;
  18947. data.aClockwise = this.aClockwise;
  18948. data.aRotation = this.aRotation;
  18949. return data;
  18950. }
  18951. fromJSON( json ) {
  18952. super.fromJSON( json );
  18953. this.aX = json.aX;
  18954. this.aY = json.aY;
  18955. this.xRadius = json.xRadius;
  18956. this.yRadius = json.yRadius;
  18957. this.aStartAngle = json.aStartAngle;
  18958. this.aEndAngle = json.aEndAngle;
  18959. this.aClockwise = json.aClockwise;
  18960. this.aRotation = json.aRotation;
  18961. return this;
  18962. }
  18963. }
  18964. class ArcCurve extends EllipseCurve {
  18965. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18966. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18967. this.isArcCurve = true;
  18968. this.type = 'ArcCurve';
  18969. }
  18970. }
  18971. /**
  18972. * Centripetal CatmullRom Curve - which is useful for avoiding
  18973. * cusps and self-intersections in non-uniform catmull rom curves.
  18974. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18975. *
  18976. * curve.type accepts centripetal(default), chordal and catmullrom
  18977. * curve.tension is used for catmullrom which defaults to 0.5
  18978. */
  18979. /*
  18980. Based on an optimized c++ solution in
  18981. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18982. - http://ideone.com/NoEbVM
  18983. This CubicPoly class could be used for reusing some variables and calculations,
  18984. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18985. which can be placed in CurveUtils.
  18986. */
  18987. function CubicPoly() {
  18988. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18989. /*
  18990. * Compute coefficients for a cubic polynomial
  18991. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18992. * such that
  18993. * p(0) = x0, p(1) = x1
  18994. * and
  18995. * p'(0) = t0, p'(1) = t1.
  18996. */
  18997. function init( x0, x1, t0, t1 ) {
  18998. c0 = x0;
  18999. c1 = t0;
  19000. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19001. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19002. }
  19003. return {
  19004. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19005. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19006. },
  19007. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19008. // compute tangents when parameterized in [t1,t2]
  19009. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19010. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19011. // rescale tangents for parametrization in [0,1]
  19012. t1 *= dt1;
  19013. t2 *= dt1;
  19014. init( x1, x2, t1, t2 );
  19015. },
  19016. calc: function ( t ) {
  19017. const t2 = t * t;
  19018. const t3 = t2 * t;
  19019. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19020. }
  19021. };
  19022. }
  19023. //
  19024. const tmp = /*@__PURE__*/ new Vector3();
  19025. const px = /*@__PURE__*/ new CubicPoly();
  19026. const py = /*@__PURE__*/ new CubicPoly();
  19027. const pz = /*@__PURE__*/ new CubicPoly();
  19028. class CatmullRomCurve3 extends Curve {
  19029. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19030. super();
  19031. this.isCatmullRomCurve3 = true;
  19032. this.type = 'CatmullRomCurve3';
  19033. this.points = points;
  19034. this.closed = closed;
  19035. this.curveType = curveType;
  19036. this.tension = tension;
  19037. }
  19038. getPoint( t, optionalTarget = new Vector3() ) {
  19039. const point = optionalTarget;
  19040. const points = this.points;
  19041. const l = points.length;
  19042. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19043. let intPoint = Math.floor( p );
  19044. let weight = p - intPoint;
  19045. if ( this.closed ) {
  19046. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19047. } else if ( weight === 0 && intPoint === l - 1 ) {
  19048. intPoint = l - 2;
  19049. weight = 1;
  19050. }
  19051. let p0, p3; // 4 points (p1 & p2 defined below)
  19052. if ( this.closed || intPoint > 0 ) {
  19053. p0 = points[ ( intPoint - 1 ) % l ];
  19054. } else {
  19055. // extrapolate first point
  19056. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19057. p0 = tmp;
  19058. }
  19059. const p1 = points[ intPoint % l ];
  19060. const p2 = points[ ( intPoint + 1 ) % l ];
  19061. if ( this.closed || intPoint + 2 < l ) {
  19062. p3 = points[ ( intPoint + 2 ) % l ];
  19063. } else {
  19064. // extrapolate last point
  19065. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19066. p3 = tmp;
  19067. }
  19068. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19069. // init Centripetal / Chordal Catmull-Rom
  19070. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19071. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19072. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19073. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19074. // safety check for repeated points
  19075. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19076. if ( dt0 < 1e-4 ) dt0 = dt1;
  19077. if ( dt2 < 1e-4 ) dt2 = dt1;
  19078. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19079. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19080. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19081. } else if ( this.curveType === 'catmullrom' ) {
  19082. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19083. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19084. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19085. }
  19086. point.set(
  19087. px.calc( weight ),
  19088. py.calc( weight ),
  19089. pz.calc( weight )
  19090. );
  19091. return point;
  19092. }
  19093. copy( source ) {
  19094. super.copy( source );
  19095. this.points = [];
  19096. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19097. const point = source.points[ i ];
  19098. this.points.push( point.clone() );
  19099. }
  19100. this.closed = source.closed;
  19101. this.curveType = source.curveType;
  19102. this.tension = source.tension;
  19103. return this;
  19104. }
  19105. toJSON() {
  19106. const data = super.toJSON();
  19107. data.points = [];
  19108. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19109. const point = this.points[ i ];
  19110. data.points.push( point.toArray() );
  19111. }
  19112. data.closed = this.closed;
  19113. data.curveType = this.curveType;
  19114. data.tension = this.tension;
  19115. return data;
  19116. }
  19117. fromJSON( json ) {
  19118. super.fromJSON( json );
  19119. this.points = [];
  19120. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19121. const point = json.points[ i ];
  19122. this.points.push( new Vector3().fromArray( point ) );
  19123. }
  19124. this.closed = json.closed;
  19125. this.curveType = json.curveType;
  19126. this.tension = json.tension;
  19127. return this;
  19128. }
  19129. }
  19130. /**
  19131. * Bezier Curves formulas obtained from
  19132. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19133. */
  19134. function CatmullRom( t, p0, p1, p2, p3 ) {
  19135. const v0 = ( p2 - p0 ) * 0.5;
  19136. const v1 = ( p3 - p1 ) * 0.5;
  19137. const t2 = t * t;
  19138. const t3 = t * t2;
  19139. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19140. }
  19141. //
  19142. function QuadraticBezierP0( t, p ) {
  19143. const k = 1 - t;
  19144. return k * k * p;
  19145. }
  19146. function QuadraticBezierP1( t, p ) {
  19147. return 2 * ( 1 - t ) * t * p;
  19148. }
  19149. function QuadraticBezierP2( t, p ) {
  19150. return t * t * p;
  19151. }
  19152. function QuadraticBezier( t, p0, p1, p2 ) {
  19153. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19154. QuadraticBezierP2( t, p2 );
  19155. }
  19156. //
  19157. function CubicBezierP0( t, p ) {
  19158. const k = 1 - t;
  19159. return k * k * k * p;
  19160. }
  19161. function CubicBezierP1( t, p ) {
  19162. const k = 1 - t;
  19163. return 3 * k * k * t * p;
  19164. }
  19165. function CubicBezierP2( t, p ) {
  19166. return 3 * ( 1 - t ) * t * t * p;
  19167. }
  19168. function CubicBezierP3( t, p ) {
  19169. return t * t * t * p;
  19170. }
  19171. function CubicBezier( t, p0, p1, p2, p3 ) {
  19172. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19173. CubicBezierP3( t, p3 );
  19174. }
  19175. class CubicBezierCurve extends Curve {
  19176. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19177. super();
  19178. this.isCubicBezierCurve = true;
  19179. this.type = 'CubicBezierCurve';
  19180. this.v0 = v0;
  19181. this.v1 = v1;
  19182. this.v2 = v2;
  19183. this.v3 = v3;
  19184. }
  19185. getPoint( t, optionalTarget = new Vector2() ) {
  19186. const point = optionalTarget;
  19187. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19188. point.set(
  19189. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19190. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19191. );
  19192. return point;
  19193. }
  19194. copy( source ) {
  19195. super.copy( source );
  19196. this.v0.copy( source.v0 );
  19197. this.v1.copy( source.v1 );
  19198. this.v2.copy( source.v2 );
  19199. this.v3.copy( source.v3 );
  19200. return this;
  19201. }
  19202. toJSON() {
  19203. const data = super.toJSON();
  19204. data.v0 = this.v0.toArray();
  19205. data.v1 = this.v1.toArray();
  19206. data.v2 = this.v2.toArray();
  19207. data.v3 = this.v3.toArray();
  19208. return data;
  19209. }
  19210. fromJSON( json ) {
  19211. super.fromJSON( json );
  19212. this.v0.fromArray( json.v0 );
  19213. this.v1.fromArray( json.v1 );
  19214. this.v2.fromArray( json.v2 );
  19215. this.v3.fromArray( json.v3 );
  19216. return this;
  19217. }
  19218. }
  19219. class CubicBezierCurve3 extends Curve {
  19220. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19221. super();
  19222. this.isCubicBezierCurve3 = true;
  19223. this.type = 'CubicBezierCurve3';
  19224. this.v0 = v0;
  19225. this.v1 = v1;
  19226. this.v2 = v2;
  19227. this.v3 = v3;
  19228. }
  19229. getPoint( t, optionalTarget = new Vector3() ) {
  19230. const point = optionalTarget;
  19231. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19232. point.set(
  19233. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19234. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19235. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19236. );
  19237. return point;
  19238. }
  19239. copy( source ) {
  19240. super.copy( source );
  19241. this.v0.copy( source.v0 );
  19242. this.v1.copy( source.v1 );
  19243. this.v2.copy( source.v2 );
  19244. this.v3.copy( source.v3 );
  19245. return this;
  19246. }
  19247. toJSON() {
  19248. const data = super.toJSON();
  19249. data.v0 = this.v0.toArray();
  19250. data.v1 = this.v1.toArray();
  19251. data.v2 = this.v2.toArray();
  19252. data.v3 = this.v3.toArray();
  19253. return data;
  19254. }
  19255. fromJSON( json ) {
  19256. super.fromJSON( json );
  19257. this.v0.fromArray( json.v0 );
  19258. this.v1.fromArray( json.v1 );
  19259. this.v2.fromArray( json.v2 );
  19260. this.v3.fromArray( json.v3 );
  19261. return this;
  19262. }
  19263. }
  19264. class LineCurve extends Curve {
  19265. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19266. super();
  19267. this.isLineCurve = true;
  19268. this.type = 'LineCurve';
  19269. this.v1 = v1;
  19270. this.v2 = v2;
  19271. }
  19272. getPoint( t, optionalTarget = new Vector2() ) {
  19273. const point = optionalTarget;
  19274. if ( t === 1 ) {
  19275. point.copy( this.v2 );
  19276. } else {
  19277. point.copy( this.v2 ).sub( this.v1 );
  19278. point.multiplyScalar( t ).add( this.v1 );
  19279. }
  19280. return point;
  19281. }
  19282. // Line curve is linear, so we can overwrite default getPointAt
  19283. getPointAt( u, optionalTarget ) {
  19284. return this.getPoint( u, optionalTarget );
  19285. }
  19286. getTangent( t, optionalTarget ) {
  19287. const tangent = optionalTarget || new Vector2();
  19288. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19289. return tangent;
  19290. }
  19291. copy( source ) {
  19292. super.copy( source );
  19293. this.v1.copy( source.v1 );
  19294. this.v2.copy( source.v2 );
  19295. return this;
  19296. }
  19297. toJSON() {
  19298. const data = super.toJSON();
  19299. data.v1 = this.v1.toArray();
  19300. data.v2 = this.v2.toArray();
  19301. return data;
  19302. }
  19303. fromJSON( json ) {
  19304. super.fromJSON( json );
  19305. this.v1.fromArray( json.v1 );
  19306. this.v2.fromArray( json.v2 );
  19307. return this;
  19308. }
  19309. }
  19310. class LineCurve3 extends Curve {
  19311. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19312. super();
  19313. this.isLineCurve3 = true;
  19314. this.type = 'LineCurve3';
  19315. this.v1 = v1;
  19316. this.v2 = v2;
  19317. }
  19318. getPoint( t, optionalTarget = new Vector3() ) {
  19319. const point = optionalTarget;
  19320. if ( t === 1 ) {
  19321. point.copy( this.v2 );
  19322. } else {
  19323. point.copy( this.v2 ).sub( this.v1 );
  19324. point.multiplyScalar( t ).add( this.v1 );
  19325. }
  19326. return point;
  19327. }
  19328. // Line curve is linear, so we can overwrite default getPointAt
  19329. getPointAt( u, optionalTarget ) {
  19330. return this.getPoint( u, optionalTarget );
  19331. }
  19332. copy( source ) {
  19333. super.copy( source );
  19334. this.v1.copy( source.v1 );
  19335. this.v2.copy( source.v2 );
  19336. return this;
  19337. }
  19338. toJSON() {
  19339. const data = super.toJSON();
  19340. data.v1 = this.v1.toArray();
  19341. data.v2 = this.v2.toArray();
  19342. return data;
  19343. }
  19344. fromJSON( json ) {
  19345. super.fromJSON( json );
  19346. this.v1.fromArray( json.v1 );
  19347. this.v2.fromArray( json.v2 );
  19348. return this;
  19349. }
  19350. }
  19351. class QuadraticBezierCurve extends Curve {
  19352. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19353. super();
  19354. this.isQuadraticBezierCurve = true;
  19355. this.type = 'QuadraticBezierCurve';
  19356. this.v0 = v0;
  19357. this.v1 = v1;
  19358. this.v2 = v2;
  19359. }
  19360. getPoint( t, optionalTarget = new Vector2() ) {
  19361. const point = optionalTarget;
  19362. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19363. point.set(
  19364. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19365. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19366. );
  19367. return point;
  19368. }
  19369. copy( source ) {
  19370. super.copy( source );
  19371. this.v0.copy( source.v0 );
  19372. this.v1.copy( source.v1 );
  19373. this.v2.copy( source.v2 );
  19374. return this;
  19375. }
  19376. toJSON() {
  19377. const data = super.toJSON();
  19378. data.v0 = this.v0.toArray();
  19379. data.v1 = this.v1.toArray();
  19380. data.v2 = this.v2.toArray();
  19381. return data;
  19382. }
  19383. fromJSON( json ) {
  19384. super.fromJSON( json );
  19385. this.v0.fromArray( json.v0 );
  19386. this.v1.fromArray( json.v1 );
  19387. this.v2.fromArray( json.v2 );
  19388. return this;
  19389. }
  19390. }
  19391. class QuadraticBezierCurve3 extends Curve {
  19392. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19393. super();
  19394. this.isQuadraticBezierCurve3 = true;
  19395. this.type = 'QuadraticBezierCurve3';
  19396. this.v0 = v0;
  19397. this.v1 = v1;
  19398. this.v2 = v2;
  19399. }
  19400. getPoint( t, optionalTarget = new Vector3() ) {
  19401. const point = optionalTarget;
  19402. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19403. point.set(
  19404. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19405. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19406. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19407. );
  19408. return point;
  19409. }
  19410. copy( source ) {
  19411. super.copy( source );
  19412. this.v0.copy( source.v0 );
  19413. this.v1.copy( source.v1 );
  19414. this.v2.copy( source.v2 );
  19415. return this;
  19416. }
  19417. toJSON() {
  19418. const data = super.toJSON();
  19419. data.v0 = this.v0.toArray();
  19420. data.v1 = this.v1.toArray();
  19421. data.v2 = this.v2.toArray();
  19422. return data;
  19423. }
  19424. fromJSON( json ) {
  19425. super.fromJSON( json );
  19426. this.v0.fromArray( json.v0 );
  19427. this.v1.fromArray( json.v1 );
  19428. this.v2.fromArray( json.v2 );
  19429. return this;
  19430. }
  19431. }
  19432. class SplineCurve extends Curve {
  19433. constructor( points = [] ) {
  19434. super();
  19435. this.isSplineCurve = true;
  19436. this.type = 'SplineCurve';
  19437. this.points = points;
  19438. }
  19439. getPoint( t, optionalTarget = new Vector2() ) {
  19440. const point = optionalTarget;
  19441. const points = this.points;
  19442. const p = ( points.length - 1 ) * t;
  19443. const intPoint = Math.floor( p );
  19444. const weight = p - intPoint;
  19445. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19446. const p1 = points[ intPoint ];
  19447. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19448. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19449. point.set(
  19450. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19451. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19452. );
  19453. return point;
  19454. }
  19455. copy( source ) {
  19456. super.copy( source );
  19457. this.points = [];
  19458. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19459. const point = source.points[ i ];
  19460. this.points.push( point.clone() );
  19461. }
  19462. return this;
  19463. }
  19464. toJSON() {
  19465. const data = super.toJSON();
  19466. data.points = [];
  19467. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19468. const point = this.points[ i ];
  19469. data.points.push( point.toArray() );
  19470. }
  19471. return data;
  19472. }
  19473. fromJSON( json ) {
  19474. super.fromJSON( json );
  19475. this.points = [];
  19476. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19477. const point = json.points[ i ];
  19478. this.points.push( new Vector2().fromArray( point ) );
  19479. }
  19480. return this;
  19481. }
  19482. }
  19483. var Curves = /*#__PURE__*/Object.freeze({
  19484. __proto__: null,
  19485. ArcCurve: ArcCurve,
  19486. CatmullRomCurve3: CatmullRomCurve3,
  19487. CubicBezierCurve: CubicBezierCurve,
  19488. CubicBezierCurve3: CubicBezierCurve3,
  19489. EllipseCurve: EllipseCurve,
  19490. LineCurve: LineCurve,
  19491. LineCurve3: LineCurve3,
  19492. QuadraticBezierCurve: QuadraticBezierCurve,
  19493. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19494. SplineCurve: SplineCurve
  19495. });
  19496. /**************************************************************
  19497. * Curved Path - a curve path is simply a array of connected
  19498. * curves, but retains the api of a curve
  19499. **************************************************************/
  19500. class CurvePath extends Curve {
  19501. constructor() {
  19502. super();
  19503. this.type = 'CurvePath';
  19504. this.curves = [];
  19505. this.autoClose = false; // Automatically closes the path
  19506. }
  19507. add( curve ) {
  19508. this.curves.push( curve );
  19509. }
  19510. closePath() {
  19511. // Add a line curve if start and end of lines are not connected
  19512. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19513. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19514. if ( ! startPoint.equals( endPoint ) ) {
  19515. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19516. }
  19517. }
  19518. // To get accurate point with reference to
  19519. // entire path distance at time t,
  19520. // following has to be done:
  19521. // 1. Length of each sub path have to be known
  19522. // 2. Locate and identify type of curve
  19523. // 3. Get t for the curve
  19524. // 4. Return curve.getPointAt(t')
  19525. getPoint( t, optionalTarget ) {
  19526. const d = t * this.getLength();
  19527. const curveLengths = this.getCurveLengths();
  19528. let i = 0;
  19529. // To think about boundaries points.
  19530. while ( i < curveLengths.length ) {
  19531. if ( curveLengths[ i ] >= d ) {
  19532. const diff = curveLengths[ i ] - d;
  19533. const curve = this.curves[ i ];
  19534. const segmentLength = curve.getLength();
  19535. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19536. return curve.getPointAt( u, optionalTarget );
  19537. }
  19538. i ++;
  19539. }
  19540. return null;
  19541. // loop where sum != 0, sum > d , sum+1 <d
  19542. }
  19543. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19544. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19545. // getPoint() depends on getLength
  19546. getLength() {
  19547. const lens = this.getCurveLengths();
  19548. return lens[ lens.length - 1 ];
  19549. }
  19550. // cacheLengths must be recalculated.
  19551. updateArcLengths() {
  19552. this.needsUpdate = true;
  19553. this.cacheLengths = null;
  19554. this.getCurveLengths();
  19555. }
  19556. // Compute lengths and cache them
  19557. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19558. getCurveLengths() {
  19559. // We use cache values if curves and cache array are same length
  19560. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19561. return this.cacheLengths;
  19562. }
  19563. // Get length of sub-curve
  19564. // Push sums into cached array
  19565. const lengths = [];
  19566. let sums = 0;
  19567. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19568. sums += this.curves[ i ].getLength();
  19569. lengths.push( sums );
  19570. }
  19571. this.cacheLengths = lengths;
  19572. return lengths;
  19573. }
  19574. getSpacedPoints( divisions = 40 ) {
  19575. const points = [];
  19576. for ( let i = 0; i <= divisions; i ++ ) {
  19577. points.push( this.getPoint( i / divisions ) );
  19578. }
  19579. if ( this.autoClose ) {
  19580. points.push( points[ 0 ] );
  19581. }
  19582. return points;
  19583. }
  19584. getPoints( divisions = 12 ) {
  19585. const points = [];
  19586. let last;
  19587. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19588. const curve = curves[ i ];
  19589. const resolution = curve.isEllipseCurve ? divisions * 2
  19590. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19591. : curve.isSplineCurve ? divisions * curve.points.length
  19592. : divisions;
  19593. const pts = curve.getPoints( resolution );
  19594. for ( let j = 0; j < pts.length; j ++ ) {
  19595. const point = pts[ j ];
  19596. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19597. points.push( point );
  19598. last = point;
  19599. }
  19600. }
  19601. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19602. points.push( points[ 0 ] );
  19603. }
  19604. return points;
  19605. }
  19606. copy( source ) {
  19607. super.copy( source );
  19608. this.curves = [];
  19609. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19610. const curve = source.curves[ i ];
  19611. this.curves.push( curve.clone() );
  19612. }
  19613. this.autoClose = source.autoClose;
  19614. return this;
  19615. }
  19616. toJSON() {
  19617. const data = super.toJSON();
  19618. data.autoClose = this.autoClose;
  19619. data.curves = [];
  19620. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19621. const curve = this.curves[ i ];
  19622. data.curves.push( curve.toJSON() );
  19623. }
  19624. return data;
  19625. }
  19626. fromJSON( json ) {
  19627. super.fromJSON( json );
  19628. this.autoClose = json.autoClose;
  19629. this.curves = [];
  19630. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19631. const curve = json.curves[ i ];
  19632. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19633. }
  19634. return this;
  19635. }
  19636. }
  19637. class Path extends CurvePath {
  19638. constructor( points ) {
  19639. super();
  19640. this.type = 'Path';
  19641. this.currentPoint = new Vector2();
  19642. if ( points ) {
  19643. this.setFromPoints( points );
  19644. }
  19645. }
  19646. setFromPoints( points ) {
  19647. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19648. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19649. this.lineTo( points[ i ].x, points[ i ].y );
  19650. }
  19651. return this;
  19652. }
  19653. moveTo( x, y ) {
  19654. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19655. return this;
  19656. }
  19657. lineTo( x, y ) {
  19658. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19659. this.curves.push( curve );
  19660. this.currentPoint.set( x, y );
  19661. return this;
  19662. }
  19663. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19664. const curve = new QuadraticBezierCurve(
  19665. this.currentPoint.clone(),
  19666. new Vector2( aCPx, aCPy ),
  19667. new Vector2( aX, aY )
  19668. );
  19669. this.curves.push( curve );
  19670. this.currentPoint.set( aX, aY );
  19671. return this;
  19672. }
  19673. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19674. const curve = new CubicBezierCurve(
  19675. this.currentPoint.clone(),
  19676. new Vector2( aCP1x, aCP1y ),
  19677. new Vector2( aCP2x, aCP2y ),
  19678. new Vector2( aX, aY )
  19679. );
  19680. this.curves.push( curve );
  19681. this.currentPoint.set( aX, aY );
  19682. return this;
  19683. }
  19684. splineThru( pts /*Array of Vector*/ ) {
  19685. const npts = [ this.currentPoint.clone() ].concat( pts );
  19686. const curve = new SplineCurve( npts );
  19687. this.curves.push( curve );
  19688. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19689. return this;
  19690. }
  19691. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19692. const x0 = this.currentPoint.x;
  19693. const y0 = this.currentPoint.y;
  19694. this.absarc( aX + x0, aY + y0, aRadius,
  19695. aStartAngle, aEndAngle, aClockwise );
  19696. return this;
  19697. }
  19698. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19699. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19700. return this;
  19701. }
  19702. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19703. const x0 = this.currentPoint.x;
  19704. const y0 = this.currentPoint.y;
  19705. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19706. return this;
  19707. }
  19708. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19709. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19710. if ( this.curves.length > 0 ) {
  19711. // if a previous curve is present, attempt to join
  19712. const firstPoint = curve.getPoint( 0 );
  19713. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19714. this.lineTo( firstPoint.x, firstPoint.y );
  19715. }
  19716. }
  19717. this.curves.push( curve );
  19718. const lastPoint = curve.getPoint( 1 );
  19719. this.currentPoint.copy( lastPoint );
  19720. return this;
  19721. }
  19722. copy( source ) {
  19723. super.copy( source );
  19724. this.currentPoint.copy( source.currentPoint );
  19725. return this;
  19726. }
  19727. toJSON() {
  19728. const data = super.toJSON();
  19729. data.currentPoint = this.currentPoint.toArray();
  19730. return data;
  19731. }
  19732. fromJSON( json ) {
  19733. super.fromJSON( json );
  19734. this.currentPoint.fromArray( json.currentPoint );
  19735. return this;
  19736. }
  19737. }
  19738. class LatheGeometry extends BufferGeometry {
  19739. 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 ) {
  19740. super();
  19741. this.type = 'LatheGeometry';
  19742. this.parameters = {
  19743. points: points,
  19744. segments: segments,
  19745. phiStart: phiStart,
  19746. phiLength: phiLength
  19747. };
  19748. segments = Math.floor( segments );
  19749. // clamp phiLength so it's in range of [ 0, 2PI ]
  19750. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19751. // buffers
  19752. const indices = [];
  19753. const vertices = [];
  19754. const uvs = [];
  19755. const initNormals = [];
  19756. const normals = [];
  19757. // helper variables
  19758. const inverseSegments = 1.0 / segments;
  19759. const vertex = new Vector3();
  19760. const uv = new Vector2();
  19761. const normal = new Vector3();
  19762. const curNormal = new Vector3();
  19763. const prevNormal = new Vector3();
  19764. let dx = 0;
  19765. let dy = 0;
  19766. // pre-compute normals for initial "meridian"
  19767. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19768. switch ( j ) {
  19769. case 0: // special handling for 1st vertex on path
  19770. dx = points[ j + 1 ].x - points[ j ].x;
  19771. dy = points[ j + 1 ].y - points[ j ].y;
  19772. normal.x = dy * 1.0;
  19773. normal.y = - dx;
  19774. normal.z = dy * 0.0;
  19775. prevNormal.copy( normal );
  19776. normal.normalize();
  19777. initNormals.push( normal.x, normal.y, normal.z );
  19778. break;
  19779. case ( points.length - 1 ): // special handling for last Vertex on path
  19780. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19781. break;
  19782. default: // default handling for all vertices in between
  19783. dx = points[ j + 1 ].x - points[ j ].x;
  19784. dy = points[ j + 1 ].y - points[ j ].y;
  19785. normal.x = dy * 1.0;
  19786. normal.y = - dx;
  19787. normal.z = dy * 0.0;
  19788. curNormal.copy( normal );
  19789. normal.x += prevNormal.x;
  19790. normal.y += prevNormal.y;
  19791. normal.z += prevNormal.z;
  19792. normal.normalize();
  19793. initNormals.push( normal.x, normal.y, normal.z );
  19794. prevNormal.copy( curNormal );
  19795. }
  19796. }
  19797. // generate vertices, uvs and normals
  19798. for ( let i = 0; i <= segments; i ++ ) {
  19799. const phi = phiStart + i * inverseSegments * phiLength;
  19800. const sin = Math.sin( phi );
  19801. const cos = Math.cos( phi );
  19802. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19803. // vertex
  19804. vertex.x = points[ j ].x * sin;
  19805. vertex.y = points[ j ].y;
  19806. vertex.z = points[ j ].x * cos;
  19807. vertices.push( vertex.x, vertex.y, vertex.z );
  19808. // uv
  19809. uv.x = i / segments;
  19810. uv.y = j / ( points.length - 1 );
  19811. uvs.push( uv.x, uv.y );
  19812. // normal
  19813. const x = initNormals[ 3 * j + 0 ] * sin;
  19814. const y = initNormals[ 3 * j + 1 ];
  19815. const z = initNormals[ 3 * j + 0 ] * cos;
  19816. normals.push( x, y, z );
  19817. }
  19818. }
  19819. // indices
  19820. for ( let i = 0; i < segments; i ++ ) {
  19821. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19822. const base = j + i * points.length;
  19823. const a = base;
  19824. const b = base + points.length;
  19825. const c = base + points.length + 1;
  19826. const d = base + 1;
  19827. // faces
  19828. indices.push( a, b, d );
  19829. indices.push( c, d, b );
  19830. }
  19831. }
  19832. // build geometry
  19833. this.setIndex( indices );
  19834. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19835. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19836. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19837. }
  19838. static fromJSON( data ) {
  19839. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19840. }
  19841. }
  19842. class CapsuleGeometry extends LatheGeometry {
  19843. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19844. const path = new Path();
  19845. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19846. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19847. super( path.getPoints( capSegments ), radialSegments );
  19848. this.type = 'CapsuleGeometry';
  19849. this.parameters = {
  19850. radius: radius,
  19851. height: length,
  19852. capSegments: capSegments,
  19853. radialSegments: radialSegments,
  19854. };
  19855. }
  19856. static fromJSON( data ) {
  19857. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19858. }
  19859. }
  19860. class CircleGeometry extends BufferGeometry {
  19861. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19862. super();
  19863. this.type = 'CircleGeometry';
  19864. this.parameters = {
  19865. radius: radius,
  19866. segments: segments,
  19867. thetaStart: thetaStart,
  19868. thetaLength: thetaLength
  19869. };
  19870. segments = Math.max( 3, segments );
  19871. // buffers
  19872. const indices = [];
  19873. const vertices = [];
  19874. const normals = [];
  19875. const uvs = [];
  19876. // helper variables
  19877. const vertex = new Vector3();
  19878. const uv = new Vector2();
  19879. // center point
  19880. vertices.push( 0, 0, 0 );
  19881. normals.push( 0, 0, 1 );
  19882. uvs.push( 0.5, 0.5 );
  19883. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19884. const segment = thetaStart + s / segments * thetaLength;
  19885. // vertex
  19886. vertex.x = radius * Math.cos( segment );
  19887. vertex.y = radius * Math.sin( segment );
  19888. vertices.push( vertex.x, vertex.y, vertex.z );
  19889. // normal
  19890. normals.push( 0, 0, 1 );
  19891. // uvs
  19892. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19893. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19894. uvs.push( uv.x, uv.y );
  19895. }
  19896. // indices
  19897. for ( let i = 1; i <= segments; i ++ ) {
  19898. indices.push( i, i + 1, 0 );
  19899. }
  19900. // build geometry
  19901. this.setIndex( indices );
  19902. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19903. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19904. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19905. }
  19906. static fromJSON( data ) {
  19907. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19908. }
  19909. }
  19910. class CylinderGeometry extends BufferGeometry {
  19911. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19912. super();
  19913. this.type = 'CylinderGeometry';
  19914. this.parameters = {
  19915. radiusTop: radiusTop,
  19916. radiusBottom: radiusBottom,
  19917. height: height,
  19918. radialSegments: radialSegments,
  19919. heightSegments: heightSegments,
  19920. openEnded: openEnded,
  19921. thetaStart: thetaStart,
  19922. thetaLength: thetaLength
  19923. };
  19924. const scope = this;
  19925. radialSegments = Math.floor( radialSegments );
  19926. heightSegments = Math.floor( heightSegments );
  19927. // buffers
  19928. const indices = [];
  19929. const vertices = [];
  19930. const normals = [];
  19931. const uvs = [];
  19932. // helper variables
  19933. let index = 0;
  19934. const indexArray = [];
  19935. const halfHeight = height / 2;
  19936. let groupStart = 0;
  19937. // generate geometry
  19938. generateTorso();
  19939. if ( openEnded === false ) {
  19940. if ( radiusTop > 0 ) generateCap( true );
  19941. if ( radiusBottom > 0 ) generateCap( false );
  19942. }
  19943. // build geometry
  19944. this.setIndex( indices );
  19945. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19946. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19947. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19948. function generateTorso() {
  19949. const normal = new Vector3();
  19950. const vertex = new Vector3();
  19951. let groupCount = 0;
  19952. // this will be used to calculate the normal
  19953. const slope = ( radiusBottom - radiusTop ) / height;
  19954. // generate vertices, normals and uvs
  19955. for ( let y = 0; y <= heightSegments; y ++ ) {
  19956. const indexRow = [];
  19957. const v = y / heightSegments;
  19958. // calculate the radius of the current row
  19959. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19960. for ( let x = 0; x <= radialSegments; x ++ ) {
  19961. const u = x / radialSegments;
  19962. const theta = u * thetaLength + thetaStart;
  19963. const sinTheta = Math.sin( theta );
  19964. const cosTheta = Math.cos( theta );
  19965. // vertex
  19966. vertex.x = radius * sinTheta;
  19967. vertex.y = - v * height + halfHeight;
  19968. vertex.z = radius * cosTheta;
  19969. vertices.push( vertex.x, vertex.y, vertex.z );
  19970. // normal
  19971. normal.set( sinTheta, slope, cosTheta ).normalize();
  19972. normals.push( normal.x, normal.y, normal.z );
  19973. // uv
  19974. uvs.push( u, 1 - v );
  19975. // save index of vertex in respective row
  19976. indexRow.push( index ++ );
  19977. }
  19978. // now save vertices of the row in our index array
  19979. indexArray.push( indexRow );
  19980. }
  19981. // generate indices
  19982. for ( let x = 0; x < radialSegments; x ++ ) {
  19983. for ( let y = 0; y < heightSegments; y ++ ) {
  19984. // we use the index array to access the correct indices
  19985. const a = indexArray[ y ][ x ];
  19986. const b = indexArray[ y + 1 ][ x ];
  19987. const c = indexArray[ y + 1 ][ x + 1 ];
  19988. const d = indexArray[ y ][ x + 1 ];
  19989. // faces
  19990. indices.push( a, b, d );
  19991. indices.push( b, c, d );
  19992. // update group counter
  19993. groupCount += 6;
  19994. }
  19995. }
  19996. // add a group to the geometry. this will ensure multi material support
  19997. scope.addGroup( groupStart, groupCount, 0 );
  19998. // calculate new start value for groups
  19999. groupStart += groupCount;
  20000. }
  20001. function generateCap( top ) {
  20002. // save the index of the first center vertex
  20003. const centerIndexStart = index;
  20004. const uv = new Vector2();
  20005. const vertex = new Vector3();
  20006. let groupCount = 0;
  20007. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20008. const sign = ( top === true ) ? 1 : - 1;
  20009. // first we generate the center vertex data of the cap.
  20010. // because the geometry needs one set of uvs per face,
  20011. // we must generate a center vertex per face/segment
  20012. for ( let x = 1; x <= radialSegments; x ++ ) {
  20013. // vertex
  20014. vertices.push( 0, halfHeight * sign, 0 );
  20015. // normal
  20016. normals.push( 0, sign, 0 );
  20017. // uv
  20018. uvs.push( 0.5, 0.5 );
  20019. // increase index
  20020. index ++;
  20021. }
  20022. // save the index of the last center vertex
  20023. const centerIndexEnd = index;
  20024. // now we generate the surrounding vertices, normals and uvs
  20025. for ( let x = 0; x <= radialSegments; x ++ ) {
  20026. const u = x / radialSegments;
  20027. const theta = u * thetaLength + thetaStart;
  20028. const cosTheta = Math.cos( theta );
  20029. const sinTheta = Math.sin( theta );
  20030. // vertex
  20031. vertex.x = radius * sinTheta;
  20032. vertex.y = halfHeight * sign;
  20033. vertex.z = radius * cosTheta;
  20034. vertices.push( vertex.x, vertex.y, vertex.z );
  20035. // normal
  20036. normals.push( 0, sign, 0 );
  20037. // uv
  20038. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20039. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20040. uvs.push( uv.x, uv.y );
  20041. // increase index
  20042. index ++;
  20043. }
  20044. // generate indices
  20045. for ( let x = 0; x < radialSegments; x ++ ) {
  20046. const c = centerIndexStart + x;
  20047. const i = centerIndexEnd + x;
  20048. if ( top === true ) {
  20049. // face top
  20050. indices.push( i, i + 1, c );
  20051. } else {
  20052. // face bottom
  20053. indices.push( i + 1, i, c );
  20054. }
  20055. groupCount += 3;
  20056. }
  20057. // add a group to the geometry. this will ensure multi material support
  20058. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20059. // calculate new start value for groups
  20060. groupStart += groupCount;
  20061. }
  20062. }
  20063. static fromJSON( data ) {
  20064. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20065. }
  20066. }
  20067. class ConeGeometry extends CylinderGeometry {
  20068. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20069. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20070. this.type = 'ConeGeometry';
  20071. this.parameters = {
  20072. radius: radius,
  20073. height: height,
  20074. radialSegments: radialSegments,
  20075. heightSegments: heightSegments,
  20076. openEnded: openEnded,
  20077. thetaStart: thetaStart,
  20078. thetaLength: thetaLength
  20079. };
  20080. }
  20081. static fromJSON( data ) {
  20082. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20083. }
  20084. }
  20085. class PolyhedronGeometry extends BufferGeometry {
  20086. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20087. super();
  20088. this.type = 'PolyhedronGeometry';
  20089. this.parameters = {
  20090. vertices: vertices,
  20091. indices: indices,
  20092. radius: radius,
  20093. detail: detail
  20094. };
  20095. // default buffer data
  20096. const vertexBuffer = [];
  20097. const uvBuffer = [];
  20098. // the subdivision creates the vertex buffer data
  20099. subdivide( detail );
  20100. // all vertices should lie on a conceptual sphere with a given radius
  20101. applyRadius( radius );
  20102. // finally, create the uv data
  20103. generateUVs();
  20104. // build non-indexed geometry
  20105. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20106. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20107. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20108. if ( detail === 0 ) {
  20109. this.computeVertexNormals(); // flat normals
  20110. } else {
  20111. this.normalizeNormals(); // smooth normals
  20112. }
  20113. // helper functions
  20114. function subdivide( detail ) {
  20115. const a = new Vector3();
  20116. const b = new Vector3();
  20117. const c = new Vector3();
  20118. // iterate over all faces and apply a subdivision with the given detail value
  20119. for ( let i = 0; i < indices.length; i += 3 ) {
  20120. // get the vertices of the face
  20121. getVertexByIndex( indices[ i + 0 ], a );
  20122. getVertexByIndex( indices[ i + 1 ], b );
  20123. getVertexByIndex( indices[ i + 2 ], c );
  20124. // perform subdivision
  20125. subdivideFace( a, b, c, detail );
  20126. }
  20127. }
  20128. function subdivideFace( a, b, c, detail ) {
  20129. const cols = detail + 1;
  20130. // we use this multidimensional array as a data structure for creating the subdivision
  20131. const v = [];
  20132. // construct all of the vertices for this subdivision
  20133. for ( let i = 0; i <= cols; i ++ ) {
  20134. v[ i ] = [];
  20135. const aj = a.clone().lerp( c, i / cols );
  20136. const bj = b.clone().lerp( c, i / cols );
  20137. const rows = cols - i;
  20138. for ( let j = 0; j <= rows; j ++ ) {
  20139. if ( j === 0 && i === cols ) {
  20140. v[ i ][ j ] = aj;
  20141. } else {
  20142. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20143. }
  20144. }
  20145. }
  20146. // construct all of the faces
  20147. for ( let i = 0; i < cols; i ++ ) {
  20148. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20149. const k = Math.floor( j / 2 );
  20150. if ( j % 2 === 0 ) {
  20151. pushVertex( v[ i ][ k + 1 ] );
  20152. pushVertex( v[ i + 1 ][ k ] );
  20153. pushVertex( v[ i ][ k ] );
  20154. } else {
  20155. pushVertex( v[ i ][ k + 1 ] );
  20156. pushVertex( v[ i + 1 ][ k + 1 ] );
  20157. pushVertex( v[ i + 1 ][ k ] );
  20158. }
  20159. }
  20160. }
  20161. }
  20162. function applyRadius( radius ) {
  20163. const vertex = new Vector3();
  20164. // iterate over the entire buffer and apply the radius to each vertex
  20165. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20166. vertex.x = vertexBuffer[ i + 0 ];
  20167. vertex.y = vertexBuffer[ i + 1 ];
  20168. vertex.z = vertexBuffer[ i + 2 ];
  20169. vertex.normalize().multiplyScalar( radius );
  20170. vertexBuffer[ i + 0 ] = vertex.x;
  20171. vertexBuffer[ i + 1 ] = vertex.y;
  20172. vertexBuffer[ i + 2 ] = vertex.z;
  20173. }
  20174. }
  20175. function generateUVs() {
  20176. const vertex = new Vector3();
  20177. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20178. vertex.x = vertexBuffer[ i + 0 ];
  20179. vertex.y = vertexBuffer[ i + 1 ];
  20180. vertex.z = vertexBuffer[ i + 2 ];
  20181. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20182. const v = inclination( vertex ) / Math.PI + 0.5;
  20183. uvBuffer.push( u, 1 - v );
  20184. }
  20185. correctUVs();
  20186. correctSeam();
  20187. }
  20188. function correctSeam() {
  20189. // handle case when face straddles the seam, see #3269
  20190. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20191. // uv data of a single face
  20192. const x0 = uvBuffer[ i + 0 ];
  20193. const x1 = uvBuffer[ i + 2 ];
  20194. const x2 = uvBuffer[ i + 4 ];
  20195. const max = Math.max( x0, x1, x2 );
  20196. const min = Math.min( x0, x1, x2 );
  20197. // 0.9 is somewhat arbitrary
  20198. if ( max > 0.9 && min < 0.1 ) {
  20199. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20200. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20201. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20202. }
  20203. }
  20204. }
  20205. function pushVertex( vertex ) {
  20206. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20207. }
  20208. function getVertexByIndex( index, vertex ) {
  20209. const stride = index * 3;
  20210. vertex.x = vertices[ stride + 0 ];
  20211. vertex.y = vertices[ stride + 1 ];
  20212. vertex.z = vertices[ stride + 2 ];
  20213. }
  20214. function correctUVs() {
  20215. const a = new Vector3();
  20216. const b = new Vector3();
  20217. const c = new Vector3();
  20218. const centroid = new Vector3();
  20219. const uvA = new Vector2();
  20220. const uvB = new Vector2();
  20221. const uvC = new Vector2();
  20222. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20223. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20224. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20225. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20226. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20227. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20228. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20229. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20230. const azi = azimuth( centroid );
  20231. correctUV( uvA, j + 0, a, azi );
  20232. correctUV( uvB, j + 2, b, azi );
  20233. correctUV( uvC, j + 4, c, azi );
  20234. }
  20235. }
  20236. function correctUV( uv, stride, vector, azimuth ) {
  20237. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20238. uvBuffer[ stride ] = uv.x - 1;
  20239. }
  20240. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20241. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20242. }
  20243. }
  20244. // Angle around the Y axis, counter-clockwise when looking from above.
  20245. function azimuth( vector ) {
  20246. return Math.atan2( vector.z, - vector.x );
  20247. }
  20248. // Angle above the XZ plane.
  20249. function inclination( vector ) {
  20250. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20251. }
  20252. }
  20253. static fromJSON( data ) {
  20254. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20255. }
  20256. }
  20257. class DodecahedronGeometry extends PolyhedronGeometry {
  20258. constructor( radius = 1, detail = 0 ) {
  20259. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20260. const r = 1 / t;
  20261. const vertices = [
  20262. // (±1, ±1, ±1)
  20263. - 1, - 1, - 1, - 1, - 1, 1,
  20264. - 1, 1, - 1, - 1, 1, 1,
  20265. 1, - 1, - 1, 1, - 1, 1,
  20266. 1, 1, - 1, 1, 1, 1,
  20267. // (0, ±1/φ, ±φ)
  20268. 0, - r, - t, 0, - r, t,
  20269. 0, r, - t, 0, r, t,
  20270. // (±1/φ, ±φ, 0)
  20271. - r, - t, 0, - r, t, 0,
  20272. r, - t, 0, r, t, 0,
  20273. // (±φ, 0, ±1/φ)
  20274. - t, 0, - r, t, 0, - r,
  20275. - t, 0, r, t, 0, r
  20276. ];
  20277. const indices = [
  20278. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20279. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20280. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20281. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20282. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20283. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20284. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20285. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20286. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20287. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20288. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20289. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20290. ];
  20291. super( vertices, indices, radius, detail );
  20292. this.type = 'DodecahedronGeometry';
  20293. this.parameters = {
  20294. radius: radius,
  20295. detail: detail
  20296. };
  20297. }
  20298. static fromJSON( data ) {
  20299. return new DodecahedronGeometry( data.radius, data.detail );
  20300. }
  20301. }
  20302. const _v0 = /*@__PURE__*/ new Vector3();
  20303. const _v1$1 = /*@__PURE__*/ new Vector3();
  20304. const _normal = /*@__PURE__*/ new Vector3();
  20305. const _triangle = /*@__PURE__*/ new Triangle();
  20306. class EdgesGeometry extends BufferGeometry {
  20307. constructor( geometry = null, thresholdAngle = 1 ) {
  20308. super();
  20309. this.type = 'EdgesGeometry';
  20310. this.parameters = {
  20311. geometry: geometry,
  20312. thresholdAngle: thresholdAngle
  20313. };
  20314. if ( geometry !== null ) {
  20315. const precisionPoints = 4;
  20316. const precision = Math.pow( 10, precisionPoints );
  20317. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20318. const indexAttr = geometry.getIndex();
  20319. const positionAttr = geometry.getAttribute( 'position' );
  20320. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20321. const indexArr = [ 0, 0, 0 ];
  20322. const vertKeys = [ 'a', 'b', 'c' ];
  20323. const hashes = new Array( 3 );
  20324. const edgeData = {};
  20325. const vertices = [];
  20326. for ( let i = 0; i < indexCount; i += 3 ) {
  20327. if ( indexAttr ) {
  20328. indexArr[ 0 ] = indexAttr.getX( i );
  20329. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20330. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20331. } else {
  20332. indexArr[ 0 ] = i;
  20333. indexArr[ 1 ] = i + 1;
  20334. indexArr[ 2 ] = i + 2;
  20335. }
  20336. const { a, b, c } = _triangle;
  20337. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20338. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20339. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20340. _triangle.getNormal( _normal );
  20341. // create hashes for the edge from the vertices
  20342. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20343. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20344. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20345. // skip degenerate triangles
  20346. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20347. continue;
  20348. }
  20349. // iterate over every edge
  20350. for ( let j = 0; j < 3; j ++ ) {
  20351. // get the first and next vertex making up the edge
  20352. const jNext = ( j + 1 ) % 3;
  20353. const vecHash0 = hashes[ j ];
  20354. const vecHash1 = hashes[ jNext ];
  20355. const v0 = _triangle[ vertKeys[ j ] ];
  20356. const v1 = _triangle[ vertKeys[ jNext ] ];
  20357. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20358. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20359. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20360. // if we found a sibling edge add it into the vertex array if
  20361. // it meets the angle threshold and delete the edge from the map.
  20362. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20363. vertices.push( v0.x, v0.y, v0.z );
  20364. vertices.push( v1.x, v1.y, v1.z );
  20365. }
  20366. edgeData[ reverseHash ] = null;
  20367. } else if ( ! ( hash in edgeData ) ) {
  20368. // if we've already got an edge here then skip adding a new one
  20369. edgeData[ hash ] = {
  20370. index0: indexArr[ j ],
  20371. index1: indexArr[ jNext ],
  20372. normal: _normal.clone(),
  20373. };
  20374. }
  20375. }
  20376. }
  20377. // iterate over all remaining, unmatched edges and add them to the vertex array
  20378. for ( const key in edgeData ) {
  20379. if ( edgeData[ key ] ) {
  20380. const { index0, index1 } = edgeData[ key ];
  20381. _v0.fromBufferAttribute( positionAttr, index0 );
  20382. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20383. vertices.push( _v0.x, _v0.y, _v0.z );
  20384. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20385. }
  20386. }
  20387. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20388. }
  20389. }
  20390. }
  20391. class Shape extends Path {
  20392. constructor( points ) {
  20393. super( points );
  20394. this.uuid = generateUUID();
  20395. this.type = 'Shape';
  20396. this.holes = [];
  20397. }
  20398. getPointsHoles( divisions ) {
  20399. const holesPts = [];
  20400. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20401. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20402. }
  20403. return holesPts;
  20404. }
  20405. // get points of shape and holes (keypoints based on segments parameter)
  20406. extractPoints( divisions ) {
  20407. return {
  20408. shape: this.getPoints( divisions ),
  20409. holes: this.getPointsHoles( divisions )
  20410. };
  20411. }
  20412. copy( source ) {
  20413. super.copy( source );
  20414. this.holes = [];
  20415. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20416. const hole = source.holes[ i ];
  20417. this.holes.push( hole.clone() );
  20418. }
  20419. return this;
  20420. }
  20421. toJSON() {
  20422. const data = super.toJSON();
  20423. data.uuid = this.uuid;
  20424. data.holes = [];
  20425. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20426. const hole = this.holes[ i ];
  20427. data.holes.push( hole.toJSON() );
  20428. }
  20429. return data;
  20430. }
  20431. fromJSON( json ) {
  20432. super.fromJSON( json );
  20433. this.uuid = json.uuid;
  20434. this.holes = [];
  20435. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20436. const hole = json.holes[ i ];
  20437. this.holes.push( new Path().fromJSON( hole ) );
  20438. }
  20439. return this;
  20440. }
  20441. }
  20442. /**
  20443. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20444. */
  20445. const Earcut = {
  20446. triangulate: function ( data, holeIndices, dim = 2 ) {
  20447. const hasHoles = holeIndices && holeIndices.length;
  20448. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20449. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20450. const triangles = [];
  20451. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20452. let minX, minY, maxX, maxY, x, y, invSize;
  20453. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20454. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20455. if ( data.length > 80 * dim ) {
  20456. minX = maxX = data[ 0 ];
  20457. minY = maxY = data[ 1 ];
  20458. for ( let i = dim; i < outerLen; i += dim ) {
  20459. x = data[ i ];
  20460. y = data[ i + 1 ];
  20461. if ( x < minX ) minX = x;
  20462. if ( y < minY ) minY = y;
  20463. if ( x > maxX ) maxX = x;
  20464. if ( y > maxY ) maxY = y;
  20465. }
  20466. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20467. invSize = Math.max( maxX - minX, maxY - minY );
  20468. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20469. }
  20470. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20471. return triangles;
  20472. }
  20473. };
  20474. // create a circular doubly linked list from polygon points in the specified winding order
  20475. function linkedList( data, start, end, dim, clockwise ) {
  20476. let i, last;
  20477. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20478. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20479. } else {
  20480. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20481. }
  20482. if ( last && equals( last, last.next ) ) {
  20483. removeNode( last );
  20484. last = last.next;
  20485. }
  20486. return last;
  20487. }
  20488. // eliminate colinear or duplicate points
  20489. function filterPoints( start, end ) {
  20490. if ( ! start ) return start;
  20491. if ( ! end ) end = start;
  20492. let p = start,
  20493. again;
  20494. do {
  20495. again = false;
  20496. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20497. removeNode( p );
  20498. p = end = p.prev;
  20499. if ( p === p.next ) break;
  20500. again = true;
  20501. } else {
  20502. p = p.next;
  20503. }
  20504. } while ( again || p !== end );
  20505. return end;
  20506. }
  20507. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20508. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20509. if ( ! ear ) return;
  20510. // interlink polygon nodes in z-order
  20511. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20512. let stop = ear,
  20513. prev, next;
  20514. // iterate through ears, slicing them one by one
  20515. while ( ear.prev !== ear.next ) {
  20516. prev = ear.prev;
  20517. next = ear.next;
  20518. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20519. // cut off the triangle
  20520. triangles.push( prev.i / dim | 0 );
  20521. triangles.push( ear.i / dim | 0 );
  20522. triangles.push( next.i / dim | 0 );
  20523. removeNode( ear );
  20524. // skipping the next vertex leads to less sliver triangles
  20525. ear = next.next;
  20526. stop = next.next;
  20527. continue;
  20528. }
  20529. ear = next;
  20530. // if we looped through the whole remaining polygon and can't find any more ears
  20531. if ( ear === stop ) {
  20532. // try filtering points and slicing again
  20533. if ( ! pass ) {
  20534. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20535. // if this didn't work, try curing all small self-intersections locally
  20536. } else if ( pass === 1 ) {
  20537. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20538. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20539. // as a last resort, try splitting the remaining polygon into two
  20540. } else if ( pass === 2 ) {
  20541. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20542. }
  20543. break;
  20544. }
  20545. }
  20546. }
  20547. // check whether a polygon node forms a valid ear with adjacent nodes
  20548. function isEar( ear ) {
  20549. const a = ear.prev,
  20550. b = ear,
  20551. c = ear.next;
  20552. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20553. // now make sure we don't have other points inside the potential ear
  20554. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20555. // triangle bbox; min & max are calculated like this for speed
  20556. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20557. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20558. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20559. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20560. let p = c.next;
  20561. while ( p !== a ) {
  20562. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20563. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20564. area( p.prev, p, p.next ) >= 0 ) return false;
  20565. p = p.next;
  20566. }
  20567. return true;
  20568. }
  20569. function isEarHashed( ear, minX, minY, invSize ) {
  20570. const a = ear.prev,
  20571. b = ear,
  20572. c = ear.next;
  20573. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20574. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20575. // triangle bbox; min & max are calculated like this for speed
  20576. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20577. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20578. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20579. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20580. // z-order range for the current triangle bbox;
  20581. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20582. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20583. let p = ear.prevZ,
  20584. n = ear.nextZ;
  20585. // look for points inside the triangle in both directions
  20586. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20587. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20588. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20589. p = p.prevZ;
  20590. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20591. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20592. n = n.nextZ;
  20593. }
  20594. // look for remaining points in decreasing z-order
  20595. while ( p && p.z >= minZ ) {
  20596. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20597. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20598. p = p.prevZ;
  20599. }
  20600. // look for remaining points in increasing z-order
  20601. while ( n && n.z <= maxZ ) {
  20602. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20603. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20604. n = n.nextZ;
  20605. }
  20606. return true;
  20607. }
  20608. // go through all polygon nodes and cure small local self-intersections
  20609. function cureLocalIntersections( start, triangles, dim ) {
  20610. let p = start;
  20611. do {
  20612. const a = p.prev,
  20613. b = p.next.next;
  20614. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20615. triangles.push( a.i / dim | 0 );
  20616. triangles.push( p.i / dim | 0 );
  20617. triangles.push( b.i / dim | 0 );
  20618. // remove two nodes involved
  20619. removeNode( p );
  20620. removeNode( p.next );
  20621. p = start = b;
  20622. }
  20623. p = p.next;
  20624. } while ( p !== start );
  20625. return filterPoints( p );
  20626. }
  20627. // try splitting polygon into two and triangulate them independently
  20628. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20629. // look for a valid diagonal that divides the polygon into two
  20630. let a = start;
  20631. do {
  20632. let b = a.next.next;
  20633. while ( b !== a.prev ) {
  20634. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20635. // split the polygon in two by the diagonal
  20636. let c = splitPolygon( a, b );
  20637. // filter colinear points around the cuts
  20638. a = filterPoints( a, a.next );
  20639. c = filterPoints( c, c.next );
  20640. // run earcut on each half
  20641. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20642. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20643. return;
  20644. }
  20645. b = b.next;
  20646. }
  20647. a = a.next;
  20648. } while ( a !== start );
  20649. }
  20650. // link every hole into the outer loop, producing a single-ring polygon without holes
  20651. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20652. const queue = [];
  20653. let i, len, start, end, list;
  20654. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20655. start = holeIndices[ i ] * dim;
  20656. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20657. list = linkedList( data, start, end, dim, false );
  20658. if ( list === list.next ) list.steiner = true;
  20659. queue.push( getLeftmost( list ) );
  20660. }
  20661. queue.sort( compareX );
  20662. // process holes from left to right
  20663. for ( i = 0; i < queue.length; i ++ ) {
  20664. outerNode = eliminateHole( queue[ i ], outerNode );
  20665. }
  20666. return outerNode;
  20667. }
  20668. function compareX( a, b ) {
  20669. return a.x - b.x;
  20670. }
  20671. // find a bridge between vertices that connects hole with an outer ring and link it
  20672. function eliminateHole( hole, outerNode ) {
  20673. const bridge = findHoleBridge( hole, outerNode );
  20674. if ( ! bridge ) {
  20675. return outerNode;
  20676. }
  20677. const bridgeReverse = splitPolygon( bridge, hole );
  20678. // filter collinear points around the cuts
  20679. filterPoints( bridgeReverse, bridgeReverse.next );
  20680. return filterPoints( bridge, bridge.next );
  20681. }
  20682. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20683. function findHoleBridge( hole, outerNode ) {
  20684. let p = outerNode,
  20685. qx = - Infinity,
  20686. m;
  20687. const hx = hole.x, hy = hole.y;
  20688. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20689. // segment's endpoint with lesser x will be potential connection point
  20690. do {
  20691. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20692. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20693. if ( x <= hx && x > qx ) {
  20694. qx = x;
  20695. m = p.x < p.next.x ? p : p.next;
  20696. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20697. }
  20698. }
  20699. p = p.next;
  20700. } while ( p !== outerNode );
  20701. if ( ! m ) return null;
  20702. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20703. // if there are no points found, we have a valid connection;
  20704. // otherwise choose the point of the minimum angle with the ray as connection point
  20705. const stop = m,
  20706. mx = m.x,
  20707. my = m.y;
  20708. let tanMin = Infinity, tan;
  20709. p = m;
  20710. do {
  20711. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20712. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20713. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20714. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20715. m = p;
  20716. tanMin = tan;
  20717. }
  20718. }
  20719. p = p.next;
  20720. } while ( p !== stop );
  20721. return m;
  20722. }
  20723. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20724. function sectorContainsSector( m, p ) {
  20725. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20726. }
  20727. // interlink polygon nodes in z-order
  20728. function indexCurve( start, minX, minY, invSize ) {
  20729. let p = start;
  20730. do {
  20731. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20732. p.prevZ = p.prev;
  20733. p.nextZ = p.next;
  20734. p = p.next;
  20735. } while ( p !== start );
  20736. p.prevZ.nextZ = null;
  20737. p.prevZ = null;
  20738. sortLinked( p );
  20739. }
  20740. // Simon Tatham's linked list merge sort algorithm
  20741. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20742. function sortLinked( list ) {
  20743. let i, p, q, e, tail, numMerges, pSize, qSize,
  20744. inSize = 1;
  20745. do {
  20746. p = list;
  20747. list = null;
  20748. tail = null;
  20749. numMerges = 0;
  20750. while ( p ) {
  20751. numMerges ++;
  20752. q = p;
  20753. pSize = 0;
  20754. for ( i = 0; i < inSize; i ++ ) {
  20755. pSize ++;
  20756. q = q.nextZ;
  20757. if ( ! q ) break;
  20758. }
  20759. qSize = inSize;
  20760. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20761. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20762. e = p;
  20763. p = p.nextZ;
  20764. pSize --;
  20765. } else {
  20766. e = q;
  20767. q = q.nextZ;
  20768. qSize --;
  20769. }
  20770. if ( tail ) tail.nextZ = e;
  20771. else list = e;
  20772. e.prevZ = tail;
  20773. tail = e;
  20774. }
  20775. p = q;
  20776. }
  20777. tail.nextZ = null;
  20778. inSize *= 2;
  20779. } while ( numMerges > 1 );
  20780. return list;
  20781. }
  20782. // z-order of a point given coords and inverse of the longer side of data bbox
  20783. function zOrder( x, y, minX, minY, invSize ) {
  20784. // coords are transformed into non-negative 15-bit integer range
  20785. x = ( x - minX ) * invSize | 0;
  20786. y = ( y - minY ) * invSize | 0;
  20787. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20788. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20789. x = ( x | ( x << 2 ) ) & 0x33333333;
  20790. x = ( x | ( x << 1 ) ) & 0x55555555;
  20791. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20792. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20793. y = ( y | ( y << 2 ) ) & 0x33333333;
  20794. y = ( y | ( y << 1 ) ) & 0x55555555;
  20795. return x | ( y << 1 );
  20796. }
  20797. // find the leftmost node of a polygon ring
  20798. function getLeftmost( start ) {
  20799. let p = start,
  20800. leftmost = start;
  20801. do {
  20802. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20803. p = p.next;
  20804. } while ( p !== start );
  20805. return leftmost;
  20806. }
  20807. // check if a point lies within a convex triangle
  20808. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20809. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20810. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20811. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20812. }
  20813. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20814. function isValidDiagonal( a, b ) {
  20815. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20816. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20817. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20818. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20819. }
  20820. // signed area of a triangle
  20821. function area( p, q, r ) {
  20822. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20823. }
  20824. // check if two points are equal
  20825. function equals( p1, p2 ) {
  20826. return p1.x === p2.x && p1.y === p2.y;
  20827. }
  20828. // check if two segments intersect
  20829. function intersects( p1, q1, p2, q2 ) {
  20830. const o1 = sign( area( p1, q1, p2 ) );
  20831. const o2 = sign( area( p1, q1, q2 ) );
  20832. const o3 = sign( area( p2, q2, p1 ) );
  20833. const o4 = sign( area( p2, q2, q1 ) );
  20834. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20835. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20836. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20837. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20838. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20839. return false;
  20840. }
  20841. // for collinear points p, q, r, check if point q lies on segment pr
  20842. function onSegment( p, q, r ) {
  20843. 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 );
  20844. }
  20845. function sign( num ) {
  20846. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20847. }
  20848. // check if a polygon diagonal intersects any polygon segments
  20849. function intersectsPolygon( a, b ) {
  20850. let p = a;
  20851. do {
  20852. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20853. intersects( p, p.next, a, b ) ) return true;
  20854. p = p.next;
  20855. } while ( p !== a );
  20856. return false;
  20857. }
  20858. // check if a polygon diagonal is locally inside the polygon
  20859. function locallyInside( a, b ) {
  20860. return area( a.prev, a, a.next ) < 0 ?
  20861. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20862. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20863. }
  20864. // check if the middle point of a polygon diagonal is inside the polygon
  20865. function middleInside( a, b ) {
  20866. let p = a,
  20867. inside = false;
  20868. const px = ( a.x + b.x ) / 2,
  20869. py = ( a.y + b.y ) / 2;
  20870. do {
  20871. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20872. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20873. inside = ! inside;
  20874. p = p.next;
  20875. } while ( p !== a );
  20876. return inside;
  20877. }
  20878. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20879. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20880. function splitPolygon( a, b ) {
  20881. const a2 = new Node( a.i, a.x, a.y ),
  20882. b2 = new Node( b.i, b.x, b.y ),
  20883. an = a.next,
  20884. bp = b.prev;
  20885. a.next = b;
  20886. b.prev = a;
  20887. a2.next = an;
  20888. an.prev = a2;
  20889. b2.next = a2;
  20890. a2.prev = b2;
  20891. bp.next = b2;
  20892. b2.prev = bp;
  20893. return b2;
  20894. }
  20895. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20896. function insertNode( i, x, y, last ) {
  20897. const p = new Node( i, x, y );
  20898. if ( ! last ) {
  20899. p.prev = p;
  20900. p.next = p;
  20901. } else {
  20902. p.next = last.next;
  20903. p.prev = last;
  20904. last.next.prev = p;
  20905. last.next = p;
  20906. }
  20907. return p;
  20908. }
  20909. function removeNode( p ) {
  20910. p.next.prev = p.prev;
  20911. p.prev.next = p.next;
  20912. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20913. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20914. }
  20915. function Node( i, x, y ) {
  20916. // vertex index in coordinates array
  20917. this.i = i;
  20918. // vertex coordinates
  20919. this.x = x;
  20920. this.y = y;
  20921. // previous and next vertex nodes in a polygon ring
  20922. this.prev = null;
  20923. this.next = null;
  20924. // z-order curve value
  20925. this.z = 0;
  20926. // previous and next nodes in z-order
  20927. this.prevZ = null;
  20928. this.nextZ = null;
  20929. // indicates whether this is a steiner point
  20930. this.steiner = false;
  20931. }
  20932. function signedArea( data, start, end, dim ) {
  20933. let sum = 0;
  20934. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20935. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20936. j = i;
  20937. }
  20938. return sum;
  20939. }
  20940. class ShapeUtils {
  20941. // calculate area of the contour polygon
  20942. static area( contour ) {
  20943. const n = contour.length;
  20944. let a = 0.0;
  20945. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20946. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20947. }
  20948. return a * 0.5;
  20949. }
  20950. static isClockWise( pts ) {
  20951. return ShapeUtils.area( pts ) < 0;
  20952. }
  20953. static triangulateShape( contour, holes ) {
  20954. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20955. const holeIndices = []; // array of hole indices
  20956. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20957. removeDupEndPts( contour );
  20958. addContour( vertices, contour );
  20959. //
  20960. let holeIndex = contour.length;
  20961. holes.forEach( removeDupEndPts );
  20962. for ( let i = 0; i < holes.length; i ++ ) {
  20963. holeIndices.push( holeIndex );
  20964. holeIndex += holes[ i ].length;
  20965. addContour( vertices, holes[ i ] );
  20966. }
  20967. //
  20968. const triangles = Earcut.triangulate( vertices, holeIndices );
  20969. //
  20970. for ( let i = 0; i < triangles.length; i += 3 ) {
  20971. faces.push( triangles.slice( i, i + 3 ) );
  20972. }
  20973. return faces;
  20974. }
  20975. }
  20976. function removeDupEndPts( points ) {
  20977. const l = points.length;
  20978. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20979. points.pop();
  20980. }
  20981. }
  20982. function addContour( vertices, contour ) {
  20983. for ( let i = 0; i < contour.length; i ++ ) {
  20984. vertices.push( contour[ i ].x );
  20985. vertices.push( contour[ i ].y );
  20986. }
  20987. }
  20988. /**
  20989. * Creates extruded geometry from a path shape.
  20990. *
  20991. * parameters = {
  20992. *
  20993. * curveSegments: <int>, // number of points on the curves
  20994. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20995. * depth: <float>, // Depth to extrude the shape
  20996. *
  20997. * bevelEnabled: <bool>, // turn on bevel
  20998. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20999. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21000. * bevelOffset: <float>, // how far from shape outline does bevel start
  21001. * bevelSegments: <int>, // number of bevel layers
  21002. *
  21003. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21004. *
  21005. * UVGenerator: <Object> // object that provides UV generator functions
  21006. *
  21007. * }
  21008. */
  21009. class ExtrudeGeometry extends BufferGeometry {
  21010. 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 = {} ) {
  21011. super();
  21012. this.type = 'ExtrudeGeometry';
  21013. this.parameters = {
  21014. shapes: shapes,
  21015. options: options
  21016. };
  21017. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21018. const scope = this;
  21019. const verticesArray = [];
  21020. const uvArray = [];
  21021. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21022. const shape = shapes[ i ];
  21023. addShape( shape );
  21024. }
  21025. // build geometry
  21026. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21027. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21028. this.computeVertexNormals();
  21029. // functions
  21030. function addShape( shape ) {
  21031. const placeholder = [];
  21032. // options
  21033. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21034. const steps = options.steps !== undefined ? options.steps : 1;
  21035. const depth = options.depth !== undefined ? options.depth : 1;
  21036. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21037. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21038. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21039. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21040. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21041. const extrudePath = options.extrudePath;
  21042. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21043. //
  21044. let extrudePts, extrudeByPath = false;
  21045. let splineTube, binormal, normal, position2;
  21046. if ( extrudePath ) {
  21047. extrudePts = extrudePath.getSpacedPoints( steps );
  21048. extrudeByPath = true;
  21049. bevelEnabled = false; // bevels not supported for path extrusion
  21050. // SETUP TNB variables
  21051. // TODO1 - have a .isClosed in spline?
  21052. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21053. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21054. binormal = new Vector3();
  21055. normal = new Vector3();
  21056. position2 = new Vector3();
  21057. }
  21058. // Safeguards if bevels are not enabled
  21059. if ( ! bevelEnabled ) {
  21060. bevelSegments = 0;
  21061. bevelThickness = 0;
  21062. bevelSize = 0;
  21063. bevelOffset = 0;
  21064. }
  21065. // Variables initialization
  21066. const shapePoints = shape.extractPoints( curveSegments );
  21067. let vertices = shapePoints.shape;
  21068. const holes = shapePoints.holes;
  21069. const reverse = ! ShapeUtils.isClockWise( vertices );
  21070. if ( reverse ) {
  21071. vertices = vertices.reverse();
  21072. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21073. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21074. const ahole = holes[ h ];
  21075. if ( ShapeUtils.isClockWise( ahole ) ) {
  21076. holes[ h ] = ahole.reverse();
  21077. }
  21078. }
  21079. }
  21080. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21081. /* Vertices */
  21082. const contour = vertices; // vertices has all points but contour has only points of circumference
  21083. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21084. const ahole = holes[ h ];
  21085. vertices = vertices.concat( ahole );
  21086. }
  21087. function scalePt2( pt, vec, size ) {
  21088. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21089. return vec.clone().multiplyScalar( size ).add( pt );
  21090. }
  21091. const vlen = vertices.length, flen = faces.length;
  21092. // Find directions for point movement
  21093. function getBevelVec( inPt, inPrev, inNext ) {
  21094. // computes for inPt the corresponding point inPt' on a new contour
  21095. // shifted by 1 unit (length of normalized vector) to the left
  21096. // if we walk along contour clockwise, this new contour is outside the old one
  21097. //
  21098. // inPt' is the intersection of the two lines parallel to the two
  21099. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21100. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21101. // good reading for geometry algorithms (here: line-line intersection)
  21102. // http://geomalgorithms.com/a05-_intersect-1.html
  21103. const v_prev_x = inPt.x - inPrev.x,
  21104. v_prev_y = inPt.y - inPrev.y;
  21105. const v_next_x = inNext.x - inPt.x,
  21106. v_next_y = inNext.y - inPt.y;
  21107. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21108. // check for collinear edges
  21109. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21110. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21111. // not collinear
  21112. // length of vectors for normalizing
  21113. const v_prev_len = Math.sqrt( v_prev_lensq );
  21114. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21115. // shift adjacent points by unit vectors to the left
  21116. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21117. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21118. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21119. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21120. // scaling factor for v_prev to intersection point
  21121. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21122. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21123. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21124. // vector from inPt to intersection point
  21125. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21126. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21127. // Don't normalize!, otherwise sharp corners become ugly
  21128. // but prevent crazy spikes
  21129. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21130. if ( v_trans_lensq <= 2 ) {
  21131. return new Vector2( v_trans_x, v_trans_y );
  21132. } else {
  21133. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21134. }
  21135. } else {
  21136. // handle special case of collinear edges
  21137. let direction_eq = false; // assumes: opposite
  21138. if ( v_prev_x > Number.EPSILON ) {
  21139. if ( v_next_x > Number.EPSILON ) {
  21140. direction_eq = true;
  21141. }
  21142. } else {
  21143. if ( v_prev_x < - Number.EPSILON ) {
  21144. if ( v_next_x < - Number.EPSILON ) {
  21145. direction_eq = true;
  21146. }
  21147. } else {
  21148. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21149. direction_eq = true;
  21150. }
  21151. }
  21152. }
  21153. if ( direction_eq ) {
  21154. // console.log("Warning: lines are a straight sequence");
  21155. v_trans_x = - v_prev_y;
  21156. v_trans_y = v_prev_x;
  21157. shrink_by = Math.sqrt( v_prev_lensq );
  21158. } else {
  21159. // console.log("Warning: lines are a straight spike");
  21160. v_trans_x = v_prev_x;
  21161. v_trans_y = v_prev_y;
  21162. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21163. }
  21164. }
  21165. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21166. }
  21167. const contourMovements = [];
  21168. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21169. if ( j === il ) j = 0;
  21170. if ( k === il ) k = 0;
  21171. // (j)---(i)---(k)
  21172. // console.log('i,j,k', i, j , k)
  21173. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21174. }
  21175. const holesMovements = [];
  21176. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21177. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21178. const ahole = holes[ h ];
  21179. oneHoleMovements = [];
  21180. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21181. if ( j === il ) j = 0;
  21182. if ( k === il ) k = 0;
  21183. // (j)---(i)---(k)
  21184. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21185. }
  21186. holesMovements.push( oneHoleMovements );
  21187. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21188. }
  21189. // Loop bevelSegments, 1 for the front, 1 for the back
  21190. for ( let b = 0; b < bevelSegments; b ++ ) {
  21191. //for ( b = bevelSegments; b > 0; b -- ) {
  21192. const t = b / bevelSegments;
  21193. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21194. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21195. // contract shape
  21196. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21197. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21198. v( vert.x, vert.y, - z );
  21199. }
  21200. // expand holes
  21201. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21202. const ahole = holes[ h ];
  21203. oneHoleMovements = holesMovements[ h ];
  21204. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21205. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21206. v( vert.x, vert.y, - z );
  21207. }
  21208. }
  21209. }
  21210. const bs = bevelSize + bevelOffset;
  21211. // Back facing vertices
  21212. for ( let i = 0; i < vlen; i ++ ) {
  21213. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21214. if ( ! extrudeByPath ) {
  21215. v( vert.x, vert.y, 0 );
  21216. } else {
  21217. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21218. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21219. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21220. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21221. v( position2.x, position2.y, position2.z );
  21222. }
  21223. }
  21224. // Add stepped vertices...
  21225. // Including front facing vertices
  21226. for ( let s = 1; s <= steps; s ++ ) {
  21227. for ( let i = 0; i < vlen; i ++ ) {
  21228. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21229. if ( ! extrudeByPath ) {
  21230. v( vert.x, vert.y, depth / steps * s );
  21231. } else {
  21232. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21233. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21234. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21235. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21236. v( position2.x, position2.y, position2.z );
  21237. }
  21238. }
  21239. }
  21240. // Add bevel segments planes
  21241. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21242. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21243. const t = b / bevelSegments;
  21244. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21245. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21246. // contract shape
  21247. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21248. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21249. v( vert.x, vert.y, depth + z );
  21250. }
  21251. // expand holes
  21252. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21253. const ahole = holes[ h ];
  21254. oneHoleMovements = holesMovements[ h ];
  21255. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21256. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21257. if ( ! extrudeByPath ) {
  21258. v( vert.x, vert.y, depth + z );
  21259. } else {
  21260. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21261. }
  21262. }
  21263. }
  21264. }
  21265. /* Faces */
  21266. // Top and bottom faces
  21267. buildLidFaces();
  21268. // Sides faces
  21269. buildSideFaces();
  21270. ///// Internal functions
  21271. function buildLidFaces() {
  21272. const start = verticesArray.length / 3;
  21273. if ( bevelEnabled ) {
  21274. let layer = 0; // steps + 1
  21275. let offset = vlen * layer;
  21276. // Bottom faces
  21277. for ( let i = 0; i < flen; i ++ ) {
  21278. const face = faces[ i ];
  21279. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21280. }
  21281. layer = steps + bevelSegments * 2;
  21282. offset = vlen * layer;
  21283. // Top faces
  21284. for ( let i = 0; i < flen; i ++ ) {
  21285. const face = faces[ i ];
  21286. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21287. }
  21288. } else {
  21289. // Bottom faces
  21290. for ( let i = 0; i < flen; i ++ ) {
  21291. const face = faces[ i ];
  21292. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21293. }
  21294. // Top faces
  21295. for ( let i = 0; i < flen; i ++ ) {
  21296. const face = faces[ i ];
  21297. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21298. }
  21299. }
  21300. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21301. }
  21302. // Create faces for the z-sides of the shape
  21303. function buildSideFaces() {
  21304. const start = verticesArray.length / 3;
  21305. let layeroffset = 0;
  21306. sidewalls( contour, layeroffset );
  21307. layeroffset += contour.length;
  21308. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21309. const ahole = holes[ h ];
  21310. sidewalls( ahole, layeroffset );
  21311. //, true
  21312. layeroffset += ahole.length;
  21313. }
  21314. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21315. }
  21316. function sidewalls( contour, layeroffset ) {
  21317. let i = contour.length;
  21318. while ( -- i >= 0 ) {
  21319. const j = i;
  21320. let k = i - 1;
  21321. if ( k < 0 ) k = contour.length - 1;
  21322. //console.log('b', i,j, i-1, k,vertices.length);
  21323. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21324. const slen1 = vlen * s;
  21325. const slen2 = vlen * ( s + 1 );
  21326. const a = layeroffset + j + slen1,
  21327. b = layeroffset + k + slen1,
  21328. c = layeroffset + k + slen2,
  21329. d = layeroffset + j + slen2;
  21330. f4( a, b, c, d );
  21331. }
  21332. }
  21333. }
  21334. function v( x, y, z ) {
  21335. placeholder.push( x );
  21336. placeholder.push( y );
  21337. placeholder.push( z );
  21338. }
  21339. function f3( a, b, c ) {
  21340. addVertex( a );
  21341. addVertex( b );
  21342. addVertex( c );
  21343. const nextIndex = verticesArray.length / 3;
  21344. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21345. addUV( uvs[ 0 ] );
  21346. addUV( uvs[ 1 ] );
  21347. addUV( uvs[ 2 ] );
  21348. }
  21349. function f4( a, b, c, d ) {
  21350. addVertex( a );
  21351. addVertex( b );
  21352. addVertex( d );
  21353. addVertex( b );
  21354. addVertex( c );
  21355. addVertex( d );
  21356. const nextIndex = verticesArray.length / 3;
  21357. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21358. addUV( uvs[ 0 ] );
  21359. addUV( uvs[ 1 ] );
  21360. addUV( uvs[ 3 ] );
  21361. addUV( uvs[ 1 ] );
  21362. addUV( uvs[ 2 ] );
  21363. addUV( uvs[ 3 ] );
  21364. }
  21365. function addVertex( index ) {
  21366. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21367. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21368. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21369. }
  21370. function addUV( vector2 ) {
  21371. uvArray.push( vector2.x );
  21372. uvArray.push( vector2.y );
  21373. }
  21374. }
  21375. }
  21376. toJSON() {
  21377. const data = super.toJSON();
  21378. const shapes = this.parameters.shapes;
  21379. const options = this.parameters.options;
  21380. return toJSON$1( shapes, options, data );
  21381. }
  21382. static fromJSON( data, shapes ) {
  21383. const geometryShapes = [];
  21384. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21385. const shape = shapes[ data.shapes[ j ] ];
  21386. geometryShapes.push( shape );
  21387. }
  21388. const extrudePath = data.options.extrudePath;
  21389. if ( extrudePath !== undefined ) {
  21390. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21391. }
  21392. return new ExtrudeGeometry( geometryShapes, data.options );
  21393. }
  21394. }
  21395. const WorldUVGenerator = {
  21396. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21397. const a_x = vertices[ indexA * 3 ];
  21398. const a_y = vertices[ indexA * 3 + 1 ];
  21399. const b_x = vertices[ indexB * 3 ];
  21400. const b_y = vertices[ indexB * 3 + 1 ];
  21401. const c_x = vertices[ indexC * 3 ];
  21402. const c_y = vertices[ indexC * 3 + 1 ];
  21403. return [
  21404. new Vector2( a_x, a_y ),
  21405. new Vector2( b_x, b_y ),
  21406. new Vector2( c_x, c_y )
  21407. ];
  21408. },
  21409. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21410. const a_x = vertices[ indexA * 3 ];
  21411. const a_y = vertices[ indexA * 3 + 1 ];
  21412. const a_z = vertices[ indexA * 3 + 2 ];
  21413. const b_x = vertices[ indexB * 3 ];
  21414. const b_y = vertices[ indexB * 3 + 1 ];
  21415. const b_z = vertices[ indexB * 3 + 2 ];
  21416. const c_x = vertices[ indexC * 3 ];
  21417. const c_y = vertices[ indexC * 3 + 1 ];
  21418. const c_z = vertices[ indexC * 3 + 2 ];
  21419. const d_x = vertices[ indexD * 3 ];
  21420. const d_y = vertices[ indexD * 3 + 1 ];
  21421. const d_z = vertices[ indexD * 3 + 2 ];
  21422. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21423. return [
  21424. new Vector2( a_x, 1 - a_z ),
  21425. new Vector2( b_x, 1 - b_z ),
  21426. new Vector2( c_x, 1 - c_z ),
  21427. new Vector2( d_x, 1 - d_z )
  21428. ];
  21429. } else {
  21430. return [
  21431. new Vector2( a_y, 1 - a_z ),
  21432. new Vector2( b_y, 1 - b_z ),
  21433. new Vector2( c_y, 1 - c_z ),
  21434. new Vector2( d_y, 1 - d_z )
  21435. ];
  21436. }
  21437. }
  21438. };
  21439. function toJSON$1( shapes, options, data ) {
  21440. data.shapes = [];
  21441. if ( Array.isArray( shapes ) ) {
  21442. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21443. const shape = shapes[ i ];
  21444. data.shapes.push( shape.uuid );
  21445. }
  21446. } else {
  21447. data.shapes.push( shapes.uuid );
  21448. }
  21449. data.options = Object.assign( {}, options );
  21450. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21451. return data;
  21452. }
  21453. class IcosahedronGeometry extends PolyhedronGeometry {
  21454. constructor( radius = 1, detail = 0 ) {
  21455. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21456. const vertices = [
  21457. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21458. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21459. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21460. ];
  21461. const indices = [
  21462. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21463. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21464. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21465. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21466. ];
  21467. super( vertices, indices, radius, detail );
  21468. this.type = 'IcosahedronGeometry';
  21469. this.parameters = {
  21470. radius: radius,
  21471. detail: detail
  21472. };
  21473. }
  21474. static fromJSON( data ) {
  21475. return new IcosahedronGeometry( data.radius, data.detail );
  21476. }
  21477. }
  21478. class OctahedronGeometry extends PolyhedronGeometry {
  21479. constructor( radius = 1, detail = 0 ) {
  21480. const vertices = [
  21481. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21482. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21483. ];
  21484. const indices = [
  21485. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21486. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21487. 1, 3, 4, 1, 4, 2
  21488. ];
  21489. super( vertices, indices, radius, detail );
  21490. this.type = 'OctahedronGeometry';
  21491. this.parameters = {
  21492. radius: radius,
  21493. detail: detail
  21494. };
  21495. }
  21496. static fromJSON( data ) {
  21497. return new OctahedronGeometry( data.radius, data.detail );
  21498. }
  21499. }
  21500. class RingGeometry extends BufferGeometry {
  21501. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21502. super();
  21503. this.type = 'RingGeometry';
  21504. this.parameters = {
  21505. innerRadius: innerRadius,
  21506. outerRadius: outerRadius,
  21507. thetaSegments: thetaSegments,
  21508. phiSegments: phiSegments,
  21509. thetaStart: thetaStart,
  21510. thetaLength: thetaLength
  21511. };
  21512. thetaSegments = Math.max( 3, thetaSegments );
  21513. phiSegments = Math.max( 1, phiSegments );
  21514. // buffers
  21515. const indices = [];
  21516. const vertices = [];
  21517. const normals = [];
  21518. const uvs = [];
  21519. // some helper variables
  21520. let radius = innerRadius;
  21521. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21522. const vertex = new Vector3();
  21523. const uv = new Vector2();
  21524. // generate vertices, normals and uvs
  21525. for ( let j = 0; j <= phiSegments; j ++ ) {
  21526. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21527. // values are generate from the inside of the ring to the outside
  21528. const segment = thetaStart + i / thetaSegments * thetaLength;
  21529. // vertex
  21530. vertex.x = radius * Math.cos( segment );
  21531. vertex.y = radius * Math.sin( segment );
  21532. vertices.push( vertex.x, vertex.y, vertex.z );
  21533. // normal
  21534. normals.push( 0, 0, 1 );
  21535. // uv
  21536. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21537. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21538. uvs.push( uv.x, uv.y );
  21539. }
  21540. // increase the radius for next row of vertices
  21541. radius += radiusStep;
  21542. }
  21543. // indices
  21544. for ( let j = 0; j < phiSegments; j ++ ) {
  21545. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21546. for ( let i = 0; i < thetaSegments; i ++ ) {
  21547. const segment = i + thetaSegmentLevel;
  21548. const a = segment;
  21549. const b = segment + thetaSegments + 1;
  21550. const c = segment + thetaSegments + 2;
  21551. const d = segment + 1;
  21552. // faces
  21553. indices.push( a, b, d );
  21554. indices.push( b, c, d );
  21555. }
  21556. }
  21557. // build geometry
  21558. this.setIndex( indices );
  21559. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21560. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21561. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21562. }
  21563. static fromJSON( data ) {
  21564. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21565. }
  21566. }
  21567. class ShapeGeometry extends BufferGeometry {
  21568. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21569. super();
  21570. this.type = 'ShapeGeometry';
  21571. this.parameters = {
  21572. shapes: shapes,
  21573. curveSegments: curveSegments
  21574. };
  21575. // buffers
  21576. const indices = [];
  21577. const vertices = [];
  21578. const normals = [];
  21579. const uvs = [];
  21580. // helper variables
  21581. let groupStart = 0;
  21582. let groupCount = 0;
  21583. // allow single and array values for "shapes" parameter
  21584. if ( Array.isArray( shapes ) === false ) {
  21585. addShape( shapes );
  21586. } else {
  21587. for ( let i = 0; i < shapes.length; i ++ ) {
  21588. addShape( shapes[ i ] );
  21589. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21590. groupStart += groupCount;
  21591. groupCount = 0;
  21592. }
  21593. }
  21594. // build geometry
  21595. this.setIndex( indices );
  21596. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21597. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21598. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21599. // helper functions
  21600. function addShape( shape ) {
  21601. const indexOffset = vertices.length / 3;
  21602. const points = shape.extractPoints( curveSegments );
  21603. let shapeVertices = points.shape;
  21604. const shapeHoles = points.holes;
  21605. // check direction of vertices
  21606. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21607. shapeVertices = shapeVertices.reverse();
  21608. }
  21609. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21610. const shapeHole = shapeHoles[ i ];
  21611. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21612. shapeHoles[ i ] = shapeHole.reverse();
  21613. }
  21614. }
  21615. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21616. // join vertices of inner and outer paths to a single array
  21617. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21618. const shapeHole = shapeHoles[ i ];
  21619. shapeVertices = shapeVertices.concat( shapeHole );
  21620. }
  21621. // vertices, normals, uvs
  21622. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21623. const vertex = shapeVertices[ i ];
  21624. vertices.push( vertex.x, vertex.y, 0 );
  21625. normals.push( 0, 0, 1 );
  21626. uvs.push( vertex.x, vertex.y ); // world uvs
  21627. }
  21628. // indices
  21629. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21630. const face = faces[ i ];
  21631. const a = face[ 0 ] + indexOffset;
  21632. const b = face[ 1 ] + indexOffset;
  21633. const c = face[ 2 ] + indexOffset;
  21634. indices.push( a, b, c );
  21635. groupCount += 3;
  21636. }
  21637. }
  21638. }
  21639. toJSON() {
  21640. const data = super.toJSON();
  21641. const shapes = this.parameters.shapes;
  21642. return toJSON( shapes, data );
  21643. }
  21644. static fromJSON( data, shapes ) {
  21645. const geometryShapes = [];
  21646. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21647. const shape = shapes[ data.shapes[ j ] ];
  21648. geometryShapes.push( shape );
  21649. }
  21650. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21651. }
  21652. }
  21653. function toJSON( shapes, data ) {
  21654. data.shapes = [];
  21655. if ( Array.isArray( shapes ) ) {
  21656. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21657. const shape = shapes[ i ];
  21658. data.shapes.push( shape.uuid );
  21659. }
  21660. } else {
  21661. data.shapes.push( shapes.uuid );
  21662. }
  21663. return data;
  21664. }
  21665. class SphereGeometry extends BufferGeometry {
  21666. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21667. super();
  21668. this.type = 'SphereGeometry';
  21669. this.parameters = {
  21670. radius: radius,
  21671. widthSegments: widthSegments,
  21672. heightSegments: heightSegments,
  21673. phiStart: phiStart,
  21674. phiLength: phiLength,
  21675. thetaStart: thetaStart,
  21676. thetaLength: thetaLength
  21677. };
  21678. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21679. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21680. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21681. let index = 0;
  21682. const grid = [];
  21683. const vertex = new Vector3();
  21684. const normal = new Vector3();
  21685. // buffers
  21686. const indices = [];
  21687. const vertices = [];
  21688. const normals = [];
  21689. const uvs = [];
  21690. // generate vertices, normals and uvs
  21691. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21692. const verticesRow = [];
  21693. const v = iy / heightSegments;
  21694. // special case for the poles
  21695. let uOffset = 0;
  21696. if ( iy == 0 && thetaStart == 0 ) {
  21697. uOffset = 0.5 / widthSegments;
  21698. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21699. uOffset = - 0.5 / widthSegments;
  21700. }
  21701. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21702. const u = ix / widthSegments;
  21703. // vertex
  21704. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21705. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21706. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21707. vertices.push( vertex.x, vertex.y, vertex.z );
  21708. // normal
  21709. normal.copy( vertex ).normalize();
  21710. normals.push( normal.x, normal.y, normal.z );
  21711. // uv
  21712. uvs.push( u + uOffset, 1 - v );
  21713. verticesRow.push( index ++ );
  21714. }
  21715. grid.push( verticesRow );
  21716. }
  21717. // indices
  21718. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21719. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21720. const a = grid[ iy ][ ix + 1 ];
  21721. const b = grid[ iy ][ ix ];
  21722. const c = grid[ iy + 1 ][ ix ];
  21723. const d = grid[ iy + 1 ][ ix + 1 ];
  21724. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21725. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21726. }
  21727. }
  21728. // build geometry
  21729. this.setIndex( indices );
  21730. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21731. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21732. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21733. }
  21734. static fromJSON( data ) {
  21735. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21736. }
  21737. }
  21738. class TetrahedronGeometry extends PolyhedronGeometry {
  21739. constructor( radius = 1, detail = 0 ) {
  21740. const vertices = [
  21741. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21742. ];
  21743. const indices = [
  21744. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21745. ];
  21746. super( vertices, indices, radius, detail );
  21747. this.type = 'TetrahedronGeometry';
  21748. this.parameters = {
  21749. radius: radius,
  21750. detail: detail
  21751. };
  21752. }
  21753. static fromJSON( data ) {
  21754. return new TetrahedronGeometry( data.radius, data.detail );
  21755. }
  21756. }
  21757. class TorusGeometry extends BufferGeometry {
  21758. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  21759. super();
  21760. this.type = 'TorusGeometry';
  21761. this.parameters = {
  21762. radius: radius,
  21763. tube: tube,
  21764. radialSegments: radialSegments,
  21765. tubularSegments: tubularSegments,
  21766. arc: arc
  21767. };
  21768. radialSegments = Math.floor( radialSegments );
  21769. tubularSegments = Math.floor( tubularSegments );
  21770. // buffers
  21771. const indices = [];
  21772. const vertices = [];
  21773. const normals = [];
  21774. const uvs = [];
  21775. // helper variables
  21776. const center = new Vector3();
  21777. const vertex = new Vector3();
  21778. const normal = new Vector3();
  21779. // generate vertices, normals and uvs
  21780. for ( let j = 0; j <= radialSegments; j ++ ) {
  21781. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21782. const u = i / tubularSegments * arc;
  21783. const v = j / radialSegments * Math.PI * 2;
  21784. // vertex
  21785. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21786. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21787. vertex.z = tube * Math.sin( v );
  21788. vertices.push( vertex.x, vertex.y, vertex.z );
  21789. // normal
  21790. center.x = radius * Math.cos( u );
  21791. center.y = radius * Math.sin( u );
  21792. normal.subVectors( vertex, center ).normalize();
  21793. normals.push( normal.x, normal.y, normal.z );
  21794. // uv
  21795. uvs.push( i / tubularSegments );
  21796. uvs.push( j / radialSegments );
  21797. }
  21798. }
  21799. // generate indices
  21800. for ( let j = 1; j <= radialSegments; j ++ ) {
  21801. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21802. // indices
  21803. const a = ( tubularSegments + 1 ) * j + i - 1;
  21804. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21805. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21806. const d = ( tubularSegments + 1 ) * j + i;
  21807. // faces
  21808. indices.push( a, b, d );
  21809. indices.push( b, c, d );
  21810. }
  21811. }
  21812. // build geometry
  21813. this.setIndex( indices );
  21814. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21815. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21816. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21817. }
  21818. static fromJSON( data ) {
  21819. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21820. }
  21821. }
  21822. class TorusKnotGeometry extends BufferGeometry {
  21823. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21824. super();
  21825. this.type = 'TorusKnotGeometry';
  21826. this.parameters = {
  21827. radius: radius,
  21828. tube: tube,
  21829. tubularSegments: tubularSegments,
  21830. radialSegments: radialSegments,
  21831. p: p,
  21832. q: q
  21833. };
  21834. tubularSegments = Math.floor( tubularSegments );
  21835. radialSegments = Math.floor( radialSegments );
  21836. // buffers
  21837. const indices = [];
  21838. const vertices = [];
  21839. const normals = [];
  21840. const uvs = [];
  21841. // helper variables
  21842. const vertex = new Vector3();
  21843. const normal = new Vector3();
  21844. const P1 = new Vector3();
  21845. const P2 = new Vector3();
  21846. const B = new Vector3();
  21847. const T = new Vector3();
  21848. const N = new Vector3();
  21849. // generate vertices, normals and uvs
  21850. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21851. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21852. const u = i / tubularSegments * p * Math.PI * 2;
  21853. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21854. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21855. calculatePositionOnCurve( u, p, q, radius, P1 );
  21856. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21857. // calculate orthonormal basis
  21858. T.subVectors( P2, P1 );
  21859. N.addVectors( P2, P1 );
  21860. B.crossVectors( T, N );
  21861. N.crossVectors( B, T );
  21862. // normalize B, N. T can be ignored, we don't use it
  21863. B.normalize();
  21864. N.normalize();
  21865. for ( let j = 0; j <= radialSegments; ++ j ) {
  21866. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21867. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21868. const v = j / radialSegments * Math.PI * 2;
  21869. const cx = - tube * Math.cos( v );
  21870. const cy = tube * Math.sin( v );
  21871. // now calculate the final vertex position.
  21872. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21873. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21874. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21875. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21876. vertices.push( vertex.x, vertex.y, vertex.z );
  21877. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21878. normal.subVectors( vertex, P1 ).normalize();
  21879. normals.push( normal.x, normal.y, normal.z );
  21880. // uv
  21881. uvs.push( i / tubularSegments );
  21882. uvs.push( j / radialSegments );
  21883. }
  21884. }
  21885. // generate indices
  21886. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21887. for ( let i = 1; i <= radialSegments; i ++ ) {
  21888. // indices
  21889. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21890. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21891. const c = ( radialSegments + 1 ) * j + i;
  21892. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21893. // faces
  21894. indices.push( a, b, d );
  21895. indices.push( b, c, d );
  21896. }
  21897. }
  21898. // build geometry
  21899. this.setIndex( indices );
  21900. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21901. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21902. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21903. // this function calculates the current position on the torus curve
  21904. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21905. const cu = Math.cos( u );
  21906. const su = Math.sin( u );
  21907. const quOverP = q / p * u;
  21908. const cs = Math.cos( quOverP );
  21909. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21910. position.y = radius * ( 2 + cs ) * su * 0.5;
  21911. position.z = radius * Math.sin( quOverP ) * 0.5;
  21912. }
  21913. }
  21914. static fromJSON( data ) {
  21915. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21916. }
  21917. }
  21918. class TubeGeometry extends BufferGeometry {
  21919. 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 ) {
  21920. super();
  21921. this.type = 'TubeGeometry';
  21922. this.parameters = {
  21923. path: path,
  21924. tubularSegments: tubularSegments,
  21925. radius: radius,
  21926. radialSegments: radialSegments,
  21927. closed: closed
  21928. };
  21929. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21930. // expose internals
  21931. this.tangents = frames.tangents;
  21932. this.normals = frames.normals;
  21933. this.binormals = frames.binormals;
  21934. // helper variables
  21935. const vertex = new Vector3();
  21936. const normal = new Vector3();
  21937. const uv = new Vector2();
  21938. let P = new Vector3();
  21939. // buffer
  21940. const vertices = [];
  21941. const normals = [];
  21942. const uvs = [];
  21943. const indices = [];
  21944. // create buffer data
  21945. generateBufferData();
  21946. // build geometry
  21947. this.setIndex( indices );
  21948. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21949. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21950. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21951. // functions
  21952. function generateBufferData() {
  21953. for ( let i = 0; i < tubularSegments; i ++ ) {
  21954. generateSegment( i );
  21955. }
  21956. // if the geometry is not closed, generate the last row of vertices and normals
  21957. // at the regular position on the given path
  21958. //
  21959. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21960. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21961. // uvs are generated in a separate function.
  21962. // this makes it easy compute correct values for closed geometries
  21963. generateUVs();
  21964. // finally create faces
  21965. generateIndices();
  21966. }
  21967. function generateSegment( i ) {
  21968. // we use getPointAt to sample evenly distributed points from the given path
  21969. P = path.getPointAt( i / tubularSegments, P );
  21970. // retrieve corresponding normal and binormal
  21971. const N = frames.normals[ i ];
  21972. const B = frames.binormals[ i ];
  21973. // generate normals and vertices for the current segment
  21974. for ( let j = 0; j <= radialSegments; j ++ ) {
  21975. const v = j / radialSegments * Math.PI * 2;
  21976. const sin = Math.sin( v );
  21977. const cos = - Math.cos( v );
  21978. // normal
  21979. normal.x = ( cos * N.x + sin * B.x );
  21980. normal.y = ( cos * N.y + sin * B.y );
  21981. normal.z = ( cos * N.z + sin * B.z );
  21982. normal.normalize();
  21983. normals.push( normal.x, normal.y, normal.z );
  21984. // vertex
  21985. vertex.x = P.x + radius * normal.x;
  21986. vertex.y = P.y + radius * normal.y;
  21987. vertex.z = P.z + radius * normal.z;
  21988. vertices.push( vertex.x, vertex.y, vertex.z );
  21989. }
  21990. }
  21991. function generateIndices() {
  21992. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21993. for ( let i = 1; i <= radialSegments; i ++ ) {
  21994. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21995. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21996. const c = ( radialSegments + 1 ) * j + i;
  21997. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21998. // faces
  21999. indices.push( a, b, d );
  22000. indices.push( b, c, d );
  22001. }
  22002. }
  22003. }
  22004. function generateUVs() {
  22005. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22006. for ( let j = 0; j <= radialSegments; j ++ ) {
  22007. uv.x = i / tubularSegments;
  22008. uv.y = j / radialSegments;
  22009. uvs.push( uv.x, uv.y );
  22010. }
  22011. }
  22012. }
  22013. }
  22014. toJSON() {
  22015. const data = super.toJSON();
  22016. data.path = this.parameters.path.toJSON();
  22017. return data;
  22018. }
  22019. static fromJSON( data ) {
  22020. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22021. // User defined curves or instances of CurvePath will not be deserialized.
  22022. return new TubeGeometry(
  22023. new Curves[ data.path.type ]().fromJSON( data.path ),
  22024. data.tubularSegments,
  22025. data.radius,
  22026. data.radialSegments,
  22027. data.closed
  22028. );
  22029. }
  22030. }
  22031. class WireframeGeometry extends BufferGeometry {
  22032. constructor( geometry = null ) {
  22033. super();
  22034. this.type = 'WireframeGeometry';
  22035. this.parameters = {
  22036. geometry: geometry
  22037. };
  22038. if ( geometry !== null ) {
  22039. // buffer
  22040. const vertices = [];
  22041. const edges = new Set();
  22042. // helper variables
  22043. const start = new Vector3();
  22044. const end = new Vector3();
  22045. if ( geometry.index !== null ) {
  22046. // indexed BufferGeometry
  22047. const position = geometry.attributes.position;
  22048. const indices = geometry.index;
  22049. let groups = geometry.groups;
  22050. if ( groups.length === 0 ) {
  22051. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22052. }
  22053. // create a data structure that contains all edges without duplicates
  22054. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22055. const group = groups[ o ];
  22056. const groupStart = group.start;
  22057. const groupCount = group.count;
  22058. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22059. for ( let j = 0; j < 3; j ++ ) {
  22060. const index1 = indices.getX( i + j );
  22061. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22062. start.fromBufferAttribute( position, index1 );
  22063. end.fromBufferAttribute( position, index2 );
  22064. if ( isUniqueEdge( start, end, edges ) === true ) {
  22065. vertices.push( start.x, start.y, start.z );
  22066. vertices.push( end.x, end.y, end.z );
  22067. }
  22068. }
  22069. }
  22070. }
  22071. } else {
  22072. // non-indexed BufferGeometry
  22073. const position = geometry.attributes.position;
  22074. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22075. for ( let j = 0; j < 3; j ++ ) {
  22076. // three edges per triangle, an edge is represented as (index1, index2)
  22077. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22078. const index1 = 3 * i + j;
  22079. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22080. start.fromBufferAttribute( position, index1 );
  22081. end.fromBufferAttribute( position, index2 );
  22082. if ( isUniqueEdge( start, end, edges ) === true ) {
  22083. vertices.push( start.x, start.y, start.z );
  22084. vertices.push( end.x, end.y, end.z );
  22085. }
  22086. }
  22087. }
  22088. }
  22089. // build geometry
  22090. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22091. }
  22092. }
  22093. }
  22094. function isUniqueEdge( start, end, edges ) {
  22095. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22096. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22097. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22098. return false;
  22099. } else {
  22100. edges.add( hash1 );
  22101. edges.add( hash2 );
  22102. return true;
  22103. }
  22104. }
  22105. var Geometries = /*#__PURE__*/Object.freeze({
  22106. __proto__: null,
  22107. BoxGeometry: BoxGeometry,
  22108. CapsuleGeometry: CapsuleGeometry,
  22109. CircleGeometry: CircleGeometry,
  22110. ConeGeometry: ConeGeometry,
  22111. CylinderGeometry: CylinderGeometry,
  22112. DodecahedronGeometry: DodecahedronGeometry,
  22113. EdgesGeometry: EdgesGeometry,
  22114. ExtrudeGeometry: ExtrudeGeometry,
  22115. IcosahedronGeometry: IcosahedronGeometry,
  22116. LatheGeometry: LatheGeometry,
  22117. OctahedronGeometry: OctahedronGeometry,
  22118. PlaneGeometry: PlaneGeometry,
  22119. PolyhedronGeometry: PolyhedronGeometry,
  22120. RingGeometry: RingGeometry,
  22121. ShapeGeometry: ShapeGeometry,
  22122. SphereGeometry: SphereGeometry,
  22123. TetrahedronGeometry: TetrahedronGeometry,
  22124. TorusGeometry: TorusGeometry,
  22125. TorusKnotGeometry: TorusKnotGeometry,
  22126. TubeGeometry: TubeGeometry,
  22127. WireframeGeometry: WireframeGeometry
  22128. });
  22129. class ShadowMaterial extends Material {
  22130. constructor( parameters ) {
  22131. super();
  22132. this.isShadowMaterial = true;
  22133. this.type = 'ShadowMaterial';
  22134. this.color = new Color( 0x000000 );
  22135. this.transparent = true;
  22136. this.fog = true;
  22137. this.setValues( parameters );
  22138. }
  22139. copy( source ) {
  22140. super.copy( source );
  22141. this.color.copy( source.color );
  22142. this.fog = source.fog;
  22143. return this;
  22144. }
  22145. }
  22146. class RawShaderMaterial extends ShaderMaterial {
  22147. constructor( parameters ) {
  22148. super( parameters );
  22149. this.isRawShaderMaterial = true;
  22150. this.type = 'RawShaderMaterial';
  22151. }
  22152. }
  22153. class MeshStandardMaterial extends Material {
  22154. constructor( parameters ) {
  22155. super();
  22156. this.isMeshStandardMaterial = true;
  22157. this.defines = { 'STANDARD': '' };
  22158. this.type = 'MeshStandardMaterial';
  22159. this.color = new Color( 0xffffff ); // diffuse
  22160. this.roughness = 1.0;
  22161. this.metalness = 0.0;
  22162. this.map = null;
  22163. this.lightMap = null;
  22164. this.lightMapIntensity = 1.0;
  22165. this.aoMap = null;
  22166. this.aoMapIntensity = 1.0;
  22167. this.emissive = new Color( 0x000000 );
  22168. this.emissiveIntensity = 1.0;
  22169. this.emissiveMap = null;
  22170. this.bumpMap = null;
  22171. this.bumpScale = 1;
  22172. this.normalMap = null;
  22173. this.normalMapType = TangentSpaceNormalMap;
  22174. this.normalScale = new Vector2( 1, 1 );
  22175. this.displacementMap = null;
  22176. this.displacementScale = 1;
  22177. this.displacementBias = 0;
  22178. this.roughnessMap = null;
  22179. this.metalnessMap = null;
  22180. this.alphaMap = null;
  22181. this.envMap = null;
  22182. this.envMapIntensity = 1.0;
  22183. this.wireframe = false;
  22184. this.wireframeLinewidth = 1;
  22185. this.wireframeLinecap = 'round';
  22186. this.wireframeLinejoin = 'round';
  22187. this.flatShading = false;
  22188. this.fog = true;
  22189. this.setValues( parameters );
  22190. }
  22191. copy( source ) {
  22192. super.copy( source );
  22193. this.defines = { 'STANDARD': '' };
  22194. this.color.copy( source.color );
  22195. this.roughness = source.roughness;
  22196. this.metalness = source.metalness;
  22197. this.map = source.map;
  22198. this.lightMap = source.lightMap;
  22199. this.lightMapIntensity = source.lightMapIntensity;
  22200. this.aoMap = source.aoMap;
  22201. this.aoMapIntensity = source.aoMapIntensity;
  22202. this.emissive.copy( source.emissive );
  22203. this.emissiveMap = source.emissiveMap;
  22204. this.emissiveIntensity = source.emissiveIntensity;
  22205. this.bumpMap = source.bumpMap;
  22206. this.bumpScale = source.bumpScale;
  22207. this.normalMap = source.normalMap;
  22208. this.normalMapType = source.normalMapType;
  22209. this.normalScale.copy( source.normalScale );
  22210. this.displacementMap = source.displacementMap;
  22211. this.displacementScale = source.displacementScale;
  22212. this.displacementBias = source.displacementBias;
  22213. this.roughnessMap = source.roughnessMap;
  22214. this.metalnessMap = source.metalnessMap;
  22215. this.alphaMap = source.alphaMap;
  22216. this.envMap = source.envMap;
  22217. this.envMapIntensity = source.envMapIntensity;
  22218. this.wireframe = source.wireframe;
  22219. this.wireframeLinewidth = source.wireframeLinewidth;
  22220. this.wireframeLinecap = source.wireframeLinecap;
  22221. this.wireframeLinejoin = source.wireframeLinejoin;
  22222. this.flatShading = source.flatShading;
  22223. this.fog = source.fog;
  22224. return this;
  22225. }
  22226. }
  22227. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22228. constructor( parameters ) {
  22229. super();
  22230. this.isMeshPhysicalMaterial = true;
  22231. this.defines = {
  22232. 'STANDARD': '',
  22233. 'PHYSICAL': ''
  22234. };
  22235. this.type = 'MeshPhysicalMaterial';
  22236. this.clearcoatMap = null;
  22237. this.clearcoatRoughness = 0.0;
  22238. this.clearcoatRoughnessMap = null;
  22239. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22240. this.clearcoatNormalMap = null;
  22241. this.ior = 1.5;
  22242. Object.defineProperty( this, 'reflectivity', {
  22243. get: function () {
  22244. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22245. },
  22246. set: function ( reflectivity ) {
  22247. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22248. }
  22249. } );
  22250. this.iridescenceMap = null;
  22251. this.iridescenceIOR = 1.3;
  22252. this.iridescenceThicknessRange = [ 100, 400 ];
  22253. this.iridescenceThicknessMap = null;
  22254. this.sheenColor = new Color( 0x000000 );
  22255. this.sheenColorMap = null;
  22256. this.sheenRoughness = 1.0;
  22257. this.sheenRoughnessMap = null;
  22258. this.transmissionMap = null;
  22259. this.thickness = 0;
  22260. this.thicknessMap = null;
  22261. this.attenuationDistance = Infinity;
  22262. this.attenuationColor = new Color( 1, 1, 1 );
  22263. this.specularIntensity = 1.0;
  22264. this.specularIntensityMap = null;
  22265. this.specularColor = new Color( 1, 1, 1 );
  22266. this.specularColorMap = null;
  22267. this._sheen = 0.0;
  22268. this._clearcoat = 0;
  22269. this._iridescence = 0;
  22270. this._transmission = 0;
  22271. this.setValues( parameters );
  22272. }
  22273. get sheen() {
  22274. return this._sheen;
  22275. }
  22276. set sheen( value ) {
  22277. if ( this._sheen > 0 !== value > 0 ) {
  22278. this.version ++;
  22279. }
  22280. this._sheen = value;
  22281. }
  22282. get clearcoat() {
  22283. return this._clearcoat;
  22284. }
  22285. set clearcoat( value ) {
  22286. if ( this._clearcoat > 0 !== value > 0 ) {
  22287. this.version ++;
  22288. }
  22289. this._clearcoat = value;
  22290. }
  22291. get iridescence() {
  22292. return this._iridescence;
  22293. }
  22294. set iridescence( value ) {
  22295. if ( this._iridescence > 0 !== value > 0 ) {
  22296. this.version ++;
  22297. }
  22298. this._iridescence = value;
  22299. }
  22300. get transmission() {
  22301. return this._transmission;
  22302. }
  22303. set transmission( value ) {
  22304. if ( this._transmission > 0 !== value > 0 ) {
  22305. this.version ++;
  22306. }
  22307. this._transmission = value;
  22308. }
  22309. copy( source ) {
  22310. super.copy( source );
  22311. this.defines = {
  22312. 'STANDARD': '',
  22313. 'PHYSICAL': ''
  22314. };
  22315. this.clearcoat = source.clearcoat;
  22316. this.clearcoatMap = source.clearcoatMap;
  22317. this.clearcoatRoughness = source.clearcoatRoughness;
  22318. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22319. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22320. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22321. this.ior = source.ior;
  22322. this.iridescence = source.iridescence;
  22323. this.iridescenceMap = source.iridescenceMap;
  22324. this.iridescenceIOR = source.iridescenceIOR;
  22325. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22326. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22327. this.sheen = source.sheen;
  22328. this.sheenColor.copy( source.sheenColor );
  22329. this.sheenColorMap = source.sheenColorMap;
  22330. this.sheenRoughness = source.sheenRoughness;
  22331. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22332. this.transmission = source.transmission;
  22333. this.transmissionMap = source.transmissionMap;
  22334. this.thickness = source.thickness;
  22335. this.thicknessMap = source.thicknessMap;
  22336. this.attenuationDistance = source.attenuationDistance;
  22337. this.attenuationColor.copy( source.attenuationColor );
  22338. this.specularIntensity = source.specularIntensity;
  22339. this.specularIntensityMap = source.specularIntensityMap;
  22340. this.specularColor.copy( source.specularColor );
  22341. this.specularColorMap = source.specularColorMap;
  22342. return this;
  22343. }
  22344. }
  22345. class MeshPhongMaterial extends Material {
  22346. constructor( parameters ) {
  22347. super();
  22348. this.isMeshPhongMaterial = true;
  22349. this.type = 'MeshPhongMaterial';
  22350. this.color = new Color( 0xffffff ); // diffuse
  22351. this.specular = new Color( 0x111111 );
  22352. this.shininess = 30;
  22353. this.map = null;
  22354. this.lightMap = null;
  22355. this.lightMapIntensity = 1.0;
  22356. this.aoMap = null;
  22357. this.aoMapIntensity = 1.0;
  22358. this.emissive = new Color( 0x000000 );
  22359. this.emissiveIntensity = 1.0;
  22360. this.emissiveMap = null;
  22361. this.bumpMap = null;
  22362. this.bumpScale = 1;
  22363. this.normalMap = null;
  22364. this.normalMapType = TangentSpaceNormalMap;
  22365. this.normalScale = new Vector2( 1, 1 );
  22366. this.displacementMap = null;
  22367. this.displacementScale = 1;
  22368. this.displacementBias = 0;
  22369. this.specularMap = null;
  22370. this.alphaMap = null;
  22371. this.envMap = null;
  22372. this.combine = MultiplyOperation;
  22373. this.reflectivity = 1;
  22374. this.refractionRatio = 0.98;
  22375. this.wireframe = false;
  22376. this.wireframeLinewidth = 1;
  22377. this.wireframeLinecap = 'round';
  22378. this.wireframeLinejoin = 'round';
  22379. this.flatShading = false;
  22380. this.fog = true;
  22381. this.setValues( parameters );
  22382. }
  22383. copy( source ) {
  22384. super.copy( source );
  22385. this.color.copy( source.color );
  22386. this.specular.copy( source.specular );
  22387. this.shininess = source.shininess;
  22388. this.map = source.map;
  22389. this.lightMap = source.lightMap;
  22390. this.lightMapIntensity = source.lightMapIntensity;
  22391. this.aoMap = source.aoMap;
  22392. this.aoMapIntensity = source.aoMapIntensity;
  22393. this.emissive.copy( source.emissive );
  22394. this.emissiveMap = source.emissiveMap;
  22395. this.emissiveIntensity = source.emissiveIntensity;
  22396. this.bumpMap = source.bumpMap;
  22397. this.bumpScale = source.bumpScale;
  22398. this.normalMap = source.normalMap;
  22399. this.normalMapType = source.normalMapType;
  22400. this.normalScale.copy( source.normalScale );
  22401. this.displacementMap = source.displacementMap;
  22402. this.displacementScale = source.displacementScale;
  22403. this.displacementBias = source.displacementBias;
  22404. this.specularMap = source.specularMap;
  22405. this.alphaMap = source.alphaMap;
  22406. this.envMap = source.envMap;
  22407. this.combine = source.combine;
  22408. this.reflectivity = source.reflectivity;
  22409. this.refractionRatio = source.refractionRatio;
  22410. this.wireframe = source.wireframe;
  22411. this.wireframeLinewidth = source.wireframeLinewidth;
  22412. this.wireframeLinecap = source.wireframeLinecap;
  22413. this.wireframeLinejoin = source.wireframeLinejoin;
  22414. this.flatShading = source.flatShading;
  22415. this.fog = source.fog;
  22416. return this;
  22417. }
  22418. }
  22419. class MeshToonMaterial extends Material {
  22420. constructor( parameters ) {
  22421. super();
  22422. this.isMeshToonMaterial = true;
  22423. this.defines = { 'TOON': '' };
  22424. this.type = 'MeshToonMaterial';
  22425. this.color = new Color( 0xffffff );
  22426. this.map = null;
  22427. this.gradientMap = null;
  22428. this.lightMap = null;
  22429. this.lightMapIntensity = 1.0;
  22430. this.aoMap = null;
  22431. this.aoMapIntensity = 1.0;
  22432. this.emissive = new Color( 0x000000 );
  22433. this.emissiveIntensity = 1.0;
  22434. this.emissiveMap = null;
  22435. this.bumpMap = null;
  22436. this.bumpScale = 1;
  22437. this.normalMap = null;
  22438. this.normalMapType = TangentSpaceNormalMap;
  22439. this.normalScale = new Vector2( 1, 1 );
  22440. this.displacementMap = null;
  22441. this.displacementScale = 1;
  22442. this.displacementBias = 0;
  22443. this.alphaMap = null;
  22444. this.wireframe = false;
  22445. this.wireframeLinewidth = 1;
  22446. this.wireframeLinecap = 'round';
  22447. this.wireframeLinejoin = 'round';
  22448. this.fog = true;
  22449. this.setValues( parameters );
  22450. }
  22451. copy( source ) {
  22452. super.copy( source );
  22453. this.color.copy( source.color );
  22454. this.map = source.map;
  22455. this.gradientMap = source.gradientMap;
  22456. this.lightMap = source.lightMap;
  22457. this.lightMapIntensity = source.lightMapIntensity;
  22458. this.aoMap = source.aoMap;
  22459. this.aoMapIntensity = source.aoMapIntensity;
  22460. this.emissive.copy( source.emissive );
  22461. this.emissiveMap = source.emissiveMap;
  22462. this.emissiveIntensity = source.emissiveIntensity;
  22463. this.bumpMap = source.bumpMap;
  22464. this.bumpScale = source.bumpScale;
  22465. this.normalMap = source.normalMap;
  22466. this.normalMapType = source.normalMapType;
  22467. this.normalScale.copy( source.normalScale );
  22468. this.displacementMap = source.displacementMap;
  22469. this.displacementScale = source.displacementScale;
  22470. this.displacementBias = source.displacementBias;
  22471. this.alphaMap = source.alphaMap;
  22472. this.wireframe = source.wireframe;
  22473. this.wireframeLinewidth = source.wireframeLinewidth;
  22474. this.wireframeLinecap = source.wireframeLinecap;
  22475. this.wireframeLinejoin = source.wireframeLinejoin;
  22476. this.fog = source.fog;
  22477. return this;
  22478. }
  22479. }
  22480. class MeshNormalMaterial extends Material {
  22481. constructor( parameters ) {
  22482. super();
  22483. this.isMeshNormalMaterial = true;
  22484. this.type = 'MeshNormalMaterial';
  22485. this.bumpMap = null;
  22486. this.bumpScale = 1;
  22487. this.normalMap = null;
  22488. this.normalMapType = TangentSpaceNormalMap;
  22489. this.normalScale = new Vector2( 1, 1 );
  22490. this.displacementMap = null;
  22491. this.displacementScale = 1;
  22492. this.displacementBias = 0;
  22493. this.wireframe = false;
  22494. this.wireframeLinewidth = 1;
  22495. this.flatShading = false;
  22496. this.setValues( parameters );
  22497. }
  22498. copy( source ) {
  22499. super.copy( source );
  22500. this.bumpMap = source.bumpMap;
  22501. this.bumpScale = source.bumpScale;
  22502. this.normalMap = source.normalMap;
  22503. this.normalMapType = source.normalMapType;
  22504. this.normalScale.copy( source.normalScale );
  22505. this.displacementMap = source.displacementMap;
  22506. this.displacementScale = source.displacementScale;
  22507. this.displacementBias = source.displacementBias;
  22508. this.wireframe = source.wireframe;
  22509. this.wireframeLinewidth = source.wireframeLinewidth;
  22510. this.flatShading = source.flatShading;
  22511. return this;
  22512. }
  22513. }
  22514. class MeshLambertMaterial extends Material {
  22515. constructor( parameters ) {
  22516. super();
  22517. this.isMeshLambertMaterial = true;
  22518. this.type = 'MeshLambertMaterial';
  22519. this.color = new Color( 0xffffff ); // diffuse
  22520. this.map = null;
  22521. this.lightMap = null;
  22522. this.lightMapIntensity = 1.0;
  22523. this.aoMap = null;
  22524. this.aoMapIntensity = 1.0;
  22525. this.emissive = new Color( 0x000000 );
  22526. this.emissiveIntensity = 1.0;
  22527. this.emissiveMap = null;
  22528. this.bumpMap = null;
  22529. this.bumpScale = 1;
  22530. this.normalMap = null;
  22531. this.normalMapType = TangentSpaceNormalMap;
  22532. this.normalScale = new Vector2( 1, 1 );
  22533. this.displacementMap = null;
  22534. this.displacementScale = 1;
  22535. this.displacementBias = 0;
  22536. this.specularMap = null;
  22537. this.alphaMap = null;
  22538. this.envMap = null;
  22539. this.combine = MultiplyOperation;
  22540. this.reflectivity = 1;
  22541. this.refractionRatio = 0.98;
  22542. this.wireframe = false;
  22543. this.wireframeLinewidth = 1;
  22544. this.wireframeLinecap = 'round';
  22545. this.wireframeLinejoin = 'round';
  22546. this.flatShading = false;
  22547. this.fog = true;
  22548. this.setValues( parameters );
  22549. }
  22550. copy( source ) {
  22551. super.copy( source );
  22552. this.color.copy( source.color );
  22553. this.map = source.map;
  22554. this.lightMap = source.lightMap;
  22555. this.lightMapIntensity = source.lightMapIntensity;
  22556. this.aoMap = source.aoMap;
  22557. this.aoMapIntensity = source.aoMapIntensity;
  22558. this.emissive.copy( source.emissive );
  22559. this.emissiveMap = source.emissiveMap;
  22560. this.emissiveIntensity = source.emissiveIntensity;
  22561. this.bumpMap = source.bumpMap;
  22562. this.bumpScale = source.bumpScale;
  22563. this.normalMap = source.normalMap;
  22564. this.normalMapType = source.normalMapType;
  22565. this.normalScale.copy( source.normalScale );
  22566. this.displacementMap = source.displacementMap;
  22567. this.displacementScale = source.displacementScale;
  22568. this.displacementBias = source.displacementBias;
  22569. this.specularMap = source.specularMap;
  22570. this.alphaMap = source.alphaMap;
  22571. this.envMap = source.envMap;
  22572. this.combine = source.combine;
  22573. this.reflectivity = source.reflectivity;
  22574. this.refractionRatio = source.refractionRatio;
  22575. this.wireframe = source.wireframe;
  22576. this.wireframeLinewidth = source.wireframeLinewidth;
  22577. this.wireframeLinecap = source.wireframeLinecap;
  22578. this.wireframeLinejoin = source.wireframeLinejoin;
  22579. this.flatShading = source.flatShading;
  22580. this.fog = source.fog;
  22581. return this;
  22582. }
  22583. }
  22584. class MeshMatcapMaterial extends Material {
  22585. constructor( parameters ) {
  22586. super();
  22587. this.isMeshMatcapMaterial = true;
  22588. this.defines = { 'MATCAP': '' };
  22589. this.type = 'MeshMatcapMaterial';
  22590. this.color = new Color( 0xffffff ); // diffuse
  22591. this.matcap = null;
  22592. this.map = null;
  22593. this.bumpMap = null;
  22594. this.bumpScale = 1;
  22595. this.normalMap = null;
  22596. this.normalMapType = TangentSpaceNormalMap;
  22597. this.normalScale = new Vector2( 1, 1 );
  22598. this.displacementMap = null;
  22599. this.displacementScale = 1;
  22600. this.displacementBias = 0;
  22601. this.alphaMap = null;
  22602. this.flatShading = false;
  22603. this.fog = true;
  22604. this.setValues( parameters );
  22605. }
  22606. copy( source ) {
  22607. super.copy( source );
  22608. this.defines = { 'MATCAP': '' };
  22609. this.color.copy( source.color );
  22610. this.matcap = source.matcap;
  22611. this.map = source.map;
  22612. this.bumpMap = source.bumpMap;
  22613. this.bumpScale = source.bumpScale;
  22614. this.normalMap = source.normalMap;
  22615. this.normalMapType = source.normalMapType;
  22616. this.normalScale.copy( source.normalScale );
  22617. this.displacementMap = source.displacementMap;
  22618. this.displacementScale = source.displacementScale;
  22619. this.displacementBias = source.displacementBias;
  22620. this.alphaMap = source.alphaMap;
  22621. this.flatShading = source.flatShading;
  22622. this.fog = source.fog;
  22623. return this;
  22624. }
  22625. }
  22626. class LineDashedMaterial extends LineBasicMaterial {
  22627. constructor( parameters ) {
  22628. super();
  22629. this.isLineDashedMaterial = true;
  22630. this.type = 'LineDashedMaterial';
  22631. this.scale = 1;
  22632. this.dashSize = 3;
  22633. this.gapSize = 1;
  22634. this.setValues( parameters );
  22635. }
  22636. copy( source ) {
  22637. super.copy( source );
  22638. this.scale = source.scale;
  22639. this.dashSize = source.dashSize;
  22640. this.gapSize = source.gapSize;
  22641. return this;
  22642. }
  22643. }
  22644. // same as Array.prototype.slice, but also works on typed arrays
  22645. function arraySlice( array, from, to ) {
  22646. if ( isTypedArray( array ) ) {
  22647. // in ios9 array.subarray(from, undefined) will return empty array
  22648. // but array.subarray(from) or array.subarray(from, len) is correct
  22649. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22650. }
  22651. return array.slice( from, to );
  22652. }
  22653. // converts an array to a specific type
  22654. function convertArray( array, type, forceClone ) {
  22655. if ( ! array || // let 'undefined' and 'null' pass
  22656. ! forceClone && array.constructor === type ) return array;
  22657. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22658. return new type( array ); // create typed array
  22659. }
  22660. return Array.prototype.slice.call( array ); // create Array
  22661. }
  22662. function isTypedArray( object ) {
  22663. return ArrayBuffer.isView( object ) &&
  22664. ! ( object instanceof DataView );
  22665. }
  22666. // returns an array by which times and values can be sorted
  22667. function getKeyframeOrder( times ) {
  22668. function compareTime( i, j ) {
  22669. return times[ i ] - times[ j ];
  22670. }
  22671. const n = times.length;
  22672. const result = new Array( n );
  22673. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22674. result.sort( compareTime );
  22675. return result;
  22676. }
  22677. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22678. function sortedArray( values, stride, order ) {
  22679. const nValues = values.length;
  22680. const result = new values.constructor( nValues );
  22681. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22682. const srcOffset = order[ i ] * stride;
  22683. for ( let j = 0; j !== stride; ++ j ) {
  22684. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22685. }
  22686. }
  22687. return result;
  22688. }
  22689. // function for parsing AOS keyframe formats
  22690. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22691. let i = 1, key = jsonKeys[ 0 ];
  22692. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22693. key = jsonKeys[ i ++ ];
  22694. }
  22695. if ( key === undefined ) return; // no data
  22696. let value = key[ valuePropertyName ];
  22697. if ( value === undefined ) return; // no data
  22698. if ( Array.isArray( value ) ) {
  22699. do {
  22700. value = key[ valuePropertyName ];
  22701. if ( value !== undefined ) {
  22702. times.push( key.time );
  22703. values.push.apply( values, value ); // push all elements
  22704. }
  22705. key = jsonKeys[ i ++ ];
  22706. } while ( key !== undefined );
  22707. } else if ( value.toArray !== undefined ) {
  22708. // ...assume THREE.Math-ish
  22709. do {
  22710. value = key[ valuePropertyName ];
  22711. if ( value !== undefined ) {
  22712. times.push( key.time );
  22713. value.toArray( values, values.length );
  22714. }
  22715. key = jsonKeys[ i ++ ];
  22716. } while ( key !== undefined );
  22717. } else {
  22718. // otherwise push as-is
  22719. do {
  22720. value = key[ valuePropertyName ];
  22721. if ( value !== undefined ) {
  22722. times.push( key.time );
  22723. values.push( value );
  22724. }
  22725. key = jsonKeys[ i ++ ];
  22726. } while ( key !== undefined );
  22727. }
  22728. }
  22729. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22730. const clip = sourceClip.clone();
  22731. clip.name = name;
  22732. const tracks = [];
  22733. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22734. const track = clip.tracks[ i ];
  22735. const valueSize = track.getValueSize();
  22736. const times = [];
  22737. const values = [];
  22738. for ( let j = 0; j < track.times.length; ++ j ) {
  22739. const frame = track.times[ j ] * fps;
  22740. if ( frame < startFrame || frame >= endFrame ) continue;
  22741. times.push( track.times[ j ] );
  22742. for ( let k = 0; k < valueSize; ++ k ) {
  22743. values.push( track.values[ j * valueSize + k ] );
  22744. }
  22745. }
  22746. if ( times.length === 0 ) continue;
  22747. track.times = convertArray( times, track.times.constructor );
  22748. track.values = convertArray( values, track.values.constructor );
  22749. tracks.push( track );
  22750. }
  22751. clip.tracks = tracks;
  22752. // find minimum .times value across all tracks in the trimmed clip
  22753. let minStartTime = Infinity;
  22754. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22755. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22756. minStartTime = clip.tracks[ i ].times[ 0 ];
  22757. }
  22758. }
  22759. // shift all tracks such that clip begins at t=0
  22760. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22761. clip.tracks[ i ].shift( - 1 * minStartTime );
  22762. }
  22763. clip.resetDuration();
  22764. return clip;
  22765. }
  22766. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22767. if ( fps <= 0 ) fps = 30;
  22768. const numTracks = referenceClip.tracks.length;
  22769. const referenceTime = referenceFrame / fps;
  22770. // Make each track's values relative to the values at the reference frame
  22771. for ( let i = 0; i < numTracks; ++ i ) {
  22772. const referenceTrack = referenceClip.tracks[ i ];
  22773. const referenceTrackType = referenceTrack.ValueTypeName;
  22774. // Skip this track if it's non-numeric
  22775. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22776. // Find the track in the target clip whose name and type matches the reference track
  22777. const targetTrack = targetClip.tracks.find( function ( track ) {
  22778. return track.name === referenceTrack.name
  22779. && track.ValueTypeName === referenceTrackType;
  22780. } );
  22781. if ( targetTrack === undefined ) continue;
  22782. let referenceOffset = 0;
  22783. const referenceValueSize = referenceTrack.getValueSize();
  22784. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22785. referenceOffset = referenceValueSize / 3;
  22786. }
  22787. let targetOffset = 0;
  22788. const targetValueSize = targetTrack.getValueSize();
  22789. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22790. targetOffset = targetValueSize / 3;
  22791. }
  22792. const lastIndex = referenceTrack.times.length - 1;
  22793. let referenceValue;
  22794. // Find the value to subtract out of the track
  22795. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22796. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22797. const startIndex = referenceOffset;
  22798. const endIndex = referenceValueSize - referenceOffset;
  22799. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22800. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22801. // Reference frame is after the last keyframe, so just use the last keyframe
  22802. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22803. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22804. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22805. } else {
  22806. // Interpolate to the reference value
  22807. const interpolant = referenceTrack.createInterpolant();
  22808. const startIndex = referenceOffset;
  22809. const endIndex = referenceValueSize - referenceOffset;
  22810. interpolant.evaluate( referenceTime );
  22811. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22812. }
  22813. // Conjugate the quaternion
  22814. if ( referenceTrackType === 'quaternion' ) {
  22815. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22816. referenceQuat.toArray( referenceValue );
  22817. }
  22818. // Subtract the reference value from all of the track values
  22819. const numTimes = targetTrack.times.length;
  22820. for ( let j = 0; j < numTimes; ++ j ) {
  22821. const valueStart = j * targetValueSize + targetOffset;
  22822. if ( referenceTrackType === 'quaternion' ) {
  22823. // Multiply the conjugate for quaternion track types
  22824. Quaternion.multiplyQuaternionsFlat(
  22825. targetTrack.values,
  22826. valueStart,
  22827. referenceValue,
  22828. 0,
  22829. targetTrack.values,
  22830. valueStart
  22831. );
  22832. } else {
  22833. const valueEnd = targetValueSize - targetOffset * 2;
  22834. // Subtract each value for all other numeric track types
  22835. for ( let k = 0; k < valueEnd; ++ k ) {
  22836. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22837. }
  22838. }
  22839. }
  22840. }
  22841. targetClip.blendMode = AdditiveAnimationBlendMode;
  22842. return targetClip;
  22843. }
  22844. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22845. __proto__: null,
  22846. arraySlice: arraySlice,
  22847. convertArray: convertArray,
  22848. flattenJSON: flattenJSON,
  22849. getKeyframeOrder: getKeyframeOrder,
  22850. isTypedArray: isTypedArray,
  22851. makeClipAdditive: makeClipAdditive,
  22852. sortedArray: sortedArray,
  22853. subclip: subclip
  22854. });
  22855. /**
  22856. * Abstract base class of interpolants over parametric samples.
  22857. *
  22858. * The parameter domain is one dimensional, typically the time or a path
  22859. * along a curve defined by the data.
  22860. *
  22861. * The sample values can have any dimensionality and derived classes may
  22862. * apply special interpretations to the data.
  22863. *
  22864. * This class provides the interval seek in a Template Method, deferring
  22865. * the actual interpolation to derived classes.
  22866. *
  22867. * Time complexity is O(1) for linear access crossing at most two points
  22868. * and O(log N) for random access, where N is the number of positions.
  22869. *
  22870. * References:
  22871. *
  22872. * http://www.oodesign.com/template-method-pattern.html
  22873. *
  22874. */
  22875. class Interpolant {
  22876. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22877. this.parameterPositions = parameterPositions;
  22878. this._cachedIndex = 0;
  22879. this.resultBuffer = resultBuffer !== undefined ?
  22880. resultBuffer : new sampleValues.constructor( sampleSize );
  22881. this.sampleValues = sampleValues;
  22882. this.valueSize = sampleSize;
  22883. this.settings = null;
  22884. this.DefaultSettings_ = {};
  22885. }
  22886. evaluate( t ) {
  22887. const pp = this.parameterPositions;
  22888. let i1 = this._cachedIndex,
  22889. t1 = pp[ i1 ],
  22890. t0 = pp[ i1 - 1 ];
  22891. validate_interval: {
  22892. seek: {
  22893. let right;
  22894. linear_scan: {
  22895. //- See http://jsperf.com/comparison-to-undefined/3
  22896. //- slower code:
  22897. //-
  22898. //- if ( t >= t1 || t1 === undefined ) {
  22899. forward_scan: if ( ! ( t < t1 ) ) {
  22900. for ( let giveUpAt = i1 + 2; ; ) {
  22901. if ( t1 === undefined ) {
  22902. if ( t < t0 ) break forward_scan;
  22903. // after end
  22904. i1 = pp.length;
  22905. this._cachedIndex = i1;
  22906. return this.copySampleValue_( i1 - 1 );
  22907. }
  22908. if ( i1 === giveUpAt ) break; // this loop
  22909. t0 = t1;
  22910. t1 = pp[ ++ i1 ];
  22911. if ( t < t1 ) {
  22912. // we have arrived at the sought interval
  22913. break seek;
  22914. }
  22915. }
  22916. // prepare binary search on the right side of the index
  22917. right = pp.length;
  22918. break linear_scan;
  22919. }
  22920. //- slower code:
  22921. //- if ( t < t0 || t0 === undefined ) {
  22922. if ( ! ( t >= t0 ) ) {
  22923. // looping?
  22924. const t1global = pp[ 1 ];
  22925. if ( t < t1global ) {
  22926. i1 = 2; // + 1, using the scan for the details
  22927. t0 = t1global;
  22928. }
  22929. // linear reverse scan
  22930. for ( let giveUpAt = i1 - 2; ; ) {
  22931. if ( t0 === undefined ) {
  22932. // before start
  22933. this._cachedIndex = 0;
  22934. return this.copySampleValue_( 0 );
  22935. }
  22936. if ( i1 === giveUpAt ) break; // this loop
  22937. t1 = t0;
  22938. t0 = pp[ -- i1 - 1 ];
  22939. if ( t >= t0 ) {
  22940. // we have arrived at the sought interval
  22941. break seek;
  22942. }
  22943. }
  22944. // prepare binary search on the left side of the index
  22945. right = i1;
  22946. i1 = 0;
  22947. break linear_scan;
  22948. }
  22949. // the interval is valid
  22950. break validate_interval;
  22951. } // linear scan
  22952. // binary search
  22953. while ( i1 < right ) {
  22954. const mid = ( i1 + right ) >>> 1;
  22955. if ( t < pp[ mid ] ) {
  22956. right = mid;
  22957. } else {
  22958. i1 = mid + 1;
  22959. }
  22960. }
  22961. t1 = pp[ i1 ];
  22962. t0 = pp[ i1 - 1 ];
  22963. // check boundary cases, again
  22964. if ( t0 === undefined ) {
  22965. this._cachedIndex = 0;
  22966. return this.copySampleValue_( 0 );
  22967. }
  22968. if ( t1 === undefined ) {
  22969. i1 = pp.length;
  22970. this._cachedIndex = i1;
  22971. return this.copySampleValue_( i1 - 1 );
  22972. }
  22973. } // seek
  22974. this._cachedIndex = i1;
  22975. this.intervalChanged_( i1, t0, t1 );
  22976. } // validate_interval
  22977. return this.interpolate_( i1, t0, t, t1 );
  22978. }
  22979. getSettings_() {
  22980. return this.settings || this.DefaultSettings_;
  22981. }
  22982. copySampleValue_( index ) {
  22983. // copies a sample value to the result buffer
  22984. const result = this.resultBuffer,
  22985. values = this.sampleValues,
  22986. stride = this.valueSize,
  22987. offset = index * stride;
  22988. for ( let i = 0; i !== stride; ++ i ) {
  22989. result[ i ] = values[ offset + i ];
  22990. }
  22991. return result;
  22992. }
  22993. // Template methods for derived classes:
  22994. interpolate_( /* i1, t0, t, t1 */ ) {
  22995. throw new Error( 'call to abstract method' );
  22996. // implementations shall return this.resultBuffer
  22997. }
  22998. intervalChanged_( /* i1, t0, t1 */ ) {
  22999. // empty
  23000. }
  23001. }
  23002. /**
  23003. * Fast and simple cubic spline interpolant.
  23004. *
  23005. * It was derived from a Hermitian construction setting the first derivative
  23006. * at each sample position to the linear slope between neighboring positions
  23007. * over their parameter interval.
  23008. */
  23009. class CubicInterpolant extends Interpolant {
  23010. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23011. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23012. this._weightPrev = - 0;
  23013. this._offsetPrev = - 0;
  23014. this._weightNext = - 0;
  23015. this._offsetNext = - 0;
  23016. this.DefaultSettings_ = {
  23017. endingStart: ZeroCurvatureEnding,
  23018. endingEnd: ZeroCurvatureEnding
  23019. };
  23020. }
  23021. intervalChanged_( i1, t0, t1 ) {
  23022. const pp = this.parameterPositions;
  23023. let iPrev = i1 - 2,
  23024. iNext = i1 + 1,
  23025. tPrev = pp[ iPrev ],
  23026. tNext = pp[ iNext ];
  23027. if ( tPrev === undefined ) {
  23028. switch ( this.getSettings_().endingStart ) {
  23029. case ZeroSlopeEnding:
  23030. // f'(t0) = 0
  23031. iPrev = i1;
  23032. tPrev = 2 * t0 - t1;
  23033. break;
  23034. case WrapAroundEnding:
  23035. // use the other end of the curve
  23036. iPrev = pp.length - 2;
  23037. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23038. break;
  23039. default: // ZeroCurvatureEnding
  23040. // f''(t0) = 0 a.k.a. Natural Spline
  23041. iPrev = i1;
  23042. tPrev = t1;
  23043. }
  23044. }
  23045. if ( tNext === undefined ) {
  23046. switch ( this.getSettings_().endingEnd ) {
  23047. case ZeroSlopeEnding:
  23048. // f'(tN) = 0
  23049. iNext = i1;
  23050. tNext = 2 * t1 - t0;
  23051. break;
  23052. case WrapAroundEnding:
  23053. // use the other end of the curve
  23054. iNext = 1;
  23055. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23056. break;
  23057. default: // ZeroCurvatureEnding
  23058. // f''(tN) = 0, a.k.a. Natural Spline
  23059. iNext = i1 - 1;
  23060. tNext = t0;
  23061. }
  23062. }
  23063. const halfDt = ( t1 - t0 ) * 0.5,
  23064. stride = this.valueSize;
  23065. this._weightPrev = halfDt / ( t0 - tPrev );
  23066. this._weightNext = halfDt / ( tNext - t1 );
  23067. this._offsetPrev = iPrev * stride;
  23068. this._offsetNext = iNext * stride;
  23069. }
  23070. interpolate_( i1, t0, t, t1 ) {
  23071. const result = this.resultBuffer,
  23072. values = this.sampleValues,
  23073. stride = this.valueSize,
  23074. o1 = i1 * stride, o0 = o1 - stride,
  23075. oP = this._offsetPrev, oN = this._offsetNext,
  23076. wP = this._weightPrev, wN = this._weightNext,
  23077. p = ( t - t0 ) / ( t1 - t0 ),
  23078. pp = p * p,
  23079. ppp = pp * p;
  23080. // evaluate polynomials
  23081. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23082. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23083. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23084. const sN = wN * ppp - wN * pp;
  23085. // combine data linearly
  23086. for ( let i = 0; i !== stride; ++ i ) {
  23087. result[ i ] =
  23088. sP * values[ oP + i ] +
  23089. s0 * values[ o0 + i ] +
  23090. s1 * values[ o1 + i ] +
  23091. sN * values[ oN + i ];
  23092. }
  23093. return result;
  23094. }
  23095. }
  23096. class LinearInterpolant extends Interpolant {
  23097. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23098. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23099. }
  23100. interpolate_( i1, t0, t, t1 ) {
  23101. const result = this.resultBuffer,
  23102. values = this.sampleValues,
  23103. stride = this.valueSize,
  23104. offset1 = i1 * stride,
  23105. offset0 = offset1 - stride,
  23106. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23107. weight0 = 1 - weight1;
  23108. for ( let i = 0; i !== stride; ++ i ) {
  23109. result[ i ] =
  23110. values[ offset0 + i ] * weight0 +
  23111. values[ offset1 + i ] * weight1;
  23112. }
  23113. return result;
  23114. }
  23115. }
  23116. /**
  23117. *
  23118. * Interpolant that evaluates to the sample value at the position preceding
  23119. * the parameter.
  23120. */
  23121. class DiscreteInterpolant extends Interpolant {
  23122. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23123. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23124. }
  23125. interpolate_( i1 /*, t0, t, t1 */ ) {
  23126. return this.copySampleValue_( i1 - 1 );
  23127. }
  23128. }
  23129. class KeyframeTrack {
  23130. constructor( name, times, values, interpolation ) {
  23131. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23132. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23133. this.name = name;
  23134. this.times = convertArray( times, this.TimeBufferType );
  23135. this.values = convertArray( values, this.ValueBufferType );
  23136. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23137. }
  23138. // Serialization (in static context, because of constructor invocation
  23139. // and automatic invocation of .toJSON):
  23140. static toJSON( track ) {
  23141. const trackType = track.constructor;
  23142. let json;
  23143. // derived classes can define a static toJSON method
  23144. if ( trackType.toJSON !== this.toJSON ) {
  23145. json = trackType.toJSON( track );
  23146. } else {
  23147. // by default, we assume the data can be serialized as-is
  23148. json = {
  23149. 'name': track.name,
  23150. 'times': convertArray( track.times, Array ),
  23151. 'values': convertArray( track.values, Array )
  23152. };
  23153. const interpolation = track.getInterpolation();
  23154. if ( interpolation !== track.DefaultInterpolation ) {
  23155. json.interpolation = interpolation;
  23156. }
  23157. }
  23158. json.type = track.ValueTypeName; // mandatory
  23159. return json;
  23160. }
  23161. InterpolantFactoryMethodDiscrete( result ) {
  23162. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23163. }
  23164. InterpolantFactoryMethodLinear( result ) {
  23165. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23166. }
  23167. InterpolantFactoryMethodSmooth( result ) {
  23168. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23169. }
  23170. setInterpolation( interpolation ) {
  23171. let factoryMethod;
  23172. switch ( interpolation ) {
  23173. case InterpolateDiscrete:
  23174. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23175. break;
  23176. case InterpolateLinear:
  23177. factoryMethod = this.InterpolantFactoryMethodLinear;
  23178. break;
  23179. case InterpolateSmooth:
  23180. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23181. break;
  23182. }
  23183. if ( factoryMethod === undefined ) {
  23184. const message = 'unsupported interpolation for ' +
  23185. this.ValueTypeName + ' keyframe track named ' + this.name;
  23186. if ( this.createInterpolant === undefined ) {
  23187. // fall back to default, unless the default itself is messed up
  23188. if ( interpolation !== this.DefaultInterpolation ) {
  23189. this.setInterpolation( this.DefaultInterpolation );
  23190. } else {
  23191. throw new Error( message ); // fatal, in this case
  23192. }
  23193. }
  23194. console.warn( 'THREE.KeyframeTrack:', message );
  23195. return this;
  23196. }
  23197. this.createInterpolant = factoryMethod;
  23198. return this;
  23199. }
  23200. getInterpolation() {
  23201. switch ( this.createInterpolant ) {
  23202. case this.InterpolantFactoryMethodDiscrete:
  23203. return InterpolateDiscrete;
  23204. case this.InterpolantFactoryMethodLinear:
  23205. return InterpolateLinear;
  23206. case this.InterpolantFactoryMethodSmooth:
  23207. return InterpolateSmooth;
  23208. }
  23209. }
  23210. getValueSize() {
  23211. return this.values.length / this.times.length;
  23212. }
  23213. // move all keyframes either forwards or backwards in time
  23214. shift( timeOffset ) {
  23215. if ( timeOffset !== 0.0 ) {
  23216. const times = this.times;
  23217. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23218. times[ i ] += timeOffset;
  23219. }
  23220. }
  23221. return this;
  23222. }
  23223. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23224. scale( timeScale ) {
  23225. if ( timeScale !== 1.0 ) {
  23226. const times = this.times;
  23227. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23228. times[ i ] *= timeScale;
  23229. }
  23230. }
  23231. return this;
  23232. }
  23233. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23234. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23235. trim( startTime, endTime ) {
  23236. const times = this.times,
  23237. nKeys = times.length;
  23238. let from = 0,
  23239. to = nKeys - 1;
  23240. while ( from !== nKeys && times[ from ] < startTime ) {
  23241. ++ from;
  23242. }
  23243. while ( to !== - 1 && times[ to ] > endTime ) {
  23244. -- to;
  23245. }
  23246. ++ to; // inclusive -> exclusive bound
  23247. if ( from !== 0 || to !== nKeys ) {
  23248. // empty tracks are forbidden, so keep at least one keyframe
  23249. if ( from >= to ) {
  23250. to = Math.max( to, 1 );
  23251. from = to - 1;
  23252. }
  23253. const stride = this.getValueSize();
  23254. this.times = arraySlice( times, from, to );
  23255. this.values = arraySlice( this.values, from * stride, to * stride );
  23256. }
  23257. return this;
  23258. }
  23259. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23260. validate() {
  23261. let valid = true;
  23262. const valueSize = this.getValueSize();
  23263. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23264. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23265. valid = false;
  23266. }
  23267. const times = this.times,
  23268. values = this.values,
  23269. nKeys = times.length;
  23270. if ( nKeys === 0 ) {
  23271. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23272. valid = false;
  23273. }
  23274. let prevTime = null;
  23275. for ( let i = 0; i !== nKeys; i ++ ) {
  23276. const currTime = times[ i ];
  23277. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23278. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23279. valid = false;
  23280. break;
  23281. }
  23282. if ( prevTime !== null && prevTime > currTime ) {
  23283. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23284. valid = false;
  23285. break;
  23286. }
  23287. prevTime = currTime;
  23288. }
  23289. if ( values !== undefined ) {
  23290. if ( isTypedArray( values ) ) {
  23291. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23292. const value = values[ i ];
  23293. if ( isNaN( value ) ) {
  23294. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23295. valid = false;
  23296. break;
  23297. }
  23298. }
  23299. }
  23300. }
  23301. return valid;
  23302. }
  23303. // removes equivalent sequential keys as common in morph target sequences
  23304. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23305. optimize() {
  23306. // times or values may be shared with other tracks, so overwriting is unsafe
  23307. const times = arraySlice( this.times ),
  23308. values = arraySlice( this.values ),
  23309. stride = this.getValueSize(),
  23310. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23311. lastIndex = times.length - 1;
  23312. let writeIndex = 1;
  23313. for ( let i = 1; i < lastIndex; ++ i ) {
  23314. let keep = false;
  23315. const time = times[ i ];
  23316. const timeNext = times[ i + 1 ];
  23317. // remove adjacent keyframes scheduled at the same time
  23318. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23319. if ( ! smoothInterpolation ) {
  23320. // remove unnecessary keyframes same as their neighbors
  23321. const offset = i * stride,
  23322. offsetP = offset - stride,
  23323. offsetN = offset + stride;
  23324. for ( let j = 0; j !== stride; ++ j ) {
  23325. const value = values[ offset + j ];
  23326. if ( value !== values[ offsetP + j ] ||
  23327. value !== values[ offsetN + j ] ) {
  23328. keep = true;
  23329. break;
  23330. }
  23331. }
  23332. } else {
  23333. keep = true;
  23334. }
  23335. }
  23336. // in-place compaction
  23337. if ( keep ) {
  23338. if ( i !== writeIndex ) {
  23339. times[ writeIndex ] = times[ i ];
  23340. const readOffset = i * stride,
  23341. writeOffset = writeIndex * stride;
  23342. for ( let j = 0; j !== stride; ++ j ) {
  23343. values[ writeOffset + j ] = values[ readOffset + j ];
  23344. }
  23345. }
  23346. ++ writeIndex;
  23347. }
  23348. }
  23349. // flush last keyframe (compaction looks ahead)
  23350. if ( lastIndex > 0 ) {
  23351. times[ writeIndex ] = times[ lastIndex ];
  23352. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23353. values[ writeOffset + j ] = values[ readOffset + j ];
  23354. }
  23355. ++ writeIndex;
  23356. }
  23357. if ( writeIndex !== times.length ) {
  23358. this.times = arraySlice( times, 0, writeIndex );
  23359. this.values = arraySlice( values, 0, writeIndex * stride );
  23360. } else {
  23361. this.times = times;
  23362. this.values = values;
  23363. }
  23364. return this;
  23365. }
  23366. clone() {
  23367. const times = arraySlice( this.times, 0 );
  23368. const values = arraySlice( this.values, 0 );
  23369. const TypedKeyframeTrack = this.constructor;
  23370. const track = new TypedKeyframeTrack( this.name, times, values );
  23371. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23372. track.createInterpolant = this.createInterpolant;
  23373. return track;
  23374. }
  23375. }
  23376. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23377. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23378. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23379. /**
  23380. * A Track of Boolean keyframe values.
  23381. */
  23382. class BooleanKeyframeTrack extends KeyframeTrack {}
  23383. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23384. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23385. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23386. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23387. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23388. /**
  23389. * A Track of keyframe values that represent color.
  23390. */
  23391. class ColorKeyframeTrack extends KeyframeTrack {}
  23392. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23393. /**
  23394. * A Track of numeric keyframe values.
  23395. */
  23396. class NumberKeyframeTrack extends KeyframeTrack {}
  23397. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23398. /**
  23399. * Spherical linear unit quaternion interpolant.
  23400. */
  23401. class QuaternionLinearInterpolant extends Interpolant {
  23402. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23403. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23404. }
  23405. interpolate_( i1, t0, t, t1 ) {
  23406. const result = this.resultBuffer,
  23407. values = this.sampleValues,
  23408. stride = this.valueSize,
  23409. alpha = ( t - t0 ) / ( t1 - t0 );
  23410. let offset = i1 * stride;
  23411. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23412. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23413. }
  23414. return result;
  23415. }
  23416. }
  23417. /**
  23418. * A Track of quaternion keyframe values.
  23419. */
  23420. class QuaternionKeyframeTrack extends KeyframeTrack {
  23421. InterpolantFactoryMethodLinear( result ) {
  23422. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23423. }
  23424. }
  23425. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23426. // ValueBufferType is inherited
  23427. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23428. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23429. /**
  23430. * A Track that interpolates Strings
  23431. */
  23432. class StringKeyframeTrack extends KeyframeTrack {}
  23433. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23434. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23435. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23436. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23437. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23438. /**
  23439. * A Track of vectored keyframe values.
  23440. */
  23441. class VectorKeyframeTrack extends KeyframeTrack {}
  23442. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23443. class AnimationClip {
  23444. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23445. this.name = name;
  23446. this.tracks = tracks;
  23447. this.duration = duration;
  23448. this.blendMode = blendMode;
  23449. this.uuid = generateUUID();
  23450. // this means it should figure out its duration by scanning the tracks
  23451. if ( this.duration < 0 ) {
  23452. this.resetDuration();
  23453. }
  23454. }
  23455. static parse( json ) {
  23456. const tracks = [],
  23457. jsonTracks = json.tracks,
  23458. frameTime = 1.0 / ( json.fps || 1.0 );
  23459. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23460. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23461. }
  23462. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23463. clip.uuid = json.uuid;
  23464. return clip;
  23465. }
  23466. static toJSON( clip ) {
  23467. const tracks = [],
  23468. clipTracks = clip.tracks;
  23469. const json = {
  23470. 'name': clip.name,
  23471. 'duration': clip.duration,
  23472. 'tracks': tracks,
  23473. 'uuid': clip.uuid,
  23474. 'blendMode': clip.blendMode
  23475. };
  23476. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23477. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23478. }
  23479. return json;
  23480. }
  23481. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23482. const numMorphTargets = morphTargetSequence.length;
  23483. const tracks = [];
  23484. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23485. let times = [];
  23486. let values = [];
  23487. times.push(
  23488. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23489. i,
  23490. ( i + 1 ) % numMorphTargets );
  23491. values.push( 0, 1, 0 );
  23492. const order = getKeyframeOrder( times );
  23493. times = sortedArray( times, 1, order );
  23494. values = sortedArray( values, 1, order );
  23495. // if there is a key at the first frame, duplicate it as the
  23496. // last frame as well for perfect loop.
  23497. if ( ! noLoop && times[ 0 ] === 0 ) {
  23498. times.push( numMorphTargets );
  23499. values.push( values[ 0 ] );
  23500. }
  23501. tracks.push(
  23502. new NumberKeyframeTrack(
  23503. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23504. times, values
  23505. ).scale( 1.0 / fps ) );
  23506. }
  23507. return new this( name, - 1, tracks );
  23508. }
  23509. static findByName( objectOrClipArray, name ) {
  23510. let clipArray = objectOrClipArray;
  23511. if ( ! Array.isArray( objectOrClipArray ) ) {
  23512. const o = objectOrClipArray;
  23513. clipArray = o.geometry && o.geometry.animations || o.animations;
  23514. }
  23515. for ( let i = 0; i < clipArray.length; i ++ ) {
  23516. if ( clipArray[ i ].name === name ) {
  23517. return clipArray[ i ];
  23518. }
  23519. }
  23520. return null;
  23521. }
  23522. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23523. const animationToMorphTargets = {};
  23524. // tested with https://regex101.com/ on trick sequences
  23525. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23526. const pattern = /^([\w-]*?)([\d]+)$/;
  23527. // sort morph target names into animation groups based
  23528. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23529. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23530. const morphTarget = morphTargets[ i ];
  23531. const parts = morphTarget.name.match( pattern );
  23532. if ( parts && parts.length > 1 ) {
  23533. const name = parts[ 1 ];
  23534. let animationMorphTargets = animationToMorphTargets[ name ];
  23535. if ( ! animationMorphTargets ) {
  23536. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23537. }
  23538. animationMorphTargets.push( morphTarget );
  23539. }
  23540. }
  23541. const clips = [];
  23542. for ( const name in animationToMorphTargets ) {
  23543. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23544. }
  23545. return clips;
  23546. }
  23547. // parse the animation.hierarchy format
  23548. static parseAnimation( animation, bones ) {
  23549. if ( ! animation ) {
  23550. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23551. return null;
  23552. }
  23553. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23554. // only return track if there are actually keys.
  23555. if ( animationKeys.length !== 0 ) {
  23556. const times = [];
  23557. const values = [];
  23558. flattenJSON( animationKeys, times, values, propertyName );
  23559. // empty keys are filtered out, so check again
  23560. if ( times.length !== 0 ) {
  23561. destTracks.push( new trackType( trackName, times, values ) );
  23562. }
  23563. }
  23564. };
  23565. const tracks = [];
  23566. const clipName = animation.name || 'default';
  23567. const fps = animation.fps || 30;
  23568. const blendMode = animation.blendMode;
  23569. // automatic length determination in AnimationClip.
  23570. let duration = animation.length || - 1;
  23571. const hierarchyTracks = animation.hierarchy || [];
  23572. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23573. const animationKeys = hierarchyTracks[ h ].keys;
  23574. // skip empty tracks
  23575. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23576. // process morph targets
  23577. if ( animationKeys[ 0 ].morphTargets ) {
  23578. // figure out all morph targets used in this track
  23579. const morphTargetNames = {};
  23580. let k;
  23581. for ( k = 0; k < animationKeys.length; k ++ ) {
  23582. if ( animationKeys[ k ].morphTargets ) {
  23583. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23584. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23585. }
  23586. }
  23587. }
  23588. // create a track for each morph target with all zero
  23589. // morphTargetInfluences except for the keys in which
  23590. // the morphTarget is named.
  23591. for ( const morphTargetName in morphTargetNames ) {
  23592. const times = [];
  23593. const values = [];
  23594. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23595. const animationKey = animationKeys[ k ];
  23596. times.push( animationKey.time );
  23597. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23598. }
  23599. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23600. }
  23601. duration = morphTargetNames.length * fps;
  23602. } else {
  23603. // ...assume skeletal animation
  23604. const boneName = '.bones[' + bones[ h ].name + ']';
  23605. addNonemptyTrack(
  23606. VectorKeyframeTrack, boneName + '.position',
  23607. animationKeys, 'pos', tracks );
  23608. addNonemptyTrack(
  23609. QuaternionKeyframeTrack, boneName + '.quaternion',
  23610. animationKeys, 'rot', tracks );
  23611. addNonemptyTrack(
  23612. VectorKeyframeTrack, boneName + '.scale',
  23613. animationKeys, 'scl', tracks );
  23614. }
  23615. }
  23616. if ( tracks.length === 0 ) {
  23617. return null;
  23618. }
  23619. const clip = new this( clipName, duration, tracks, blendMode );
  23620. return clip;
  23621. }
  23622. resetDuration() {
  23623. const tracks = this.tracks;
  23624. let duration = 0;
  23625. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23626. const track = this.tracks[ i ];
  23627. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23628. }
  23629. this.duration = duration;
  23630. return this;
  23631. }
  23632. trim() {
  23633. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23634. this.tracks[ i ].trim( 0, this.duration );
  23635. }
  23636. return this;
  23637. }
  23638. validate() {
  23639. let valid = true;
  23640. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23641. valid = valid && this.tracks[ i ].validate();
  23642. }
  23643. return valid;
  23644. }
  23645. optimize() {
  23646. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23647. this.tracks[ i ].optimize();
  23648. }
  23649. return this;
  23650. }
  23651. clone() {
  23652. const tracks = [];
  23653. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23654. tracks.push( this.tracks[ i ].clone() );
  23655. }
  23656. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23657. }
  23658. toJSON() {
  23659. return this.constructor.toJSON( this );
  23660. }
  23661. }
  23662. function getTrackTypeForValueTypeName( typeName ) {
  23663. switch ( typeName.toLowerCase() ) {
  23664. case 'scalar':
  23665. case 'double':
  23666. case 'float':
  23667. case 'number':
  23668. case 'integer':
  23669. return NumberKeyframeTrack;
  23670. case 'vector':
  23671. case 'vector2':
  23672. case 'vector3':
  23673. case 'vector4':
  23674. return VectorKeyframeTrack;
  23675. case 'color':
  23676. return ColorKeyframeTrack;
  23677. case 'quaternion':
  23678. return QuaternionKeyframeTrack;
  23679. case 'bool':
  23680. case 'boolean':
  23681. return BooleanKeyframeTrack;
  23682. case 'string':
  23683. return StringKeyframeTrack;
  23684. }
  23685. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23686. }
  23687. function parseKeyframeTrack( json ) {
  23688. if ( json.type === undefined ) {
  23689. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23690. }
  23691. const trackType = getTrackTypeForValueTypeName( json.type );
  23692. if ( json.times === undefined ) {
  23693. const times = [], values = [];
  23694. flattenJSON( json.keys, times, values, 'value' );
  23695. json.times = times;
  23696. json.values = values;
  23697. }
  23698. // derived classes can define a static parse method
  23699. if ( trackType.parse !== undefined ) {
  23700. return trackType.parse( json );
  23701. } else {
  23702. // by default, we assume a constructor compatible with the base
  23703. return new trackType( json.name, json.times, json.values, json.interpolation );
  23704. }
  23705. }
  23706. const Cache = {
  23707. enabled: false,
  23708. files: {},
  23709. add: function ( key, file ) {
  23710. if ( this.enabled === false ) return;
  23711. // console.log( 'THREE.Cache', 'Adding key:', key );
  23712. this.files[ key ] = file;
  23713. },
  23714. get: function ( key ) {
  23715. if ( this.enabled === false ) return;
  23716. // console.log( 'THREE.Cache', 'Checking key:', key );
  23717. return this.files[ key ];
  23718. },
  23719. remove: function ( key ) {
  23720. delete this.files[ key ];
  23721. },
  23722. clear: function () {
  23723. this.files = {};
  23724. }
  23725. };
  23726. class LoadingManager {
  23727. constructor( onLoad, onProgress, onError ) {
  23728. const scope = this;
  23729. let isLoading = false;
  23730. let itemsLoaded = 0;
  23731. let itemsTotal = 0;
  23732. let urlModifier = undefined;
  23733. const handlers = [];
  23734. // Refer to #5689 for the reason why we don't set .onStart
  23735. // in the constructor
  23736. this.onStart = undefined;
  23737. this.onLoad = onLoad;
  23738. this.onProgress = onProgress;
  23739. this.onError = onError;
  23740. this.itemStart = function ( url ) {
  23741. itemsTotal ++;
  23742. if ( isLoading === false ) {
  23743. if ( scope.onStart !== undefined ) {
  23744. scope.onStart( url, itemsLoaded, itemsTotal );
  23745. }
  23746. }
  23747. isLoading = true;
  23748. };
  23749. this.itemEnd = function ( url ) {
  23750. itemsLoaded ++;
  23751. if ( scope.onProgress !== undefined ) {
  23752. scope.onProgress( url, itemsLoaded, itemsTotal );
  23753. }
  23754. if ( itemsLoaded === itemsTotal ) {
  23755. isLoading = false;
  23756. if ( scope.onLoad !== undefined ) {
  23757. scope.onLoad();
  23758. }
  23759. }
  23760. };
  23761. this.itemError = function ( url ) {
  23762. if ( scope.onError !== undefined ) {
  23763. scope.onError( url );
  23764. }
  23765. };
  23766. this.resolveURL = function ( url ) {
  23767. if ( urlModifier ) {
  23768. return urlModifier( url );
  23769. }
  23770. return url;
  23771. };
  23772. this.setURLModifier = function ( transform ) {
  23773. urlModifier = transform;
  23774. return this;
  23775. };
  23776. this.addHandler = function ( regex, loader ) {
  23777. handlers.push( regex, loader );
  23778. return this;
  23779. };
  23780. this.removeHandler = function ( regex ) {
  23781. const index = handlers.indexOf( regex );
  23782. if ( index !== - 1 ) {
  23783. handlers.splice( index, 2 );
  23784. }
  23785. return this;
  23786. };
  23787. this.getHandler = function ( file ) {
  23788. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23789. const regex = handlers[ i ];
  23790. const loader = handlers[ i + 1 ];
  23791. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23792. if ( regex.test( file ) ) {
  23793. return loader;
  23794. }
  23795. }
  23796. return null;
  23797. };
  23798. }
  23799. }
  23800. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23801. class Loader {
  23802. constructor( manager ) {
  23803. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23804. this.crossOrigin = 'anonymous';
  23805. this.withCredentials = false;
  23806. this.path = '';
  23807. this.resourcePath = '';
  23808. this.requestHeader = {};
  23809. }
  23810. load( /* url, onLoad, onProgress, onError */ ) {}
  23811. loadAsync( url, onProgress ) {
  23812. const scope = this;
  23813. return new Promise( function ( resolve, reject ) {
  23814. scope.load( url, resolve, onProgress, reject );
  23815. } );
  23816. }
  23817. parse( /* data */ ) {}
  23818. setCrossOrigin( crossOrigin ) {
  23819. this.crossOrigin = crossOrigin;
  23820. return this;
  23821. }
  23822. setWithCredentials( value ) {
  23823. this.withCredentials = value;
  23824. return this;
  23825. }
  23826. setPath( path ) {
  23827. this.path = path;
  23828. return this;
  23829. }
  23830. setResourcePath( resourcePath ) {
  23831. this.resourcePath = resourcePath;
  23832. return this;
  23833. }
  23834. setRequestHeader( requestHeader ) {
  23835. this.requestHeader = requestHeader;
  23836. return this;
  23837. }
  23838. }
  23839. const loading = {};
  23840. class HttpError extends Error {
  23841. constructor( message, response ) {
  23842. super( message );
  23843. this.response = response;
  23844. }
  23845. }
  23846. class FileLoader extends Loader {
  23847. constructor( manager ) {
  23848. super( manager );
  23849. }
  23850. load( url, onLoad, onProgress, onError ) {
  23851. if ( url === undefined ) url = '';
  23852. if ( this.path !== undefined ) url = this.path + url;
  23853. url = this.manager.resolveURL( url );
  23854. const cached = Cache.get( url );
  23855. if ( cached !== undefined ) {
  23856. this.manager.itemStart( url );
  23857. setTimeout( () => {
  23858. if ( onLoad ) onLoad( cached );
  23859. this.manager.itemEnd( url );
  23860. }, 0 );
  23861. return cached;
  23862. }
  23863. // Check if request is duplicate
  23864. if ( loading[ url ] !== undefined ) {
  23865. loading[ url ].push( {
  23866. onLoad: onLoad,
  23867. onProgress: onProgress,
  23868. onError: onError
  23869. } );
  23870. return;
  23871. }
  23872. // Initialise array for duplicate requests
  23873. loading[ url ] = [];
  23874. loading[ url ].push( {
  23875. onLoad: onLoad,
  23876. onProgress: onProgress,
  23877. onError: onError,
  23878. } );
  23879. // create request
  23880. const req = new Request( url, {
  23881. headers: new Headers( this.requestHeader ),
  23882. credentials: this.withCredentials ? 'include' : 'same-origin',
  23883. // An abort controller could be added within a future PR
  23884. } );
  23885. // record states ( avoid data race )
  23886. const mimeType = this.mimeType;
  23887. const responseType = this.responseType;
  23888. // start the fetch
  23889. fetch( req )
  23890. .then( response => {
  23891. if ( response.status === 200 || response.status === 0 ) {
  23892. // Some browsers return HTTP Status 0 when using non-http protocol
  23893. // e.g. 'file://' or 'data://'. Handle as success.
  23894. if ( response.status === 0 ) {
  23895. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23896. }
  23897. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23898. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23899. return response;
  23900. }
  23901. const callbacks = loading[ url ];
  23902. const reader = response.body.getReader();
  23903. // Nginx needs X-File-Size check
  23904. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  23905. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  23906. const total = contentLength ? parseInt( contentLength ) : 0;
  23907. const lengthComputable = total !== 0;
  23908. let loaded = 0;
  23909. // periodically read data into the new stream tracking while download progress
  23910. const stream = new ReadableStream( {
  23911. start( controller ) {
  23912. readData();
  23913. function readData() {
  23914. reader.read().then( ( { done, value } ) => {
  23915. if ( done ) {
  23916. controller.close();
  23917. } else {
  23918. loaded += value.byteLength;
  23919. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23920. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23921. const callback = callbacks[ i ];
  23922. if ( callback.onProgress ) callback.onProgress( event );
  23923. }
  23924. controller.enqueue( value );
  23925. readData();
  23926. }
  23927. } );
  23928. }
  23929. }
  23930. } );
  23931. return new Response( stream );
  23932. } else {
  23933. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  23934. }
  23935. } )
  23936. .then( response => {
  23937. switch ( responseType ) {
  23938. case 'arraybuffer':
  23939. return response.arrayBuffer();
  23940. case 'blob':
  23941. return response.blob();
  23942. case 'document':
  23943. return response.text()
  23944. .then( text => {
  23945. const parser = new DOMParser();
  23946. return parser.parseFromString( text, mimeType );
  23947. } );
  23948. case 'json':
  23949. return response.json();
  23950. default:
  23951. if ( mimeType === undefined ) {
  23952. return response.text();
  23953. } else {
  23954. // sniff encoding
  23955. const re = /charset="?([^;"\s]*)"?/i;
  23956. const exec = re.exec( mimeType );
  23957. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23958. const decoder = new TextDecoder( label );
  23959. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23960. }
  23961. }
  23962. } )
  23963. .then( data => {
  23964. // Add to cache only on HTTP success, so that we do not cache
  23965. // error response bodies as proper responses to requests.
  23966. Cache.add( url, data );
  23967. const callbacks = loading[ url ];
  23968. delete loading[ url ];
  23969. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23970. const callback = callbacks[ i ];
  23971. if ( callback.onLoad ) callback.onLoad( data );
  23972. }
  23973. } )
  23974. .catch( err => {
  23975. // Abort errors and other errors are handled the same
  23976. const callbacks = loading[ url ];
  23977. if ( callbacks === undefined ) {
  23978. // When onLoad was called and url was deleted in `loading`
  23979. this.manager.itemError( url );
  23980. throw err;
  23981. }
  23982. delete loading[ url ];
  23983. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23984. const callback = callbacks[ i ];
  23985. if ( callback.onError ) callback.onError( err );
  23986. }
  23987. this.manager.itemError( url );
  23988. } )
  23989. .finally( () => {
  23990. this.manager.itemEnd( url );
  23991. } );
  23992. this.manager.itemStart( url );
  23993. }
  23994. setResponseType( value ) {
  23995. this.responseType = value;
  23996. return this;
  23997. }
  23998. setMimeType( value ) {
  23999. this.mimeType = value;
  24000. return this;
  24001. }
  24002. }
  24003. class AnimationLoader extends Loader {
  24004. constructor( manager ) {
  24005. super( manager );
  24006. }
  24007. load( url, onLoad, onProgress, onError ) {
  24008. const scope = this;
  24009. const loader = new FileLoader( this.manager );
  24010. loader.setPath( this.path );
  24011. loader.setRequestHeader( this.requestHeader );
  24012. loader.setWithCredentials( this.withCredentials );
  24013. loader.load( url, function ( text ) {
  24014. try {
  24015. onLoad( scope.parse( JSON.parse( text ) ) );
  24016. } catch ( e ) {
  24017. if ( onError ) {
  24018. onError( e );
  24019. } else {
  24020. console.error( e );
  24021. }
  24022. scope.manager.itemError( url );
  24023. }
  24024. }, onProgress, onError );
  24025. }
  24026. parse( json ) {
  24027. const animations = [];
  24028. for ( let i = 0; i < json.length; i ++ ) {
  24029. const clip = AnimationClip.parse( json[ i ] );
  24030. animations.push( clip );
  24031. }
  24032. return animations;
  24033. }
  24034. }
  24035. /**
  24036. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24037. *
  24038. * Sub classes have to implement the parse() method which will be used in load().
  24039. */
  24040. class CompressedTextureLoader extends Loader {
  24041. constructor( manager ) {
  24042. super( manager );
  24043. }
  24044. load( url, onLoad, onProgress, onError ) {
  24045. const scope = this;
  24046. const images = [];
  24047. const texture = new CompressedTexture();
  24048. const loader = new FileLoader( this.manager );
  24049. loader.setPath( this.path );
  24050. loader.setResponseType( 'arraybuffer' );
  24051. loader.setRequestHeader( this.requestHeader );
  24052. loader.setWithCredentials( scope.withCredentials );
  24053. let loaded = 0;
  24054. function loadTexture( i ) {
  24055. loader.load( url[ i ], function ( buffer ) {
  24056. const texDatas = scope.parse( buffer, true );
  24057. images[ i ] = {
  24058. width: texDatas.width,
  24059. height: texDatas.height,
  24060. format: texDatas.format,
  24061. mipmaps: texDatas.mipmaps
  24062. };
  24063. loaded += 1;
  24064. if ( loaded === 6 ) {
  24065. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24066. texture.image = images;
  24067. texture.format = texDatas.format;
  24068. texture.needsUpdate = true;
  24069. if ( onLoad ) onLoad( texture );
  24070. }
  24071. }, onProgress, onError );
  24072. }
  24073. if ( Array.isArray( url ) ) {
  24074. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24075. loadTexture( i );
  24076. }
  24077. } else {
  24078. // compressed cubemap texture stored in a single DDS file
  24079. loader.load( url, function ( buffer ) {
  24080. const texDatas = scope.parse( buffer, true );
  24081. if ( texDatas.isCubemap ) {
  24082. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24083. for ( let f = 0; f < faces; f ++ ) {
  24084. images[ f ] = { mipmaps: [] };
  24085. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24086. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24087. images[ f ].format = texDatas.format;
  24088. images[ f ].width = texDatas.width;
  24089. images[ f ].height = texDatas.height;
  24090. }
  24091. }
  24092. texture.image = images;
  24093. } else {
  24094. texture.image.width = texDatas.width;
  24095. texture.image.height = texDatas.height;
  24096. texture.mipmaps = texDatas.mipmaps;
  24097. }
  24098. if ( texDatas.mipmapCount === 1 ) {
  24099. texture.minFilter = LinearFilter;
  24100. }
  24101. texture.format = texDatas.format;
  24102. texture.needsUpdate = true;
  24103. if ( onLoad ) onLoad( texture );
  24104. }, onProgress, onError );
  24105. }
  24106. return texture;
  24107. }
  24108. }
  24109. class ImageLoader extends Loader {
  24110. constructor( manager ) {
  24111. super( manager );
  24112. }
  24113. load( url, onLoad, onProgress, onError ) {
  24114. if ( this.path !== undefined ) url = this.path + url;
  24115. url = this.manager.resolveURL( url );
  24116. const scope = this;
  24117. const cached = Cache.get( url );
  24118. if ( cached !== undefined ) {
  24119. scope.manager.itemStart( url );
  24120. setTimeout( function () {
  24121. if ( onLoad ) onLoad( cached );
  24122. scope.manager.itemEnd( url );
  24123. }, 0 );
  24124. return cached;
  24125. }
  24126. const image = createElementNS( 'img' );
  24127. function onImageLoad() {
  24128. removeEventListeners();
  24129. Cache.add( url, this );
  24130. if ( onLoad ) onLoad( this );
  24131. scope.manager.itemEnd( url );
  24132. }
  24133. function onImageError( event ) {
  24134. removeEventListeners();
  24135. if ( onError ) onError( event );
  24136. scope.manager.itemError( url );
  24137. scope.manager.itemEnd( url );
  24138. }
  24139. function removeEventListeners() {
  24140. image.removeEventListener( 'load', onImageLoad, false );
  24141. image.removeEventListener( 'error', onImageError, false );
  24142. }
  24143. image.addEventListener( 'load', onImageLoad, false );
  24144. image.addEventListener( 'error', onImageError, false );
  24145. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24146. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24147. }
  24148. scope.manager.itemStart( url );
  24149. image.src = url;
  24150. return image;
  24151. }
  24152. }
  24153. class CubeTextureLoader extends Loader {
  24154. constructor( manager ) {
  24155. super( manager );
  24156. }
  24157. load( urls, onLoad, onProgress, onError ) {
  24158. const texture = new CubeTexture();
  24159. const loader = new ImageLoader( this.manager );
  24160. loader.setCrossOrigin( this.crossOrigin );
  24161. loader.setPath( this.path );
  24162. let loaded = 0;
  24163. function loadTexture( i ) {
  24164. loader.load( urls[ i ], function ( image ) {
  24165. texture.images[ i ] = image;
  24166. loaded ++;
  24167. if ( loaded === 6 ) {
  24168. texture.needsUpdate = true;
  24169. if ( onLoad ) onLoad( texture );
  24170. }
  24171. }, undefined, onError );
  24172. }
  24173. for ( let i = 0; i < urls.length; ++ i ) {
  24174. loadTexture( i );
  24175. }
  24176. return texture;
  24177. }
  24178. }
  24179. /**
  24180. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24181. *
  24182. * Sub classes have to implement the parse() method which will be used in load().
  24183. */
  24184. class DataTextureLoader extends Loader {
  24185. constructor( manager ) {
  24186. super( manager );
  24187. }
  24188. load( url, onLoad, onProgress, onError ) {
  24189. const scope = this;
  24190. const texture = new DataTexture();
  24191. const loader = new FileLoader( this.manager );
  24192. loader.setResponseType( 'arraybuffer' );
  24193. loader.setRequestHeader( this.requestHeader );
  24194. loader.setPath( this.path );
  24195. loader.setWithCredentials( scope.withCredentials );
  24196. loader.load( url, function ( buffer ) {
  24197. const texData = scope.parse( buffer );
  24198. if ( ! texData ) return;
  24199. if ( texData.image !== undefined ) {
  24200. texture.image = texData.image;
  24201. } else if ( texData.data !== undefined ) {
  24202. texture.image.width = texData.width;
  24203. texture.image.height = texData.height;
  24204. texture.image.data = texData.data;
  24205. }
  24206. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24207. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24208. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24209. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24210. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24211. if ( texData.encoding !== undefined ) {
  24212. texture.encoding = texData.encoding;
  24213. }
  24214. if ( texData.flipY !== undefined ) {
  24215. texture.flipY = texData.flipY;
  24216. }
  24217. if ( texData.format !== undefined ) {
  24218. texture.format = texData.format;
  24219. }
  24220. if ( texData.type !== undefined ) {
  24221. texture.type = texData.type;
  24222. }
  24223. if ( texData.mipmaps !== undefined ) {
  24224. texture.mipmaps = texData.mipmaps;
  24225. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24226. }
  24227. if ( texData.mipmapCount === 1 ) {
  24228. texture.minFilter = LinearFilter;
  24229. }
  24230. if ( texData.generateMipmaps !== undefined ) {
  24231. texture.generateMipmaps = texData.generateMipmaps;
  24232. }
  24233. texture.needsUpdate = true;
  24234. if ( onLoad ) onLoad( texture, texData );
  24235. }, onProgress, onError );
  24236. return texture;
  24237. }
  24238. }
  24239. class TextureLoader extends Loader {
  24240. constructor( manager ) {
  24241. super( manager );
  24242. }
  24243. load( url, onLoad, onProgress, onError ) {
  24244. const texture = new Texture();
  24245. const loader = new ImageLoader( this.manager );
  24246. loader.setCrossOrigin( this.crossOrigin );
  24247. loader.setPath( this.path );
  24248. loader.load( url, function ( image ) {
  24249. texture.image = image;
  24250. texture.needsUpdate = true;
  24251. if ( onLoad !== undefined ) {
  24252. onLoad( texture );
  24253. }
  24254. }, onProgress, onError );
  24255. return texture;
  24256. }
  24257. }
  24258. class Light extends Object3D {
  24259. constructor( color, intensity = 1 ) {
  24260. super();
  24261. this.isLight = true;
  24262. this.type = 'Light';
  24263. this.color = new Color( color );
  24264. this.intensity = intensity;
  24265. }
  24266. dispose() {
  24267. // Empty here in base class; some subclasses override.
  24268. }
  24269. copy( source, recursive ) {
  24270. super.copy( source, recursive );
  24271. this.color.copy( source.color );
  24272. this.intensity = source.intensity;
  24273. return this;
  24274. }
  24275. toJSON( meta ) {
  24276. const data = super.toJSON( meta );
  24277. data.object.color = this.color.getHex();
  24278. data.object.intensity = this.intensity;
  24279. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24280. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24281. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24282. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24283. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24284. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24285. return data;
  24286. }
  24287. }
  24288. class HemisphereLight extends Light {
  24289. constructor( skyColor, groundColor, intensity ) {
  24290. super( skyColor, intensity );
  24291. this.isHemisphereLight = true;
  24292. this.type = 'HemisphereLight';
  24293. this.position.copy( Object3D.DEFAULT_UP );
  24294. this.updateMatrix();
  24295. this.groundColor = new Color( groundColor );
  24296. }
  24297. copy( source, recursive ) {
  24298. super.copy( source, recursive );
  24299. this.groundColor.copy( source.groundColor );
  24300. return this;
  24301. }
  24302. }
  24303. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24304. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24305. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24306. class LightShadow {
  24307. constructor( camera ) {
  24308. this.camera = camera;
  24309. this.bias = 0;
  24310. this.normalBias = 0;
  24311. this.radius = 1;
  24312. this.blurSamples = 8;
  24313. this.mapSize = new Vector2( 512, 512 );
  24314. this.map = null;
  24315. this.mapPass = null;
  24316. this.matrix = new Matrix4();
  24317. this.autoUpdate = true;
  24318. this.needsUpdate = false;
  24319. this._frustum = new Frustum();
  24320. this._frameExtents = new Vector2( 1, 1 );
  24321. this._viewportCount = 1;
  24322. this._viewports = [
  24323. new Vector4( 0, 0, 1, 1 )
  24324. ];
  24325. }
  24326. getViewportCount() {
  24327. return this._viewportCount;
  24328. }
  24329. getFrustum() {
  24330. return this._frustum;
  24331. }
  24332. updateMatrices( light ) {
  24333. const shadowCamera = this.camera;
  24334. const shadowMatrix = this.matrix;
  24335. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24336. shadowCamera.position.copy( _lightPositionWorld$1 );
  24337. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24338. shadowCamera.lookAt( _lookTarget$1 );
  24339. shadowCamera.updateMatrixWorld();
  24340. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24341. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24342. shadowMatrix.set(
  24343. 0.5, 0.0, 0.0, 0.5,
  24344. 0.0, 0.5, 0.0, 0.5,
  24345. 0.0, 0.0, 0.5, 0.5,
  24346. 0.0, 0.0, 0.0, 1.0
  24347. );
  24348. shadowMatrix.multiply( _projScreenMatrix$1 );
  24349. }
  24350. getViewport( viewportIndex ) {
  24351. return this._viewports[ viewportIndex ];
  24352. }
  24353. getFrameExtents() {
  24354. return this._frameExtents;
  24355. }
  24356. dispose() {
  24357. if ( this.map ) {
  24358. this.map.dispose();
  24359. }
  24360. if ( this.mapPass ) {
  24361. this.mapPass.dispose();
  24362. }
  24363. }
  24364. copy( source ) {
  24365. this.camera = source.camera.clone();
  24366. this.bias = source.bias;
  24367. this.radius = source.radius;
  24368. this.mapSize.copy( source.mapSize );
  24369. return this;
  24370. }
  24371. clone() {
  24372. return new this.constructor().copy( this );
  24373. }
  24374. toJSON() {
  24375. const object = {};
  24376. if ( this.bias !== 0 ) object.bias = this.bias;
  24377. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24378. if ( this.radius !== 1 ) object.radius = this.radius;
  24379. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24380. object.camera = this.camera.toJSON( false ).object;
  24381. delete object.camera.matrix;
  24382. return object;
  24383. }
  24384. }
  24385. class SpotLightShadow extends LightShadow {
  24386. constructor() {
  24387. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24388. this.isSpotLightShadow = true;
  24389. this.focus = 1;
  24390. }
  24391. updateMatrices( light ) {
  24392. const camera = this.camera;
  24393. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24394. const aspect = this.mapSize.width / this.mapSize.height;
  24395. const far = light.distance || camera.far;
  24396. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24397. camera.fov = fov;
  24398. camera.aspect = aspect;
  24399. camera.far = far;
  24400. camera.updateProjectionMatrix();
  24401. }
  24402. super.updateMatrices( light );
  24403. }
  24404. copy( source ) {
  24405. super.copy( source );
  24406. this.focus = source.focus;
  24407. return this;
  24408. }
  24409. }
  24410. class SpotLight extends Light {
  24411. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24412. super( color, intensity );
  24413. this.isSpotLight = true;
  24414. this.type = 'SpotLight';
  24415. this.position.copy( Object3D.DEFAULT_UP );
  24416. this.updateMatrix();
  24417. this.target = new Object3D();
  24418. this.distance = distance;
  24419. this.angle = angle;
  24420. this.penumbra = penumbra;
  24421. this.decay = decay;
  24422. this.map = null;
  24423. this.shadow = new SpotLightShadow();
  24424. }
  24425. get power() {
  24426. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24427. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24428. return this.intensity * Math.PI;
  24429. }
  24430. set power( power ) {
  24431. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24432. this.intensity = power / Math.PI;
  24433. }
  24434. dispose() {
  24435. this.shadow.dispose();
  24436. }
  24437. copy( source, recursive ) {
  24438. super.copy( source, recursive );
  24439. this.distance = source.distance;
  24440. this.angle = source.angle;
  24441. this.penumbra = source.penumbra;
  24442. this.decay = source.decay;
  24443. this.target = source.target.clone();
  24444. this.shadow = source.shadow.clone();
  24445. return this;
  24446. }
  24447. }
  24448. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24449. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24450. const _lookTarget = /*@__PURE__*/ new Vector3();
  24451. class PointLightShadow extends LightShadow {
  24452. constructor() {
  24453. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24454. this.isPointLightShadow = true;
  24455. this._frameExtents = new Vector2( 4, 2 );
  24456. this._viewportCount = 6;
  24457. this._viewports = [
  24458. // These viewports map a cube-map onto a 2D texture with the
  24459. // following orientation:
  24460. //
  24461. // xzXZ
  24462. // y Y
  24463. //
  24464. // X - Positive x direction
  24465. // x - Negative x direction
  24466. // Y - Positive y direction
  24467. // y - Negative y direction
  24468. // Z - Positive z direction
  24469. // z - Negative z direction
  24470. // positive X
  24471. new Vector4( 2, 1, 1, 1 ),
  24472. // negative X
  24473. new Vector4( 0, 1, 1, 1 ),
  24474. // positive Z
  24475. new Vector4( 3, 1, 1, 1 ),
  24476. // negative Z
  24477. new Vector4( 1, 1, 1, 1 ),
  24478. // positive Y
  24479. new Vector4( 3, 0, 1, 1 ),
  24480. // negative Y
  24481. new Vector4( 1, 0, 1, 1 )
  24482. ];
  24483. this._cubeDirections = [
  24484. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24485. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24486. ];
  24487. this._cubeUps = [
  24488. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24489. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24490. ];
  24491. }
  24492. updateMatrices( light, viewportIndex = 0 ) {
  24493. const camera = this.camera;
  24494. const shadowMatrix = this.matrix;
  24495. const far = light.distance || camera.far;
  24496. if ( far !== camera.far ) {
  24497. camera.far = far;
  24498. camera.updateProjectionMatrix();
  24499. }
  24500. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24501. camera.position.copy( _lightPositionWorld );
  24502. _lookTarget.copy( camera.position );
  24503. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24504. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24505. camera.lookAt( _lookTarget );
  24506. camera.updateMatrixWorld();
  24507. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24508. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24509. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24510. }
  24511. }
  24512. class PointLight extends Light {
  24513. constructor( color, intensity, distance = 0, decay = 2 ) {
  24514. super( color, intensity );
  24515. this.isPointLight = true;
  24516. this.type = 'PointLight';
  24517. this.distance = distance;
  24518. this.decay = decay;
  24519. this.shadow = new PointLightShadow();
  24520. }
  24521. get power() {
  24522. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24523. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24524. return this.intensity * 4 * Math.PI;
  24525. }
  24526. set power( power ) {
  24527. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24528. this.intensity = power / ( 4 * Math.PI );
  24529. }
  24530. dispose() {
  24531. this.shadow.dispose();
  24532. }
  24533. copy( source, recursive ) {
  24534. super.copy( source, recursive );
  24535. this.distance = source.distance;
  24536. this.decay = source.decay;
  24537. this.shadow = source.shadow.clone();
  24538. return this;
  24539. }
  24540. }
  24541. class DirectionalLightShadow extends LightShadow {
  24542. constructor() {
  24543. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24544. this.isDirectionalLightShadow = true;
  24545. }
  24546. }
  24547. class DirectionalLight extends Light {
  24548. constructor( color, intensity ) {
  24549. super( color, intensity );
  24550. this.isDirectionalLight = true;
  24551. this.type = 'DirectionalLight';
  24552. this.position.copy( Object3D.DEFAULT_UP );
  24553. this.updateMatrix();
  24554. this.target = new Object3D();
  24555. this.shadow = new DirectionalLightShadow();
  24556. }
  24557. dispose() {
  24558. this.shadow.dispose();
  24559. }
  24560. copy( source ) {
  24561. super.copy( source );
  24562. this.target = source.target.clone();
  24563. this.shadow = source.shadow.clone();
  24564. return this;
  24565. }
  24566. }
  24567. class AmbientLight extends Light {
  24568. constructor( color, intensity ) {
  24569. super( color, intensity );
  24570. this.isAmbientLight = true;
  24571. this.type = 'AmbientLight';
  24572. }
  24573. }
  24574. class RectAreaLight extends Light {
  24575. constructor( color, intensity, width = 10, height = 10 ) {
  24576. super( color, intensity );
  24577. this.isRectAreaLight = true;
  24578. this.type = 'RectAreaLight';
  24579. this.width = width;
  24580. this.height = height;
  24581. }
  24582. get power() {
  24583. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24584. return this.intensity * this.width * this.height * Math.PI;
  24585. }
  24586. set power( power ) {
  24587. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24588. this.intensity = power / ( this.width * this.height * Math.PI );
  24589. }
  24590. copy( source ) {
  24591. super.copy( source );
  24592. this.width = source.width;
  24593. this.height = source.height;
  24594. return this;
  24595. }
  24596. toJSON( meta ) {
  24597. const data = super.toJSON( meta );
  24598. data.object.width = this.width;
  24599. data.object.height = this.height;
  24600. return data;
  24601. }
  24602. }
  24603. /**
  24604. * Primary reference:
  24605. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24606. *
  24607. * Secondary reference:
  24608. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24609. */
  24610. // 3-band SH defined by 9 coefficients
  24611. class SphericalHarmonics3 {
  24612. constructor() {
  24613. this.isSphericalHarmonics3 = true;
  24614. this.coefficients = [];
  24615. for ( let i = 0; i < 9; i ++ ) {
  24616. this.coefficients.push( new Vector3() );
  24617. }
  24618. }
  24619. set( coefficients ) {
  24620. for ( let i = 0; i < 9; i ++ ) {
  24621. this.coefficients[ i ].copy( coefficients[ i ] );
  24622. }
  24623. return this;
  24624. }
  24625. zero() {
  24626. for ( let i = 0; i < 9; i ++ ) {
  24627. this.coefficients[ i ].set( 0, 0, 0 );
  24628. }
  24629. return this;
  24630. }
  24631. // get the radiance in the direction of the normal
  24632. // target is a Vector3
  24633. getAt( normal, target ) {
  24634. // normal is assumed to be unit length
  24635. const x = normal.x, y = normal.y, z = normal.z;
  24636. const coeff = this.coefficients;
  24637. // band 0
  24638. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24639. // band 1
  24640. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24641. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24642. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24643. // band 2
  24644. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24645. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24646. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24647. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24648. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24649. return target;
  24650. }
  24651. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24652. // target is a Vector3
  24653. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24654. getIrradianceAt( normal, target ) {
  24655. // normal is assumed to be unit length
  24656. const x = normal.x, y = normal.y, z = normal.z;
  24657. const coeff = this.coefficients;
  24658. // band 0
  24659. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24660. // band 1
  24661. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24662. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24663. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24664. // band 2
  24665. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24666. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24667. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24668. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24669. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24670. return target;
  24671. }
  24672. add( sh ) {
  24673. for ( let i = 0; i < 9; i ++ ) {
  24674. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24675. }
  24676. return this;
  24677. }
  24678. addScaledSH( sh, s ) {
  24679. for ( let i = 0; i < 9; i ++ ) {
  24680. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24681. }
  24682. return this;
  24683. }
  24684. scale( s ) {
  24685. for ( let i = 0; i < 9; i ++ ) {
  24686. this.coefficients[ i ].multiplyScalar( s );
  24687. }
  24688. return this;
  24689. }
  24690. lerp( sh, alpha ) {
  24691. for ( let i = 0; i < 9; i ++ ) {
  24692. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24693. }
  24694. return this;
  24695. }
  24696. equals( sh ) {
  24697. for ( let i = 0; i < 9; i ++ ) {
  24698. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24699. return false;
  24700. }
  24701. }
  24702. return true;
  24703. }
  24704. copy( sh ) {
  24705. return this.set( sh.coefficients );
  24706. }
  24707. clone() {
  24708. return new this.constructor().copy( this );
  24709. }
  24710. fromArray( array, offset = 0 ) {
  24711. const coefficients = this.coefficients;
  24712. for ( let i = 0; i < 9; i ++ ) {
  24713. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24714. }
  24715. return this;
  24716. }
  24717. toArray( array = [], offset = 0 ) {
  24718. const coefficients = this.coefficients;
  24719. for ( let i = 0; i < 9; i ++ ) {
  24720. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24721. }
  24722. return array;
  24723. }
  24724. // evaluate the basis functions
  24725. // shBasis is an Array[ 9 ]
  24726. static getBasisAt( normal, shBasis ) {
  24727. // normal is assumed to be unit length
  24728. const x = normal.x, y = normal.y, z = normal.z;
  24729. // band 0
  24730. shBasis[ 0 ] = 0.282095;
  24731. // band 1
  24732. shBasis[ 1 ] = 0.488603 * y;
  24733. shBasis[ 2 ] = 0.488603 * z;
  24734. shBasis[ 3 ] = 0.488603 * x;
  24735. // band 2
  24736. shBasis[ 4 ] = 1.092548 * x * y;
  24737. shBasis[ 5 ] = 1.092548 * y * z;
  24738. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24739. shBasis[ 7 ] = 1.092548 * x * z;
  24740. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24741. }
  24742. }
  24743. class LightProbe extends Light {
  24744. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24745. super( undefined, intensity );
  24746. this.isLightProbe = true;
  24747. this.sh = sh;
  24748. }
  24749. copy( source ) {
  24750. super.copy( source );
  24751. this.sh.copy( source.sh );
  24752. return this;
  24753. }
  24754. fromJSON( json ) {
  24755. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24756. this.sh.fromArray( json.sh );
  24757. return this;
  24758. }
  24759. toJSON( meta ) {
  24760. const data = super.toJSON( meta );
  24761. data.object.sh = this.sh.toArray();
  24762. return data;
  24763. }
  24764. }
  24765. class MaterialLoader extends Loader {
  24766. constructor( manager ) {
  24767. super( manager );
  24768. this.textures = {};
  24769. }
  24770. load( url, onLoad, onProgress, onError ) {
  24771. const scope = this;
  24772. const loader = new FileLoader( scope.manager );
  24773. loader.setPath( scope.path );
  24774. loader.setRequestHeader( scope.requestHeader );
  24775. loader.setWithCredentials( scope.withCredentials );
  24776. loader.load( url, function ( text ) {
  24777. try {
  24778. onLoad( scope.parse( JSON.parse( text ) ) );
  24779. } catch ( e ) {
  24780. if ( onError ) {
  24781. onError( e );
  24782. } else {
  24783. console.error( e );
  24784. }
  24785. scope.manager.itemError( url );
  24786. }
  24787. }, onProgress, onError );
  24788. }
  24789. parse( json ) {
  24790. const textures = this.textures;
  24791. function getTexture( name ) {
  24792. if ( textures[ name ] === undefined ) {
  24793. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24794. }
  24795. return textures[ name ];
  24796. }
  24797. const material = MaterialLoader.createMaterialFromType( json.type );
  24798. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24799. if ( json.name !== undefined ) material.name = json.name;
  24800. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24801. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24802. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24803. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24804. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24805. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24806. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24807. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24808. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24809. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24810. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24811. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24812. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24813. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24814. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24815. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24816. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24817. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24818. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24819. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24820. if ( json.fog !== undefined ) material.fog = json.fog;
  24821. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24822. if ( json.blending !== undefined ) material.blending = json.blending;
  24823. if ( json.combine !== undefined ) material.combine = json.combine;
  24824. if ( json.side !== undefined ) material.side = json.side;
  24825. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24826. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24827. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24828. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24829. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24830. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24831. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24832. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24833. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24834. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24835. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24836. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24837. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24838. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24839. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24840. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24841. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24842. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24843. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24844. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24845. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24846. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24847. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24848. if ( json.scale !== undefined ) material.scale = json.scale;
  24849. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24850. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24851. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24852. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24853. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24854. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24855. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24856. if ( json.visible !== undefined ) material.visible = json.visible;
  24857. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24858. if ( json.userData !== undefined ) material.userData = json.userData;
  24859. if ( json.vertexColors !== undefined ) {
  24860. if ( typeof json.vertexColors === 'number' ) {
  24861. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24862. } else {
  24863. material.vertexColors = json.vertexColors;
  24864. }
  24865. }
  24866. // Shader Material
  24867. if ( json.uniforms !== undefined ) {
  24868. for ( const name in json.uniforms ) {
  24869. const uniform = json.uniforms[ name ];
  24870. material.uniforms[ name ] = {};
  24871. switch ( uniform.type ) {
  24872. case 't':
  24873. material.uniforms[ name ].value = getTexture( uniform.value );
  24874. break;
  24875. case 'c':
  24876. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24877. break;
  24878. case 'v2':
  24879. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24880. break;
  24881. case 'v3':
  24882. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24883. break;
  24884. case 'v4':
  24885. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24886. break;
  24887. case 'm3':
  24888. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24889. break;
  24890. case 'm4':
  24891. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24892. break;
  24893. default:
  24894. material.uniforms[ name ].value = uniform.value;
  24895. }
  24896. }
  24897. }
  24898. if ( json.defines !== undefined ) material.defines = json.defines;
  24899. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24900. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24901. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24902. if ( json.extensions !== undefined ) {
  24903. for ( const key in json.extensions ) {
  24904. material.extensions[ key ] = json.extensions[ key ];
  24905. }
  24906. }
  24907. // for PointsMaterial
  24908. if ( json.size !== undefined ) material.size = json.size;
  24909. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24910. // maps
  24911. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24912. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24913. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24914. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24915. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24916. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24917. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24918. if ( json.normalScale !== undefined ) {
  24919. let normalScale = json.normalScale;
  24920. if ( Array.isArray( normalScale ) === false ) {
  24921. // Blender exporter used to export a scalar. See #7459
  24922. normalScale = [ normalScale, normalScale ];
  24923. }
  24924. material.normalScale = new Vector2().fromArray( normalScale );
  24925. }
  24926. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24927. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24928. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24929. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24930. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24931. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24932. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24933. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24934. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24935. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24936. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24937. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24938. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24939. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24940. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24941. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24942. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24943. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24944. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24945. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24946. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24947. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24948. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24949. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24950. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24951. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24952. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24953. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24954. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24955. return material;
  24956. }
  24957. setTextures( value ) {
  24958. this.textures = value;
  24959. return this;
  24960. }
  24961. static createMaterialFromType( type ) {
  24962. const materialLib = {
  24963. ShadowMaterial,
  24964. SpriteMaterial,
  24965. RawShaderMaterial,
  24966. ShaderMaterial,
  24967. PointsMaterial,
  24968. MeshPhysicalMaterial,
  24969. MeshStandardMaterial,
  24970. MeshPhongMaterial,
  24971. MeshToonMaterial,
  24972. MeshNormalMaterial,
  24973. MeshLambertMaterial,
  24974. MeshDepthMaterial,
  24975. MeshDistanceMaterial,
  24976. MeshBasicMaterial,
  24977. MeshMatcapMaterial,
  24978. LineDashedMaterial,
  24979. LineBasicMaterial,
  24980. Material
  24981. };
  24982. return new materialLib[ type ]();
  24983. }
  24984. }
  24985. class LoaderUtils {
  24986. static decodeText( array ) {
  24987. if ( typeof TextDecoder !== 'undefined' ) {
  24988. return new TextDecoder().decode( array );
  24989. }
  24990. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24991. // throws a "maximum call stack size exceeded" error for large arrays.
  24992. let s = '';
  24993. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24994. // Implicitly assumes little-endian.
  24995. s += String.fromCharCode( array[ i ] );
  24996. }
  24997. try {
  24998. // merges multi-byte utf-8 characters.
  24999. return decodeURIComponent( escape( s ) );
  25000. } catch ( e ) { // see #16358
  25001. return s;
  25002. }
  25003. }
  25004. static extractUrlBase( url ) {
  25005. const index = url.lastIndexOf( '/' );
  25006. if ( index === - 1 ) return './';
  25007. return url.slice( 0, index + 1 );
  25008. }
  25009. static resolveURL( url, path ) {
  25010. // Invalid URL
  25011. if ( typeof url !== 'string' || url === '' ) return '';
  25012. // Host Relative URL
  25013. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25014. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25015. }
  25016. // Absolute URL http://,https://,//
  25017. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25018. // Data URI
  25019. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25020. // Blob URL
  25021. if ( /^blob:.*$/i.test( url ) ) return url;
  25022. // Relative URL
  25023. return path + url;
  25024. }
  25025. }
  25026. class InstancedBufferGeometry extends BufferGeometry {
  25027. constructor() {
  25028. super();
  25029. this.isInstancedBufferGeometry = true;
  25030. this.type = 'InstancedBufferGeometry';
  25031. this.instanceCount = Infinity;
  25032. }
  25033. copy( source ) {
  25034. super.copy( source );
  25035. this.instanceCount = source.instanceCount;
  25036. return this;
  25037. }
  25038. toJSON() {
  25039. const data = super.toJSON();
  25040. data.instanceCount = this.instanceCount;
  25041. data.isInstancedBufferGeometry = true;
  25042. return data;
  25043. }
  25044. }
  25045. class BufferGeometryLoader extends Loader {
  25046. constructor( manager ) {
  25047. super( manager );
  25048. }
  25049. load( url, onLoad, onProgress, onError ) {
  25050. const scope = this;
  25051. const loader = new FileLoader( scope.manager );
  25052. loader.setPath( scope.path );
  25053. loader.setRequestHeader( scope.requestHeader );
  25054. loader.setWithCredentials( scope.withCredentials );
  25055. loader.load( url, function ( text ) {
  25056. try {
  25057. onLoad( scope.parse( JSON.parse( text ) ) );
  25058. } catch ( e ) {
  25059. if ( onError ) {
  25060. onError( e );
  25061. } else {
  25062. console.error( e );
  25063. }
  25064. scope.manager.itemError( url );
  25065. }
  25066. }, onProgress, onError );
  25067. }
  25068. parse( json ) {
  25069. const interleavedBufferMap = {};
  25070. const arrayBufferMap = {};
  25071. function getInterleavedBuffer( json, uuid ) {
  25072. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25073. const interleavedBuffers = json.interleavedBuffers;
  25074. const interleavedBuffer = interleavedBuffers[ uuid ];
  25075. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25076. const array = getTypedArray( interleavedBuffer.type, buffer );
  25077. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25078. ib.uuid = interleavedBuffer.uuid;
  25079. interleavedBufferMap[ uuid ] = ib;
  25080. return ib;
  25081. }
  25082. function getArrayBuffer( json, uuid ) {
  25083. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25084. const arrayBuffers = json.arrayBuffers;
  25085. const arrayBuffer = arrayBuffers[ uuid ];
  25086. const ab = new Uint32Array( arrayBuffer ).buffer;
  25087. arrayBufferMap[ uuid ] = ab;
  25088. return ab;
  25089. }
  25090. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25091. const index = json.data.index;
  25092. if ( index !== undefined ) {
  25093. const typedArray = getTypedArray( index.type, index.array );
  25094. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25095. }
  25096. const attributes = json.data.attributes;
  25097. for ( const key in attributes ) {
  25098. const attribute = attributes[ key ];
  25099. let bufferAttribute;
  25100. if ( attribute.isInterleavedBufferAttribute ) {
  25101. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25102. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25103. } else {
  25104. const typedArray = getTypedArray( attribute.type, attribute.array );
  25105. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25106. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25107. }
  25108. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25109. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25110. if ( attribute.updateRange !== undefined ) {
  25111. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25112. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25113. }
  25114. geometry.setAttribute( key, bufferAttribute );
  25115. }
  25116. const morphAttributes = json.data.morphAttributes;
  25117. if ( morphAttributes ) {
  25118. for ( const key in morphAttributes ) {
  25119. const attributeArray = morphAttributes[ key ];
  25120. const array = [];
  25121. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25122. const attribute = attributeArray[ i ];
  25123. let bufferAttribute;
  25124. if ( attribute.isInterleavedBufferAttribute ) {
  25125. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25126. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25127. } else {
  25128. const typedArray = getTypedArray( attribute.type, attribute.array );
  25129. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25130. }
  25131. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25132. array.push( bufferAttribute );
  25133. }
  25134. geometry.morphAttributes[ key ] = array;
  25135. }
  25136. }
  25137. const morphTargetsRelative = json.data.morphTargetsRelative;
  25138. if ( morphTargetsRelative ) {
  25139. geometry.morphTargetsRelative = true;
  25140. }
  25141. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25142. if ( groups !== undefined ) {
  25143. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25144. const group = groups[ i ];
  25145. geometry.addGroup( group.start, group.count, group.materialIndex );
  25146. }
  25147. }
  25148. const boundingSphere = json.data.boundingSphere;
  25149. if ( boundingSphere !== undefined ) {
  25150. const center = new Vector3();
  25151. if ( boundingSphere.center !== undefined ) {
  25152. center.fromArray( boundingSphere.center );
  25153. }
  25154. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25155. }
  25156. if ( json.name ) geometry.name = json.name;
  25157. if ( json.userData ) geometry.userData = json.userData;
  25158. return geometry;
  25159. }
  25160. }
  25161. class ObjectLoader extends Loader {
  25162. constructor( manager ) {
  25163. super( manager );
  25164. }
  25165. load( url, onLoad, onProgress, onError ) {
  25166. const scope = this;
  25167. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25168. this.resourcePath = this.resourcePath || path;
  25169. const loader = new FileLoader( this.manager );
  25170. loader.setPath( this.path );
  25171. loader.setRequestHeader( this.requestHeader );
  25172. loader.setWithCredentials( this.withCredentials );
  25173. loader.load( url, function ( text ) {
  25174. let json = null;
  25175. try {
  25176. json = JSON.parse( text );
  25177. } catch ( error ) {
  25178. if ( onError !== undefined ) onError( error );
  25179. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25180. return;
  25181. }
  25182. const metadata = json.metadata;
  25183. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25184. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25185. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25186. return;
  25187. }
  25188. scope.parse( json, onLoad );
  25189. }, onProgress, onError );
  25190. }
  25191. async loadAsync( url, onProgress ) {
  25192. const scope = this;
  25193. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25194. this.resourcePath = this.resourcePath || path;
  25195. const loader = new FileLoader( this.manager );
  25196. loader.setPath( this.path );
  25197. loader.setRequestHeader( this.requestHeader );
  25198. loader.setWithCredentials( this.withCredentials );
  25199. const text = await loader.loadAsync( url, onProgress );
  25200. const json = JSON.parse( text );
  25201. const metadata = json.metadata;
  25202. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25203. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25204. }
  25205. return await scope.parseAsync( json );
  25206. }
  25207. parse( json, onLoad ) {
  25208. const animations = this.parseAnimations( json.animations );
  25209. const shapes = this.parseShapes( json.shapes );
  25210. const geometries = this.parseGeometries( json.geometries, shapes );
  25211. const images = this.parseImages( json.images, function () {
  25212. if ( onLoad !== undefined ) onLoad( object );
  25213. } );
  25214. const textures = this.parseTextures( json.textures, images );
  25215. const materials = this.parseMaterials( json.materials, textures );
  25216. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25217. const skeletons = this.parseSkeletons( json.skeletons, object );
  25218. this.bindSkeletons( object, skeletons );
  25219. //
  25220. if ( onLoad !== undefined ) {
  25221. let hasImages = false;
  25222. for ( const uuid in images ) {
  25223. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25224. hasImages = true;
  25225. break;
  25226. }
  25227. }
  25228. if ( hasImages === false ) onLoad( object );
  25229. }
  25230. return object;
  25231. }
  25232. async parseAsync( json ) {
  25233. const animations = this.parseAnimations( json.animations );
  25234. const shapes = this.parseShapes( json.shapes );
  25235. const geometries = this.parseGeometries( json.geometries, shapes );
  25236. const images = await this.parseImagesAsync( json.images );
  25237. const textures = this.parseTextures( json.textures, images );
  25238. const materials = this.parseMaterials( json.materials, textures );
  25239. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25240. const skeletons = this.parseSkeletons( json.skeletons, object );
  25241. this.bindSkeletons( object, skeletons );
  25242. return object;
  25243. }
  25244. parseShapes( json ) {
  25245. const shapes = {};
  25246. if ( json !== undefined ) {
  25247. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25248. const shape = new Shape().fromJSON( json[ i ] );
  25249. shapes[ shape.uuid ] = shape;
  25250. }
  25251. }
  25252. return shapes;
  25253. }
  25254. parseSkeletons( json, object ) {
  25255. const skeletons = {};
  25256. const bones = {};
  25257. // generate bone lookup table
  25258. object.traverse( function ( child ) {
  25259. if ( child.isBone ) bones[ child.uuid ] = child;
  25260. } );
  25261. // create skeletons
  25262. if ( json !== undefined ) {
  25263. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25264. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25265. skeletons[ skeleton.uuid ] = skeleton;
  25266. }
  25267. }
  25268. return skeletons;
  25269. }
  25270. parseGeometries( json, shapes ) {
  25271. const geometries = {};
  25272. if ( json !== undefined ) {
  25273. const bufferGeometryLoader = new BufferGeometryLoader();
  25274. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25275. let geometry;
  25276. const data = json[ i ];
  25277. switch ( data.type ) {
  25278. case 'BufferGeometry':
  25279. case 'InstancedBufferGeometry':
  25280. geometry = bufferGeometryLoader.parse( data );
  25281. break;
  25282. default:
  25283. if ( data.type in Geometries ) {
  25284. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25285. } else {
  25286. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25287. }
  25288. }
  25289. geometry.uuid = data.uuid;
  25290. if ( data.name !== undefined ) geometry.name = data.name;
  25291. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25292. geometries[ data.uuid ] = geometry;
  25293. }
  25294. }
  25295. return geometries;
  25296. }
  25297. parseMaterials( json, textures ) {
  25298. const cache = {}; // MultiMaterial
  25299. const materials = {};
  25300. if ( json !== undefined ) {
  25301. const loader = new MaterialLoader();
  25302. loader.setTextures( textures );
  25303. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25304. const data = json[ i ];
  25305. if ( cache[ data.uuid ] === undefined ) {
  25306. cache[ data.uuid ] = loader.parse( data );
  25307. }
  25308. materials[ data.uuid ] = cache[ data.uuid ];
  25309. }
  25310. }
  25311. return materials;
  25312. }
  25313. parseAnimations( json ) {
  25314. const animations = {};
  25315. if ( json !== undefined ) {
  25316. for ( let i = 0; i < json.length; i ++ ) {
  25317. const data = json[ i ];
  25318. const clip = AnimationClip.parse( data );
  25319. animations[ clip.uuid ] = clip;
  25320. }
  25321. }
  25322. return animations;
  25323. }
  25324. parseImages( json, onLoad ) {
  25325. const scope = this;
  25326. const images = {};
  25327. let loader;
  25328. function loadImage( url ) {
  25329. scope.manager.itemStart( url );
  25330. return loader.load( url, function () {
  25331. scope.manager.itemEnd( url );
  25332. }, undefined, function () {
  25333. scope.manager.itemError( url );
  25334. scope.manager.itemEnd( url );
  25335. } );
  25336. }
  25337. function deserializeImage( image ) {
  25338. if ( typeof image === 'string' ) {
  25339. const url = image;
  25340. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25341. return loadImage( path );
  25342. } else {
  25343. if ( image.data ) {
  25344. return {
  25345. data: getTypedArray( image.type, image.data ),
  25346. width: image.width,
  25347. height: image.height
  25348. };
  25349. } else {
  25350. return null;
  25351. }
  25352. }
  25353. }
  25354. if ( json !== undefined && json.length > 0 ) {
  25355. const manager = new LoadingManager( onLoad );
  25356. loader = new ImageLoader( manager );
  25357. loader.setCrossOrigin( this.crossOrigin );
  25358. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25359. const image = json[ i ];
  25360. const url = image.url;
  25361. if ( Array.isArray( url ) ) {
  25362. // load array of images e.g CubeTexture
  25363. const imageArray = [];
  25364. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25365. const currentUrl = url[ j ];
  25366. const deserializedImage = deserializeImage( currentUrl );
  25367. if ( deserializedImage !== null ) {
  25368. if ( deserializedImage instanceof HTMLImageElement ) {
  25369. imageArray.push( deserializedImage );
  25370. } else {
  25371. // special case: handle array of data textures for cube textures
  25372. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25373. }
  25374. }
  25375. }
  25376. images[ image.uuid ] = new Source( imageArray );
  25377. } else {
  25378. // load single image
  25379. const deserializedImage = deserializeImage( image.url );
  25380. images[ image.uuid ] = new Source( deserializedImage );
  25381. }
  25382. }
  25383. }
  25384. return images;
  25385. }
  25386. async parseImagesAsync( json ) {
  25387. const scope = this;
  25388. const images = {};
  25389. let loader;
  25390. async function deserializeImage( image ) {
  25391. if ( typeof image === 'string' ) {
  25392. const url = image;
  25393. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25394. return await loader.loadAsync( path );
  25395. } else {
  25396. if ( image.data ) {
  25397. return {
  25398. data: getTypedArray( image.type, image.data ),
  25399. width: image.width,
  25400. height: image.height
  25401. };
  25402. } else {
  25403. return null;
  25404. }
  25405. }
  25406. }
  25407. if ( json !== undefined && json.length > 0 ) {
  25408. loader = new ImageLoader( this.manager );
  25409. loader.setCrossOrigin( this.crossOrigin );
  25410. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25411. const image = json[ i ];
  25412. const url = image.url;
  25413. if ( Array.isArray( url ) ) {
  25414. // load array of images e.g CubeTexture
  25415. const imageArray = [];
  25416. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25417. const currentUrl = url[ j ];
  25418. const deserializedImage = await deserializeImage( currentUrl );
  25419. if ( deserializedImage !== null ) {
  25420. if ( deserializedImage instanceof HTMLImageElement ) {
  25421. imageArray.push( deserializedImage );
  25422. } else {
  25423. // special case: handle array of data textures for cube textures
  25424. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25425. }
  25426. }
  25427. }
  25428. images[ image.uuid ] = new Source( imageArray );
  25429. } else {
  25430. // load single image
  25431. const deserializedImage = await deserializeImage( image.url );
  25432. images[ image.uuid ] = new Source( deserializedImage );
  25433. }
  25434. }
  25435. }
  25436. return images;
  25437. }
  25438. parseTextures( json, images ) {
  25439. function parseConstant( value, type ) {
  25440. if ( typeof value === 'number' ) return value;
  25441. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25442. return type[ value ];
  25443. }
  25444. const textures = {};
  25445. if ( json !== undefined ) {
  25446. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25447. const data = json[ i ];
  25448. if ( data.image === undefined ) {
  25449. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25450. }
  25451. if ( images[ data.image ] === undefined ) {
  25452. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25453. }
  25454. const source = images[ data.image ];
  25455. const image = source.data;
  25456. let texture;
  25457. if ( Array.isArray( image ) ) {
  25458. texture = new CubeTexture();
  25459. if ( image.length === 6 ) texture.needsUpdate = true;
  25460. } else {
  25461. if ( image && image.data ) {
  25462. texture = new DataTexture();
  25463. } else {
  25464. texture = new Texture();
  25465. }
  25466. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25467. }
  25468. texture.source = source;
  25469. texture.uuid = data.uuid;
  25470. if ( data.name !== undefined ) texture.name = data.name;
  25471. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25472. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25473. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25474. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25475. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25476. if ( data.wrap !== undefined ) {
  25477. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25478. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25479. }
  25480. if ( data.format !== undefined ) texture.format = data.format;
  25481. if ( data.type !== undefined ) texture.type = data.type;
  25482. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25483. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25484. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25485. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25486. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25487. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25488. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25489. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25490. if ( data.userData !== undefined ) texture.userData = data.userData;
  25491. textures[ data.uuid ] = texture;
  25492. }
  25493. }
  25494. return textures;
  25495. }
  25496. parseObject( data, geometries, materials, textures, animations ) {
  25497. let object;
  25498. function getGeometry( name ) {
  25499. if ( geometries[ name ] === undefined ) {
  25500. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25501. }
  25502. return geometries[ name ];
  25503. }
  25504. function getMaterial( name ) {
  25505. if ( name === undefined ) return undefined;
  25506. if ( Array.isArray( name ) ) {
  25507. const array = [];
  25508. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25509. const uuid = name[ i ];
  25510. if ( materials[ uuid ] === undefined ) {
  25511. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25512. }
  25513. array.push( materials[ uuid ] );
  25514. }
  25515. return array;
  25516. }
  25517. if ( materials[ name ] === undefined ) {
  25518. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25519. }
  25520. return materials[ name ];
  25521. }
  25522. function getTexture( uuid ) {
  25523. if ( textures[ uuid ] === undefined ) {
  25524. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25525. }
  25526. return textures[ uuid ];
  25527. }
  25528. let geometry, material;
  25529. switch ( data.type ) {
  25530. case 'Scene':
  25531. object = new Scene();
  25532. if ( data.background !== undefined ) {
  25533. if ( Number.isInteger( data.background ) ) {
  25534. object.background = new Color( data.background );
  25535. } else {
  25536. object.background = getTexture( data.background );
  25537. }
  25538. }
  25539. if ( data.environment !== undefined ) {
  25540. object.environment = getTexture( data.environment );
  25541. }
  25542. if ( data.fog !== undefined ) {
  25543. if ( data.fog.type === 'Fog' ) {
  25544. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25545. } else if ( data.fog.type === 'FogExp2' ) {
  25546. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25547. }
  25548. }
  25549. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25550. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25551. break;
  25552. case 'PerspectiveCamera':
  25553. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25554. if ( data.focus !== undefined ) object.focus = data.focus;
  25555. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25556. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25557. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25558. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25559. break;
  25560. case 'OrthographicCamera':
  25561. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25562. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25563. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25564. break;
  25565. case 'AmbientLight':
  25566. object = new AmbientLight( data.color, data.intensity );
  25567. break;
  25568. case 'DirectionalLight':
  25569. object = new DirectionalLight( data.color, data.intensity );
  25570. break;
  25571. case 'PointLight':
  25572. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25573. break;
  25574. case 'RectAreaLight':
  25575. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25576. break;
  25577. case 'SpotLight':
  25578. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25579. break;
  25580. case 'HemisphereLight':
  25581. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25582. break;
  25583. case 'LightProbe':
  25584. object = new LightProbe().fromJSON( data );
  25585. break;
  25586. case 'SkinnedMesh':
  25587. geometry = getGeometry( data.geometry );
  25588. material = getMaterial( data.material );
  25589. object = new SkinnedMesh( geometry, material );
  25590. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25591. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25592. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25593. break;
  25594. case 'Mesh':
  25595. geometry = getGeometry( data.geometry );
  25596. material = getMaterial( data.material );
  25597. object = new Mesh( geometry, material );
  25598. break;
  25599. case 'InstancedMesh':
  25600. geometry = getGeometry( data.geometry );
  25601. material = getMaterial( data.material );
  25602. const count = data.count;
  25603. const instanceMatrix = data.instanceMatrix;
  25604. const instanceColor = data.instanceColor;
  25605. object = new InstancedMesh( geometry, material, count );
  25606. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25607. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25608. break;
  25609. case 'LOD':
  25610. object = new LOD();
  25611. break;
  25612. case 'Line':
  25613. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25614. break;
  25615. case 'LineLoop':
  25616. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25617. break;
  25618. case 'LineSegments':
  25619. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25620. break;
  25621. case 'PointCloud':
  25622. case 'Points':
  25623. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25624. break;
  25625. case 'Sprite':
  25626. object = new Sprite( getMaterial( data.material ) );
  25627. break;
  25628. case 'Group':
  25629. object = new Group();
  25630. break;
  25631. case 'Bone':
  25632. object = new Bone();
  25633. break;
  25634. default:
  25635. object = new Object3D();
  25636. }
  25637. object.uuid = data.uuid;
  25638. if ( data.name !== undefined ) object.name = data.name;
  25639. if ( data.matrix !== undefined ) {
  25640. object.matrix.fromArray( data.matrix );
  25641. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25642. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25643. } else {
  25644. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25645. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25646. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25647. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25648. }
  25649. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25650. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25651. if ( data.shadow ) {
  25652. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25653. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25654. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25655. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25656. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25657. }
  25658. if ( data.visible !== undefined ) object.visible = data.visible;
  25659. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25660. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25661. if ( data.userData !== undefined ) object.userData = data.userData;
  25662. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25663. if ( data.children !== undefined ) {
  25664. const children = data.children;
  25665. for ( let i = 0; i < children.length; i ++ ) {
  25666. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25667. }
  25668. }
  25669. if ( data.animations !== undefined ) {
  25670. const objectAnimations = data.animations;
  25671. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25672. const uuid = objectAnimations[ i ];
  25673. object.animations.push( animations[ uuid ] );
  25674. }
  25675. }
  25676. if ( data.type === 'LOD' ) {
  25677. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25678. const levels = data.levels;
  25679. for ( let l = 0; l < levels.length; l ++ ) {
  25680. const level = levels[ l ];
  25681. const child = object.getObjectByProperty( 'uuid', level.object );
  25682. if ( child !== undefined ) {
  25683. object.addLevel( child, level.distance, level.hysteresis );
  25684. }
  25685. }
  25686. }
  25687. return object;
  25688. }
  25689. bindSkeletons( object, skeletons ) {
  25690. if ( Object.keys( skeletons ).length === 0 ) return;
  25691. object.traverse( function ( child ) {
  25692. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25693. const skeleton = skeletons[ child.skeleton ];
  25694. if ( skeleton === undefined ) {
  25695. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25696. } else {
  25697. child.bind( skeleton, child.bindMatrix );
  25698. }
  25699. }
  25700. } );
  25701. }
  25702. }
  25703. const TEXTURE_MAPPING = {
  25704. UVMapping: UVMapping,
  25705. CubeReflectionMapping: CubeReflectionMapping,
  25706. CubeRefractionMapping: CubeRefractionMapping,
  25707. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25708. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25709. CubeUVReflectionMapping: CubeUVReflectionMapping
  25710. };
  25711. const TEXTURE_WRAPPING = {
  25712. RepeatWrapping: RepeatWrapping,
  25713. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25714. MirroredRepeatWrapping: MirroredRepeatWrapping
  25715. };
  25716. const TEXTURE_FILTER = {
  25717. NearestFilter: NearestFilter,
  25718. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25719. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25720. LinearFilter: LinearFilter,
  25721. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25722. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25723. };
  25724. class ImageBitmapLoader extends Loader {
  25725. constructor( manager ) {
  25726. super( manager );
  25727. this.isImageBitmapLoader = true;
  25728. if ( typeof createImageBitmap === 'undefined' ) {
  25729. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25730. }
  25731. if ( typeof fetch === 'undefined' ) {
  25732. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25733. }
  25734. this.options = { premultiplyAlpha: 'none' };
  25735. }
  25736. setOptions( options ) {
  25737. this.options = options;
  25738. return this;
  25739. }
  25740. load( url, onLoad, onProgress, onError ) {
  25741. if ( url === undefined ) url = '';
  25742. if ( this.path !== undefined ) url = this.path + url;
  25743. url = this.manager.resolveURL( url );
  25744. const scope = this;
  25745. const cached = Cache.get( url );
  25746. if ( cached !== undefined ) {
  25747. scope.manager.itemStart( url );
  25748. setTimeout( function () {
  25749. if ( onLoad ) onLoad( cached );
  25750. scope.manager.itemEnd( url );
  25751. }, 0 );
  25752. return cached;
  25753. }
  25754. const fetchOptions = {};
  25755. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25756. fetchOptions.headers = this.requestHeader;
  25757. fetch( url, fetchOptions ).then( function ( res ) {
  25758. return res.blob();
  25759. } ).then( function ( blob ) {
  25760. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25761. } ).then( function ( imageBitmap ) {
  25762. Cache.add( url, imageBitmap );
  25763. if ( onLoad ) onLoad( imageBitmap );
  25764. scope.manager.itemEnd( url );
  25765. } ).catch( function ( e ) {
  25766. if ( onError ) onError( e );
  25767. scope.manager.itemError( url );
  25768. scope.manager.itemEnd( url );
  25769. } );
  25770. scope.manager.itemStart( url );
  25771. }
  25772. }
  25773. let _context;
  25774. class AudioContext {
  25775. static getContext() {
  25776. if ( _context === undefined ) {
  25777. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25778. }
  25779. return _context;
  25780. }
  25781. static setContext( value ) {
  25782. _context = value;
  25783. }
  25784. }
  25785. class AudioLoader extends Loader {
  25786. constructor( manager ) {
  25787. super( manager );
  25788. }
  25789. load( url, onLoad, onProgress, onError ) {
  25790. const scope = this;
  25791. const loader = new FileLoader( this.manager );
  25792. loader.setResponseType( 'arraybuffer' );
  25793. loader.setPath( this.path );
  25794. loader.setRequestHeader( this.requestHeader );
  25795. loader.setWithCredentials( this.withCredentials );
  25796. loader.load( url, function ( buffer ) {
  25797. try {
  25798. // Create a copy of the buffer. The `decodeAudioData` method
  25799. // detaches the buffer when complete, preventing reuse.
  25800. const bufferCopy = buffer.slice( 0 );
  25801. const context = AudioContext.getContext();
  25802. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25803. onLoad( audioBuffer );
  25804. } );
  25805. } catch ( e ) {
  25806. if ( onError ) {
  25807. onError( e );
  25808. } else {
  25809. console.error( e );
  25810. }
  25811. scope.manager.itemError( url );
  25812. }
  25813. }, onProgress, onError );
  25814. }
  25815. }
  25816. class HemisphereLightProbe extends LightProbe {
  25817. constructor( skyColor, groundColor, intensity = 1 ) {
  25818. super( undefined, intensity );
  25819. this.isHemisphereLightProbe = true;
  25820. const color1 = new Color().set( skyColor );
  25821. const color2 = new Color().set( groundColor );
  25822. const sky = new Vector3( color1.r, color1.g, color1.b );
  25823. const ground = new Vector3( color2.r, color2.g, color2.b );
  25824. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25825. const c0 = Math.sqrt( Math.PI );
  25826. const c1 = c0 * Math.sqrt( 0.75 );
  25827. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25828. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25829. }
  25830. }
  25831. class AmbientLightProbe extends LightProbe {
  25832. constructor( color, intensity = 1 ) {
  25833. super( undefined, intensity );
  25834. this.isAmbientLightProbe = true;
  25835. const color1 = new Color().set( color );
  25836. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25837. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25838. }
  25839. }
  25840. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25841. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25842. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25843. class StereoCamera {
  25844. constructor() {
  25845. this.type = 'StereoCamera';
  25846. this.aspect = 1;
  25847. this.eyeSep = 0.064;
  25848. this.cameraL = new PerspectiveCamera();
  25849. this.cameraL.layers.enable( 1 );
  25850. this.cameraL.matrixAutoUpdate = false;
  25851. this.cameraR = new PerspectiveCamera();
  25852. this.cameraR.layers.enable( 2 );
  25853. this.cameraR.matrixAutoUpdate = false;
  25854. this._cache = {
  25855. focus: null,
  25856. fov: null,
  25857. aspect: null,
  25858. near: null,
  25859. far: null,
  25860. zoom: null,
  25861. eyeSep: null
  25862. };
  25863. }
  25864. update( camera ) {
  25865. const cache = this._cache;
  25866. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25867. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25868. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25869. if ( needsUpdate ) {
  25870. cache.focus = camera.focus;
  25871. cache.fov = camera.fov;
  25872. cache.aspect = camera.aspect * this.aspect;
  25873. cache.near = camera.near;
  25874. cache.far = camera.far;
  25875. cache.zoom = camera.zoom;
  25876. cache.eyeSep = this.eyeSep;
  25877. // Off-axis stereoscopic effect based on
  25878. // http://paulbourke.net/stereographics/stereorender/
  25879. _projectionMatrix.copy( camera.projectionMatrix );
  25880. const eyeSepHalf = cache.eyeSep / 2;
  25881. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25882. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25883. let xmin, xmax;
  25884. // translate xOffset
  25885. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25886. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25887. // for left eye
  25888. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25889. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25890. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25891. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25892. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25893. // for right eye
  25894. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25895. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25896. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25897. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25898. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25899. }
  25900. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25901. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25902. }
  25903. }
  25904. class Clock {
  25905. constructor( autoStart = true ) {
  25906. this.autoStart = autoStart;
  25907. this.startTime = 0;
  25908. this.oldTime = 0;
  25909. this.elapsedTime = 0;
  25910. this.running = false;
  25911. }
  25912. start() {
  25913. this.startTime = now();
  25914. this.oldTime = this.startTime;
  25915. this.elapsedTime = 0;
  25916. this.running = true;
  25917. }
  25918. stop() {
  25919. this.getElapsedTime();
  25920. this.running = false;
  25921. this.autoStart = false;
  25922. }
  25923. getElapsedTime() {
  25924. this.getDelta();
  25925. return this.elapsedTime;
  25926. }
  25927. getDelta() {
  25928. let diff = 0;
  25929. if ( this.autoStart && ! this.running ) {
  25930. this.start();
  25931. return 0;
  25932. }
  25933. if ( this.running ) {
  25934. const newTime = now();
  25935. diff = ( newTime - this.oldTime ) / 1000;
  25936. this.oldTime = newTime;
  25937. this.elapsedTime += diff;
  25938. }
  25939. return diff;
  25940. }
  25941. }
  25942. function now() {
  25943. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25944. }
  25945. const _position$1 = /*@__PURE__*/ new Vector3();
  25946. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25947. const _scale$1 = /*@__PURE__*/ new Vector3();
  25948. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25949. class AudioListener extends Object3D {
  25950. constructor() {
  25951. super();
  25952. this.type = 'AudioListener';
  25953. this.context = AudioContext.getContext();
  25954. this.gain = this.context.createGain();
  25955. this.gain.connect( this.context.destination );
  25956. this.filter = null;
  25957. this.timeDelta = 0;
  25958. // private
  25959. this._clock = new Clock();
  25960. }
  25961. getInput() {
  25962. return this.gain;
  25963. }
  25964. removeFilter() {
  25965. if ( this.filter !== null ) {
  25966. this.gain.disconnect( this.filter );
  25967. this.filter.disconnect( this.context.destination );
  25968. this.gain.connect( this.context.destination );
  25969. this.filter = null;
  25970. }
  25971. return this;
  25972. }
  25973. getFilter() {
  25974. return this.filter;
  25975. }
  25976. setFilter( value ) {
  25977. if ( this.filter !== null ) {
  25978. this.gain.disconnect( this.filter );
  25979. this.filter.disconnect( this.context.destination );
  25980. } else {
  25981. this.gain.disconnect( this.context.destination );
  25982. }
  25983. this.filter = value;
  25984. this.gain.connect( this.filter );
  25985. this.filter.connect( this.context.destination );
  25986. return this;
  25987. }
  25988. getMasterVolume() {
  25989. return this.gain.gain.value;
  25990. }
  25991. setMasterVolume( value ) {
  25992. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25993. return this;
  25994. }
  25995. updateMatrixWorld( force ) {
  25996. super.updateMatrixWorld( force );
  25997. const listener = this.context.listener;
  25998. const up = this.up;
  25999. this.timeDelta = this._clock.getDelta();
  26000. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26001. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26002. if ( listener.positionX ) {
  26003. // code path for Chrome (see #14393)
  26004. const endTime = this.context.currentTime + this.timeDelta;
  26005. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26006. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26007. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26008. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26009. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26010. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26011. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26012. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26013. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26014. } else {
  26015. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26016. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26017. }
  26018. }
  26019. }
  26020. class Audio extends Object3D {
  26021. constructor( listener ) {
  26022. super();
  26023. this.type = 'Audio';
  26024. this.listener = listener;
  26025. this.context = listener.context;
  26026. this.gain = this.context.createGain();
  26027. this.gain.connect( listener.getInput() );
  26028. this.autoplay = false;
  26029. this.buffer = null;
  26030. this.detune = 0;
  26031. this.loop = false;
  26032. this.loopStart = 0;
  26033. this.loopEnd = 0;
  26034. this.offset = 0;
  26035. this.duration = undefined;
  26036. this.playbackRate = 1;
  26037. this.isPlaying = false;
  26038. this.hasPlaybackControl = true;
  26039. this.source = null;
  26040. this.sourceType = 'empty';
  26041. this._startedAt = 0;
  26042. this._progress = 0;
  26043. this._connected = false;
  26044. this.filters = [];
  26045. }
  26046. getOutput() {
  26047. return this.gain;
  26048. }
  26049. setNodeSource( audioNode ) {
  26050. this.hasPlaybackControl = false;
  26051. this.sourceType = 'audioNode';
  26052. this.source = audioNode;
  26053. this.connect();
  26054. return this;
  26055. }
  26056. setMediaElementSource( mediaElement ) {
  26057. this.hasPlaybackControl = false;
  26058. this.sourceType = 'mediaNode';
  26059. this.source = this.context.createMediaElementSource( mediaElement );
  26060. this.connect();
  26061. return this;
  26062. }
  26063. setMediaStreamSource( mediaStream ) {
  26064. this.hasPlaybackControl = false;
  26065. this.sourceType = 'mediaStreamNode';
  26066. this.source = this.context.createMediaStreamSource( mediaStream );
  26067. this.connect();
  26068. return this;
  26069. }
  26070. setBuffer( audioBuffer ) {
  26071. this.buffer = audioBuffer;
  26072. this.sourceType = 'buffer';
  26073. if ( this.autoplay ) this.play();
  26074. return this;
  26075. }
  26076. play( delay = 0 ) {
  26077. if ( this.isPlaying === true ) {
  26078. console.warn( 'THREE.Audio: Audio is already playing.' );
  26079. return;
  26080. }
  26081. if ( this.hasPlaybackControl === false ) {
  26082. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26083. return;
  26084. }
  26085. this._startedAt = this.context.currentTime + delay;
  26086. const source = this.context.createBufferSource();
  26087. source.buffer = this.buffer;
  26088. source.loop = this.loop;
  26089. source.loopStart = this.loopStart;
  26090. source.loopEnd = this.loopEnd;
  26091. source.onended = this.onEnded.bind( this );
  26092. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26093. this.isPlaying = true;
  26094. this.source = source;
  26095. this.setDetune( this.detune );
  26096. this.setPlaybackRate( this.playbackRate );
  26097. return this.connect();
  26098. }
  26099. pause() {
  26100. if ( this.hasPlaybackControl === false ) {
  26101. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26102. return;
  26103. }
  26104. if ( this.isPlaying === true ) {
  26105. // update current progress
  26106. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26107. if ( this.loop === true ) {
  26108. // ensure _progress does not exceed duration with looped audios
  26109. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26110. }
  26111. this.source.stop();
  26112. this.source.onended = null;
  26113. this.isPlaying = false;
  26114. }
  26115. return this;
  26116. }
  26117. stop() {
  26118. if ( this.hasPlaybackControl === false ) {
  26119. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26120. return;
  26121. }
  26122. this._progress = 0;
  26123. this.source.stop();
  26124. this.source.onended = null;
  26125. this.isPlaying = false;
  26126. return this;
  26127. }
  26128. connect() {
  26129. if ( this.filters.length > 0 ) {
  26130. this.source.connect( this.filters[ 0 ] );
  26131. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26132. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26133. }
  26134. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26135. } else {
  26136. this.source.connect( this.getOutput() );
  26137. }
  26138. this._connected = true;
  26139. return this;
  26140. }
  26141. disconnect() {
  26142. if ( this.filters.length > 0 ) {
  26143. this.source.disconnect( this.filters[ 0 ] );
  26144. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26145. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26146. }
  26147. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26148. } else {
  26149. this.source.disconnect( this.getOutput() );
  26150. }
  26151. this._connected = false;
  26152. return this;
  26153. }
  26154. getFilters() {
  26155. return this.filters;
  26156. }
  26157. setFilters( value ) {
  26158. if ( ! value ) value = [];
  26159. if ( this._connected === true ) {
  26160. this.disconnect();
  26161. this.filters = value.slice();
  26162. this.connect();
  26163. } else {
  26164. this.filters = value.slice();
  26165. }
  26166. return this;
  26167. }
  26168. setDetune( value ) {
  26169. this.detune = value;
  26170. if ( this.source.detune === undefined ) return; // only set detune when available
  26171. if ( this.isPlaying === true ) {
  26172. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26173. }
  26174. return this;
  26175. }
  26176. getDetune() {
  26177. return this.detune;
  26178. }
  26179. getFilter() {
  26180. return this.getFilters()[ 0 ];
  26181. }
  26182. setFilter( filter ) {
  26183. return this.setFilters( filter ? [ filter ] : [] );
  26184. }
  26185. setPlaybackRate( value ) {
  26186. if ( this.hasPlaybackControl === false ) {
  26187. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26188. return;
  26189. }
  26190. this.playbackRate = value;
  26191. if ( this.isPlaying === true ) {
  26192. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26193. }
  26194. return this;
  26195. }
  26196. getPlaybackRate() {
  26197. return this.playbackRate;
  26198. }
  26199. onEnded() {
  26200. this.isPlaying = false;
  26201. }
  26202. getLoop() {
  26203. if ( this.hasPlaybackControl === false ) {
  26204. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26205. return false;
  26206. }
  26207. return this.loop;
  26208. }
  26209. setLoop( value ) {
  26210. if ( this.hasPlaybackControl === false ) {
  26211. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26212. return;
  26213. }
  26214. this.loop = value;
  26215. if ( this.isPlaying === true ) {
  26216. this.source.loop = this.loop;
  26217. }
  26218. return this;
  26219. }
  26220. setLoopStart( value ) {
  26221. this.loopStart = value;
  26222. return this;
  26223. }
  26224. setLoopEnd( value ) {
  26225. this.loopEnd = value;
  26226. return this;
  26227. }
  26228. getVolume() {
  26229. return this.gain.gain.value;
  26230. }
  26231. setVolume( value ) {
  26232. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26233. return this;
  26234. }
  26235. }
  26236. const _position = /*@__PURE__*/ new Vector3();
  26237. const _quaternion = /*@__PURE__*/ new Quaternion();
  26238. const _scale = /*@__PURE__*/ new Vector3();
  26239. const _orientation = /*@__PURE__*/ new Vector3();
  26240. class PositionalAudio extends Audio {
  26241. constructor( listener ) {
  26242. super( listener );
  26243. this.panner = this.context.createPanner();
  26244. this.panner.panningModel = 'HRTF';
  26245. this.panner.connect( this.gain );
  26246. }
  26247. disconnect() {
  26248. super.disconnect();
  26249. this.panner.disconnect( this.gain );
  26250. }
  26251. getOutput() {
  26252. return this.panner;
  26253. }
  26254. getRefDistance() {
  26255. return this.panner.refDistance;
  26256. }
  26257. setRefDistance( value ) {
  26258. this.panner.refDistance = value;
  26259. return this;
  26260. }
  26261. getRolloffFactor() {
  26262. return this.panner.rolloffFactor;
  26263. }
  26264. setRolloffFactor( value ) {
  26265. this.panner.rolloffFactor = value;
  26266. return this;
  26267. }
  26268. getDistanceModel() {
  26269. return this.panner.distanceModel;
  26270. }
  26271. setDistanceModel( value ) {
  26272. this.panner.distanceModel = value;
  26273. return this;
  26274. }
  26275. getMaxDistance() {
  26276. return this.panner.maxDistance;
  26277. }
  26278. setMaxDistance( value ) {
  26279. this.panner.maxDistance = value;
  26280. return this;
  26281. }
  26282. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26283. this.panner.coneInnerAngle = coneInnerAngle;
  26284. this.panner.coneOuterAngle = coneOuterAngle;
  26285. this.panner.coneOuterGain = coneOuterGain;
  26286. return this;
  26287. }
  26288. updateMatrixWorld( force ) {
  26289. super.updateMatrixWorld( force );
  26290. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26291. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26292. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26293. const panner = this.panner;
  26294. if ( panner.positionX ) {
  26295. // code path for Chrome and Firefox (see #14393)
  26296. const endTime = this.context.currentTime + this.listener.timeDelta;
  26297. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26298. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26299. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26300. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26301. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26302. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26303. } else {
  26304. panner.setPosition( _position.x, _position.y, _position.z );
  26305. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26306. }
  26307. }
  26308. }
  26309. class AudioAnalyser {
  26310. constructor( audio, fftSize = 2048 ) {
  26311. this.analyser = audio.context.createAnalyser();
  26312. this.analyser.fftSize = fftSize;
  26313. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26314. audio.getOutput().connect( this.analyser );
  26315. }
  26316. getFrequencyData() {
  26317. this.analyser.getByteFrequencyData( this.data );
  26318. return this.data;
  26319. }
  26320. getAverageFrequency() {
  26321. let value = 0;
  26322. const data = this.getFrequencyData();
  26323. for ( let i = 0; i < data.length; i ++ ) {
  26324. value += data[ i ];
  26325. }
  26326. return value / data.length;
  26327. }
  26328. }
  26329. class PropertyMixer {
  26330. constructor( binding, typeName, valueSize ) {
  26331. this.binding = binding;
  26332. this.valueSize = valueSize;
  26333. let mixFunction,
  26334. mixFunctionAdditive,
  26335. setIdentity;
  26336. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26337. //
  26338. // interpolators can use .buffer as their .result
  26339. // the data then goes to 'incoming'
  26340. //
  26341. // 'accu0' and 'accu1' are used frame-interleaved for
  26342. // the cumulative result and are compared to detect
  26343. // changes
  26344. //
  26345. // 'orig' stores the original state of the property
  26346. //
  26347. // 'add' is used for additive cumulative results
  26348. //
  26349. // 'work' is optional and is only present for quaternion types. It is used
  26350. // to store intermediate quaternion multiplication results
  26351. switch ( typeName ) {
  26352. case 'quaternion':
  26353. mixFunction = this._slerp;
  26354. mixFunctionAdditive = this._slerpAdditive;
  26355. setIdentity = this._setAdditiveIdentityQuaternion;
  26356. this.buffer = new Float64Array( valueSize * 6 );
  26357. this._workIndex = 5;
  26358. break;
  26359. case 'string':
  26360. case 'bool':
  26361. mixFunction = this._select;
  26362. // Use the regular mix function and for additive on these types,
  26363. // additive is not relevant for non-numeric types
  26364. mixFunctionAdditive = this._select;
  26365. setIdentity = this._setAdditiveIdentityOther;
  26366. this.buffer = new Array( valueSize * 5 );
  26367. break;
  26368. default:
  26369. mixFunction = this._lerp;
  26370. mixFunctionAdditive = this._lerpAdditive;
  26371. setIdentity = this._setAdditiveIdentityNumeric;
  26372. this.buffer = new Float64Array( valueSize * 5 );
  26373. }
  26374. this._mixBufferRegion = mixFunction;
  26375. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26376. this._setIdentity = setIdentity;
  26377. this._origIndex = 3;
  26378. this._addIndex = 4;
  26379. this.cumulativeWeight = 0;
  26380. this.cumulativeWeightAdditive = 0;
  26381. this.useCount = 0;
  26382. this.referenceCount = 0;
  26383. }
  26384. // accumulate data in the 'incoming' region into 'accu<i>'
  26385. accumulate( accuIndex, weight ) {
  26386. // note: happily accumulating nothing when weight = 0, the caller knows
  26387. // the weight and shouldn't have made the call in the first place
  26388. const buffer = this.buffer,
  26389. stride = this.valueSize,
  26390. offset = accuIndex * stride + stride;
  26391. let currentWeight = this.cumulativeWeight;
  26392. if ( currentWeight === 0 ) {
  26393. // accuN := incoming * weight
  26394. for ( let i = 0; i !== stride; ++ i ) {
  26395. buffer[ offset + i ] = buffer[ i ];
  26396. }
  26397. currentWeight = weight;
  26398. } else {
  26399. // accuN := accuN + incoming * weight
  26400. currentWeight += weight;
  26401. const mix = weight / currentWeight;
  26402. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26403. }
  26404. this.cumulativeWeight = currentWeight;
  26405. }
  26406. // accumulate data in the 'incoming' region into 'add'
  26407. accumulateAdditive( weight ) {
  26408. const buffer = this.buffer,
  26409. stride = this.valueSize,
  26410. offset = stride * this._addIndex;
  26411. if ( this.cumulativeWeightAdditive === 0 ) {
  26412. // add = identity
  26413. this._setIdentity();
  26414. }
  26415. // add := add + incoming * weight
  26416. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26417. this.cumulativeWeightAdditive += weight;
  26418. }
  26419. // apply the state of 'accu<i>' to the binding when accus differ
  26420. apply( accuIndex ) {
  26421. const stride = this.valueSize,
  26422. buffer = this.buffer,
  26423. offset = accuIndex * stride + stride,
  26424. weight = this.cumulativeWeight,
  26425. weightAdditive = this.cumulativeWeightAdditive,
  26426. binding = this.binding;
  26427. this.cumulativeWeight = 0;
  26428. this.cumulativeWeightAdditive = 0;
  26429. if ( weight < 1 ) {
  26430. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26431. const originalValueOffset = stride * this._origIndex;
  26432. this._mixBufferRegion(
  26433. buffer, offset, originalValueOffset, 1 - weight, stride );
  26434. }
  26435. if ( weightAdditive > 0 ) {
  26436. // accuN := accuN + additive accuN
  26437. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26438. }
  26439. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26440. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26441. // value has changed -> update scene graph
  26442. binding.setValue( buffer, offset );
  26443. break;
  26444. }
  26445. }
  26446. }
  26447. // remember the state of the bound property and copy it to both accus
  26448. saveOriginalState() {
  26449. const binding = this.binding;
  26450. const buffer = this.buffer,
  26451. stride = this.valueSize,
  26452. originalValueOffset = stride * this._origIndex;
  26453. binding.getValue( buffer, originalValueOffset );
  26454. // accu[0..1] := orig -- initially detect changes against the original
  26455. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26456. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26457. }
  26458. // Add to identity for additive
  26459. this._setIdentity();
  26460. this.cumulativeWeight = 0;
  26461. this.cumulativeWeightAdditive = 0;
  26462. }
  26463. // apply the state previously taken via 'saveOriginalState' to the binding
  26464. restoreOriginalState() {
  26465. const originalValueOffset = this.valueSize * 3;
  26466. this.binding.setValue( this.buffer, originalValueOffset );
  26467. }
  26468. _setAdditiveIdentityNumeric() {
  26469. const startIndex = this._addIndex * this.valueSize;
  26470. const endIndex = startIndex + this.valueSize;
  26471. for ( let i = startIndex; i < endIndex; i ++ ) {
  26472. this.buffer[ i ] = 0;
  26473. }
  26474. }
  26475. _setAdditiveIdentityQuaternion() {
  26476. this._setAdditiveIdentityNumeric();
  26477. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26478. }
  26479. _setAdditiveIdentityOther() {
  26480. const startIndex = this._origIndex * this.valueSize;
  26481. const targetIndex = this._addIndex * this.valueSize;
  26482. for ( let i = 0; i < this.valueSize; i ++ ) {
  26483. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26484. }
  26485. }
  26486. // mix functions
  26487. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26488. if ( t >= 0.5 ) {
  26489. for ( let i = 0; i !== stride; ++ i ) {
  26490. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26491. }
  26492. }
  26493. }
  26494. _slerp( buffer, dstOffset, srcOffset, t ) {
  26495. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26496. }
  26497. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26498. const workOffset = this._workIndex * stride;
  26499. // Store result in intermediate buffer offset
  26500. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26501. // Slerp to the intermediate result
  26502. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26503. }
  26504. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26505. const s = 1 - t;
  26506. for ( let i = 0; i !== stride; ++ i ) {
  26507. const j = dstOffset + i;
  26508. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26509. }
  26510. }
  26511. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26512. for ( let i = 0; i !== stride; ++ i ) {
  26513. const j = dstOffset + i;
  26514. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26515. }
  26516. }
  26517. }
  26518. // Characters [].:/ are reserved for track binding syntax.
  26519. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26520. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26521. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26522. // only latin characters, and the unicode \p{L} is not yet supported. So
  26523. // instead, we exclude reserved characters and match everything else.
  26524. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26525. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26526. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26527. // be matched to parse the rest of the track name.
  26528. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26529. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26530. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26531. // Object on target node, and accessor. May not contain reserved
  26532. // characters. Accessor may contain any character except closing bracket.
  26533. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26534. // Property and accessor. May not contain reserved characters. Accessor may
  26535. // contain any non-bracket characters.
  26536. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26537. const _trackRe = new RegExp( ''
  26538. + '^'
  26539. + _directoryRe
  26540. + _nodeRe
  26541. + _objectRe
  26542. + _propertyRe
  26543. + '$'
  26544. );
  26545. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26546. class Composite {
  26547. constructor( targetGroup, path, optionalParsedPath ) {
  26548. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26549. this._targetGroup = targetGroup;
  26550. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26551. }
  26552. getValue( array, offset ) {
  26553. this.bind(); // bind all binding
  26554. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26555. binding = this._bindings[ firstValidIndex ];
  26556. // and only call .getValue on the first
  26557. if ( binding !== undefined ) binding.getValue( array, offset );
  26558. }
  26559. setValue( array, offset ) {
  26560. const bindings = this._bindings;
  26561. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26562. bindings[ i ].setValue( array, offset );
  26563. }
  26564. }
  26565. bind() {
  26566. const bindings = this._bindings;
  26567. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26568. bindings[ i ].bind();
  26569. }
  26570. }
  26571. unbind() {
  26572. const bindings = this._bindings;
  26573. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26574. bindings[ i ].unbind();
  26575. }
  26576. }
  26577. }
  26578. // Note: This class uses a State pattern on a per-method basis:
  26579. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26580. // prototype version of these methods with one that represents
  26581. // the bound state. When the property is not found, the methods
  26582. // become no-ops.
  26583. class PropertyBinding {
  26584. constructor( rootNode, path, parsedPath ) {
  26585. this.path = path;
  26586. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26587. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26588. this.rootNode = rootNode;
  26589. // initial state of these methods that calls 'bind'
  26590. this.getValue = this._getValue_unbound;
  26591. this.setValue = this._setValue_unbound;
  26592. }
  26593. static create( root, path, parsedPath ) {
  26594. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26595. return new PropertyBinding( root, path, parsedPath );
  26596. } else {
  26597. return new PropertyBinding.Composite( root, path, parsedPath );
  26598. }
  26599. }
  26600. /**
  26601. * Replaces spaces with underscores and removes unsupported characters from
  26602. * node names, to ensure compatibility with parseTrackName().
  26603. *
  26604. * @param {string} name Node name to be sanitized.
  26605. * @return {string}
  26606. */
  26607. static sanitizeNodeName( name ) {
  26608. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26609. }
  26610. static parseTrackName( trackName ) {
  26611. const matches = _trackRe.exec( trackName );
  26612. if ( matches === null ) {
  26613. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26614. }
  26615. const results = {
  26616. // directoryName: matches[ 1 ], // (tschw) currently unused
  26617. nodeName: matches[ 2 ],
  26618. objectName: matches[ 3 ],
  26619. objectIndex: matches[ 4 ],
  26620. propertyName: matches[ 5 ], // required
  26621. propertyIndex: matches[ 6 ]
  26622. };
  26623. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26624. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26625. const objectName = results.nodeName.substring( lastDot + 1 );
  26626. // Object names must be checked against an allowlist. Otherwise, there
  26627. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26628. // 'bar' could be the objectName, or part of a nodeName (which can
  26629. // include '.' characters).
  26630. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26631. results.nodeName = results.nodeName.substring( 0, lastDot );
  26632. results.objectName = objectName;
  26633. }
  26634. }
  26635. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26636. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26637. }
  26638. return results;
  26639. }
  26640. static findNode( root, nodeName ) {
  26641. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26642. return root;
  26643. }
  26644. // search into skeleton bones.
  26645. if ( root.skeleton ) {
  26646. const bone = root.skeleton.getBoneByName( nodeName );
  26647. if ( bone !== undefined ) {
  26648. return bone;
  26649. }
  26650. }
  26651. // search into node subtree.
  26652. if ( root.children ) {
  26653. const searchNodeSubtree = function ( children ) {
  26654. for ( let i = 0; i < children.length; i ++ ) {
  26655. const childNode = children[ i ];
  26656. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26657. return childNode;
  26658. }
  26659. const result = searchNodeSubtree( childNode.children );
  26660. if ( result ) return result;
  26661. }
  26662. return null;
  26663. };
  26664. const subTreeNode = searchNodeSubtree( root.children );
  26665. if ( subTreeNode ) {
  26666. return subTreeNode;
  26667. }
  26668. }
  26669. return null;
  26670. }
  26671. // these are used to "bind" a nonexistent property
  26672. _getValue_unavailable() {}
  26673. _setValue_unavailable() {}
  26674. // Getters
  26675. _getValue_direct( buffer, offset ) {
  26676. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26677. }
  26678. _getValue_array( buffer, offset ) {
  26679. const source = this.resolvedProperty;
  26680. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26681. buffer[ offset ++ ] = source[ i ];
  26682. }
  26683. }
  26684. _getValue_arrayElement( buffer, offset ) {
  26685. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26686. }
  26687. _getValue_toArray( buffer, offset ) {
  26688. this.resolvedProperty.toArray( buffer, offset );
  26689. }
  26690. // Direct
  26691. _setValue_direct( buffer, offset ) {
  26692. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26693. }
  26694. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26695. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26696. this.targetObject.needsUpdate = true;
  26697. }
  26698. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26699. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26700. this.targetObject.matrixWorldNeedsUpdate = true;
  26701. }
  26702. // EntireArray
  26703. _setValue_array( buffer, offset ) {
  26704. const dest = this.resolvedProperty;
  26705. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26706. dest[ i ] = buffer[ offset ++ ];
  26707. }
  26708. }
  26709. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26710. const dest = this.resolvedProperty;
  26711. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26712. dest[ i ] = buffer[ offset ++ ];
  26713. }
  26714. this.targetObject.needsUpdate = true;
  26715. }
  26716. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26717. const dest = this.resolvedProperty;
  26718. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26719. dest[ i ] = buffer[ offset ++ ];
  26720. }
  26721. this.targetObject.matrixWorldNeedsUpdate = true;
  26722. }
  26723. // ArrayElement
  26724. _setValue_arrayElement( buffer, offset ) {
  26725. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26726. }
  26727. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26728. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26729. this.targetObject.needsUpdate = true;
  26730. }
  26731. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26732. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26733. this.targetObject.matrixWorldNeedsUpdate = true;
  26734. }
  26735. // HasToFromArray
  26736. _setValue_fromArray( buffer, offset ) {
  26737. this.resolvedProperty.fromArray( buffer, offset );
  26738. }
  26739. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26740. this.resolvedProperty.fromArray( buffer, offset );
  26741. this.targetObject.needsUpdate = true;
  26742. }
  26743. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26744. this.resolvedProperty.fromArray( buffer, offset );
  26745. this.targetObject.matrixWorldNeedsUpdate = true;
  26746. }
  26747. _getValue_unbound( targetArray, offset ) {
  26748. this.bind();
  26749. this.getValue( targetArray, offset );
  26750. }
  26751. _setValue_unbound( sourceArray, offset ) {
  26752. this.bind();
  26753. this.setValue( sourceArray, offset );
  26754. }
  26755. // create getter / setter pair for a property in the scene graph
  26756. bind() {
  26757. let targetObject = this.node;
  26758. const parsedPath = this.parsedPath;
  26759. const objectName = parsedPath.objectName;
  26760. const propertyName = parsedPath.propertyName;
  26761. let propertyIndex = parsedPath.propertyIndex;
  26762. if ( ! targetObject ) {
  26763. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26764. this.node = targetObject;
  26765. }
  26766. // set fail state so we can just 'return' on error
  26767. this.getValue = this._getValue_unavailable;
  26768. this.setValue = this._setValue_unavailable;
  26769. // ensure there is a value node
  26770. if ( ! targetObject ) {
  26771. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26772. return;
  26773. }
  26774. if ( objectName ) {
  26775. let objectIndex = parsedPath.objectIndex;
  26776. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26777. switch ( objectName ) {
  26778. case 'materials':
  26779. if ( ! targetObject.material ) {
  26780. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26781. return;
  26782. }
  26783. if ( ! targetObject.material.materials ) {
  26784. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26785. return;
  26786. }
  26787. targetObject = targetObject.material.materials;
  26788. break;
  26789. case 'bones':
  26790. if ( ! targetObject.skeleton ) {
  26791. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26792. return;
  26793. }
  26794. // potential future optimization: skip this if propertyIndex is already an integer
  26795. // and convert the integer string to a true integer.
  26796. targetObject = targetObject.skeleton.bones;
  26797. // support resolving morphTarget names into indices.
  26798. for ( let i = 0; i < targetObject.length; i ++ ) {
  26799. if ( targetObject[ i ].name === objectIndex ) {
  26800. objectIndex = i;
  26801. break;
  26802. }
  26803. }
  26804. break;
  26805. case 'map':
  26806. if ( 'map' in targetObject ) {
  26807. targetObject = targetObject.map;
  26808. break;
  26809. }
  26810. if ( ! targetObject.material ) {
  26811. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26812. return;
  26813. }
  26814. if ( ! targetObject.material.map ) {
  26815. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26816. return;
  26817. }
  26818. targetObject = targetObject.material.map;
  26819. break;
  26820. default:
  26821. if ( targetObject[ objectName ] === undefined ) {
  26822. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26823. return;
  26824. }
  26825. targetObject = targetObject[ objectName ];
  26826. }
  26827. if ( objectIndex !== undefined ) {
  26828. if ( targetObject[ objectIndex ] === undefined ) {
  26829. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26830. return;
  26831. }
  26832. targetObject = targetObject[ objectIndex ];
  26833. }
  26834. }
  26835. // resolve property
  26836. const nodeProperty = targetObject[ propertyName ];
  26837. if ( nodeProperty === undefined ) {
  26838. const nodeName = parsedPath.nodeName;
  26839. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26840. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26841. return;
  26842. }
  26843. // determine versioning scheme
  26844. let versioning = this.Versioning.None;
  26845. this.targetObject = targetObject;
  26846. if ( targetObject.needsUpdate !== undefined ) { // material
  26847. versioning = this.Versioning.NeedsUpdate;
  26848. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26849. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26850. }
  26851. // determine how the property gets bound
  26852. let bindingType = this.BindingType.Direct;
  26853. if ( propertyIndex !== undefined ) {
  26854. // access a sub element of the property array (only primitives are supported right now)
  26855. if ( propertyName === 'morphTargetInfluences' ) {
  26856. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26857. // support resolving morphTarget names into indices.
  26858. if ( ! targetObject.geometry ) {
  26859. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26860. return;
  26861. }
  26862. if ( ! targetObject.geometry.morphAttributes ) {
  26863. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26864. return;
  26865. }
  26866. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26867. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26868. }
  26869. }
  26870. bindingType = this.BindingType.ArrayElement;
  26871. this.resolvedProperty = nodeProperty;
  26872. this.propertyIndex = propertyIndex;
  26873. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26874. // must use copy for Object3D.Euler/Quaternion
  26875. bindingType = this.BindingType.HasFromToArray;
  26876. this.resolvedProperty = nodeProperty;
  26877. } else if ( Array.isArray( nodeProperty ) ) {
  26878. bindingType = this.BindingType.EntireArray;
  26879. this.resolvedProperty = nodeProperty;
  26880. } else {
  26881. this.propertyName = propertyName;
  26882. }
  26883. // select getter / setter
  26884. this.getValue = this.GetterByBindingType[ bindingType ];
  26885. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26886. }
  26887. unbind() {
  26888. this.node = null;
  26889. // back to the prototype version of getValue / setValue
  26890. // note: avoiding to mutate the shape of 'this' via 'delete'
  26891. this.getValue = this._getValue_unbound;
  26892. this.setValue = this._setValue_unbound;
  26893. }
  26894. }
  26895. PropertyBinding.Composite = Composite;
  26896. PropertyBinding.prototype.BindingType = {
  26897. Direct: 0,
  26898. EntireArray: 1,
  26899. ArrayElement: 2,
  26900. HasFromToArray: 3
  26901. };
  26902. PropertyBinding.prototype.Versioning = {
  26903. None: 0,
  26904. NeedsUpdate: 1,
  26905. MatrixWorldNeedsUpdate: 2
  26906. };
  26907. PropertyBinding.prototype.GetterByBindingType = [
  26908. PropertyBinding.prototype._getValue_direct,
  26909. PropertyBinding.prototype._getValue_array,
  26910. PropertyBinding.prototype._getValue_arrayElement,
  26911. PropertyBinding.prototype._getValue_toArray,
  26912. ];
  26913. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26914. [
  26915. // Direct
  26916. PropertyBinding.prototype._setValue_direct,
  26917. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26918. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26919. ], [
  26920. // EntireArray
  26921. PropertyBinding.prototype._setValue_array,
  26922. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26923. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26924. ], [
  26925. // ArrayElement
  26926. PropertyBinding.prototype._setValue_arrayElement,
  26927. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26928. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26929. ], [
  26930. // HasToFromArray
  26931. PropertyBinding.prototype._setValue_fromArray,
  26932. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26933. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26934. ]
  26935. ];
  26936. /**
  26937. *
  26938. * A group of objects that receives a shared animation state.
  26939. *
  26940. * Usage:
  26941. *
  26942. * - Add objects you would otherwise pass as 'root' to the
  26943. * constructor or the .clipAction method of AnimationMixer.
  26944. *
  26945. * - Instead pass this object as 'root'.
  26946. *
  26947. * - You can also add and remove objects later when the mixer
  26948. * is running.
  26949. *
  26950. * Note:
  26951. *
  26952. * Objects of this class appear as one object to the mixer,
  26953. * so cache control of the individual objects must be done
  26954. * on the group.
  26955. *
  26956. * Limitation:
  26957. *
  26958. * - The animated properties must be compatible among the
  26959. * all objects in the group.
  26960. *
  26961. * - A single property can either be controlled through a
  26962. * target group or directly, but not both.
  26963. */
  26964. class AnimationObjectGroup {
  26965. constructor() {
  26966. this.isAnimationObjectGroup = true;
  26967. this.uuid = generateUUID();
  26968. // cached objects followed by the active ones
  26969. this._objects = Array.prototype.slice.call( arguments );
  26970. this.nCachedObjects_ = 0; // threshold
  26971. // note: read by PropertyBinding.Composite
  26972. const indices = {};
  26973. this._indicesByUUID = indices; // for bookkeeping
  26974. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26975. indices[ arguments[ i ].uuid ] = i;
  26976. }
  26977. this._paths = []; // inside: string
  26978. this._parsedPaths = []; // inside: { we don't care, here }
  26979. this._bindings = []; // inside: Array< PropertyBinding >
  26980. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26981. const scope = this;
  26982. this.stats = {
  26983. objects: {
  26984. get total() {
  26985. return scope._objects.length;
  26986. },
  26987. get inUse() {
  26988. return this.total - scope.nCachedObjects_;
  26989. }
  26990. },
  26991. get bindingsPerObject() {
  26992. return scope._bindings.length;
  26993. }
  26994. };
  26995. }
  26996. add() {
  26997. const objects = this._objects,
  26998. indicesByUUID = this._indicesByUUID,
  26999. paths = this._paths,
  27000. parsedPaths = this._parsedPaths,
  27001. bindings = this._bindings,
  27002. nBindings = bindings.length;
  27003. let knownObject = undefined,
  27004. nObjects = objects.length,
  27005. nCachedObjects = this.nCachedObjects_;
  27006. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27007. const object = arguments[ i ],
  27008. uuid = object.uuid;
  27009. let index = indicesByUUID[ uuid ];
  27010. if ( index === undefined ) {
  27011. // unknown object -> add it to the ACTIVE region
  27012. index = nObjects ++;
  27013. indicesByUUID[ uuid ] = index;
  27014. objects.push( object );
  27015. // accounting is done, now do the same for all bindings
  27016. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27017. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27018. }
  27019. } else if ( index < nCachedObjects ) {
  27020. knownObject = objects[ index ];
  27021. // move existing object to the ACTIVE region
  27022. const firstActiveIndex = -- nCachedObjects,
  27023. lastCachedObject = objects[ firstActiveIndex ];
  27024. indicesByUUID[ lastCachedObject.uuid ] = index;
  27025. objects[ index ] = lastCachedObject;
  27026. indicesByUUID[ uuid ] = firstActiveIndex;
  27027. objects[ firstActiveIndex ] = object;
  27028. // accounting is done, now do the same for all bindings
  27029. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27030. const bindingsForPath = bindings[ j ],
  27031. lastCached = bindingsForPath[ firstActiveIndex ];
  27032. let binding = bindingsForPath[ index ];
  27033. bindingsForPath[ index ] = lastCached;
  27034. if ( binding === undefined ) {
  27035. // since we do not bother to create new bindings
  27036. // for objects that are cached, the binding may
  27037. // or may not exist
  27038. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27039. }
  27040. bindingsForPath[ firstActiveIndex ] = binding;
  27041. }
  27042. } else if ( objects[ index ] !== knownObject ) {
  27043. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27044. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27045. } // else the object is already where we want it to be
  27046. } // for arguments
  27047. this.nCachedObjects_ = nCachedObjects;
  27048. }
  27049. remove() {
  27050. const objects = this._objects,
  27051. indicesByUUID = this._indicesByUUID,
  27052. bindings = this._bindings,
  27053. nBindings = bindings.length;
  27054. let nCachedObjects = this.nCachedObjects_;
  27055. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27056. const object = arguments[ i ],
  27057. uuid = object.uuid,
  27058. index = indicesByUUID[ uuid ];
  27059. if ( index !== undefined && index >= nCachedObjects ) {
  27060. // move existing object into the CACHED region
  27061. const lastCachedIndex = nCachedObjects ++,
  27062. firstActiveObject = objects[ lastCachedIndex ];
  27063. indicesByUUID[ firstActiveObject.uuid ] = index;
  27064. objects[ index ] = firstActiveObject;
  27065. indicesByUUID[ uuid ] = lastCachedIndex;
  27066. objects[ lastCachedIndex ] = object;
  27067. // accounting is done, now do the same for all bindings
  27068. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27069. const bindingsForPath = bindings[ j ],
  27070. firstActive = bindingsForPath[ lastCachedIndex ],
  27071. binding = bindingsForPath[ index ];
  27072. bindingsForPath[ index ] = firstActive;
  27073. bindingsForPath[ lastCachedIndex ] = binding;
  27074. }
  27075. }
  27076. } // for arguments
  27077. this.nCachedObjects_ = nCachedObjects;
  27078. }
  27079. // remove & forget
  27080. uncache() {
  27081. const objects = this._objects,
  27082. indicesByUUID = this._indicesByUUID,
  27083. bindings = this._bindings,
  27084. nBindings = bindings.length;
  27085. let nCachedObjects = this.nCachedObjects_,
  27086. nObjects = objects.length;
  27087. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27088. const object = arguments[ i ],
  27089. uuid = object.uuid,
  27090. index = indicesByUUID[ uuid ];
  27091. if ( index !== undefined ) {
  27092. delete indicesByUUID[ uuid ];
  27093. if ( index < nCachedObjects ) {
  27094. // object is cached, shrink the CACHED region
  27095. const firstActiveIndex = -- nCachedObjects,
  27096. lastCachedObject = objects[ firstActiveIndex ],
  27097. lastIndex = -- nObjects,
  27098. lastObject = objects[ lastIndex ];
  27099. // last cached object takes this object's place
  27100. indicesByUUID[ lastCachedObject.uuid ] = index;
  27101. objects[ index ] = lastCachedObject;
  27102. // last object goes to the activated slot and pop
  27103. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27104. objects[ firstActiveIndex ] = lastObject;
  27105. objects.pop();
  27106. // accounting is done, now do the same for all bindings
  27107. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27108. const bindingsForPath = bindings[ j ],
  27109. lastCached = bindingsForPath[ firstActiveIndex ],
  27110. last = bindingsForPath[ lastIndex ];
  27111. bindingsForPath[ index ] = lastCached;
  27112. bindingsForPath[ firstActiveIndex ] = last;
  27113. bindingsForPath.pop();
  27114. }
  27115. } else {
  27116. // object is active, just swap with the last and pop
  27117. const lastIndex = -- nObjects,
  27118. lastObject = objects[ lastIndex ];
  27119. if ( lastIndex > 0 ) {
  27120. indicesByUUID[ lastObject.uuid ] = index;
  27121. }
  27122. objects[ index ] = lastObject;
  27123. objects.pop();
  27124. // accounting is done, now do the same for all bindings
  27125. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27126. const bindingsForPath = bindings[ j ];
  27127. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27128. bindingsForPath.pop();
  27129. }
  27130. } // cached or active
  27131. } // if object is known
  27132. } // for arguments
  27133. this.nCachedObjects_ = nCachedObjects;
  27134. }
  27135. // Internal interface used by befriended PropertyBinding.Composite:
  27136. subscribe_( path, parsedPath ) {
  27137. // returns an array of bindings for the given path that is changed
  27138. // according to the contained objects in the group
  27139. const indicesByPath = this._bindingsIndicesByPath;
  27140. let index = indicesByPath[ path ];
  27141. const bindings = this._bindings;
  27142. if ( index !== undefined ) return bindings[ index ];
  27143. const paths = this._paths,
  27144. parsedPaths = this._parsedPaths,
  27145. objects = this._objects,
  27146. nObjects = objects.length,
  27147. nCachedObjects = this.nCachedObjects_,
  27148. bindingsForPath = new Array( nObjects );
  27149. index = bindings.length;
  27150. indicesByPath[ path ] = index;
  27151. paths.push( path );
  27152. parsedPaths.push( parsedPath );
  27153. bindings.push( bindingsForPath );
  27154. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27155. const object = objects[ i ];
  27156. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27157. }
  27158. return bindingsForPath;
  27159. }
  27160. unsubscribe_( path ) {
  27161. // tells the group to forget about a property path and no longer
  27162. // update the array previously obtained with 'subscribe_'
  27163. const indicesByPath = this._bindingsIndicesByPath,
  27164. index = indicesByPath[ path ];
  27165. if ( index !== undefined ) {
  27166. const paths = this._paths,
  27167. parsedPaths = this._parsedPaths,
  27168. bindings = this._bindings,
  27169. lastBindingsIndex = bindings.length - 1,
  27170. lastBindings = bindings[ lastBindingsIndex ],
  27171. lastBindingsPath = path[ lastBindingsIndex ];
  27172. indicesByPath[ lastBindingsPath ] = index;
  27173. bindings[ index ] = lastBindings;
  27174. bindings.pop();
  27175. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27176. parsedPaths.pop();
  27177. paths[ index ] = paths[ lastBindingsIndex ];
  27178. paths.pop();
  27179. }
  27180. }
  27181. }
  27182. class AnimationAction {
  27183. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27184. this._mixer = mixer;
  27185. this._clip = clip;
  27186. this._localRoot = localRoot;
  27187. this.blendMode = blendMode;
  27188. const tracks = clip.tracks,
  27189. nTracks = tracks.length,
  27190. interpolants = new Array( nTracks );
  27191. const interpolantSettings = {
  27192. endingStart: ZeroCurvatureEnding,
  27193. endingEnd: ZeroCurvatureEnding
  27194. };
  27195. for ( let i = 0; i !== nTracks; ++ i ) {
  27196. const interpolant = tracks[ i ].createInterpolant( null );
  27197. interpolants[ i ] = interpolant;
  27198. interpolant.settings = interpolantSettings;
  27199. }
  27200. this._interpolantSettings = interpolantSettings;
  27201. this._interpolants = interpolants; // bound by the mixer
  27202. // inside: PropertyMixer (managed by the mixer)
  27203. this._propertyBindings = new Array( nTracks );
  27204. this._cacheIndex = null; // for the memory manager
  27205. this._byClipCacheIndex = null; // for the memory manager
  27206. this._timeScaleInterpolant = null;
  27207. this._weightInterpolant = null;
  27208. this.loop = LoopRepeat;
  27209. this._loopCount = - 1;
  27210. // global mixer time when the action is to be started
  27211. // it's set back to 'null' upon start of the action
  27212. this._startTime = null;
  27213. // scaled local time of the action
  27214. // gets clamped or wrapped to 0..clip.duration according to loop
  27215. this.time = 0;
  27216. this.timeScale = 1;
  27217. this._effectiveTimeScale = 1;
  27218. this.weight = 1;
  27219. this._effectiveWeight = 1;
  27220. this.repetitions = Infinity; // no. of repetitions when looping
  27221. this.paused = false; // true -> zero effective time scale
  27222. this.enabled = true; // false -> zero effective weight
  27223. this.clampWhenFinished = false;// keep feeding the last frame?
  27224. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27225. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27226. }
  27227. // State & Scheduling
  27228. play() {
  27229. this._mixer._activateAction( this );
  27230. return this;
  27231. }
  27232. stop() {
  27233. this._mixer._deactivateAction( this );
  27234. return this.reset();
  27235. }
  27236. reset() {
  27237. this.paused = false;
  27238. this.enabled = true;
  27239. this.time = 0; // restart clip
  27240. this._loopCount = - 1;// forget previous loops
  27241. this._startTime = null;// forget scheduling
  27242. return this.stopFading().stopWarping();
  27243. }
  27244. isRunning() {
  27245. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27246. this._startTime === null && this._mixer._isActiveAction( this );
  27247. }
  27248. // return true when play has been called
  27249. isScheduled() {
  27250. return this._mixer._isActiveAction( this );
  27251. }
  27252. startAt( time ) {
  27253. this._startTime = time;
  27254. return this;
  27255. }
  27256. setLoop( mode, repetitions ) {
  27257. this.loop = mode;
  27258. this.repetitions = repetitions;
  27259. return this;
  27260. }
  27261. // Weight
  27262. // set the weight stopping any scheduled fading
  27263. // although .enabled = false yields an effective weight of zero, this
  27264. // method does *not* change .enabled, because it would be confusing
  27265. setEffectiveWeight( weight ) {
  27266. this.weight = weight;
  27267. // note: same logic as when updated at runtime
  27268. this._effectiveWeight = this.enabled ? weight : 0;
  27269. return this.stopFading();
  27270. }
  27271. // return the weight considering fading and .enabled
  27272. getEffectiveWeight() {
  27273. return this._effectiveWeight;
  27274. }
  27275. fadeIn( duration ) {
  27276. return this._scheduleFading( duration, 0, 1 );
  27277. }
  27278. fadeOut( duration ) {
  27279. return this._scheduleFading( duration, 1, 0 );
  27280. }
  27281. crossFadeFrom( fadeOutAction, duration, warp ) {
  27282. fadeOutAction.fadeOut( duration );
  27283. this.fadeIn( duration );
  27284. if ( warp ) {
  27285. const fadeInDuration = this._clip.duration,
  27286. fadeOutDuration = fadeOutAction._clip.duration,
  27287. startEndRatio = fadeOutDuration / fadeInDuration,
  27288. endStartRatio = fadeInDuration / fadeOutDuration;
  27289. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27290. this.warp( endStartRatio, 1.0, duration );
  27291. }
  27292. return this;
  27293. }
  27294. crossFadeTo( fadeInAction, duration, warp ) {
  27295. return fadeInAction.crossFadeFrom( this, duration, warp );
  27296. }
  27297. stopFading() {
  27298. const weightInterpolant = this._weightInterpolant;
  27299. if ( weightInterpolant !== null ) {
  27300. this._weightInterpolant = null;
  27301. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27302. }
  27303. return this;
  27304. }
  27305. // Time Scale Control
  27306. // set the time scale stopping any scheduled warping
  27307. // although .paused = true yields an effective time scale of zero, this
  27308. // method does *not* change .paused, because it would be confusing
  27309. setEffectiveTimeScale( timeScale ) {
  27310. this.timeScale = timeScale;
  27311. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27312. return this.stopWarping();
  27313. }
  27314. // return the time scale considering warping and .paused
  27315. getEffectiveTimeScale() {
  27316. return this._effectiveTimeScale;
  27317. }
  27318. setDuration( duration ) {
  27319. this.timeScale = this._clip.duration / duration;
  27320. return this.stopWarping();
  27321. }
  27322. syncWith( action ) {
  27323. this.time = action.time;
  27324. this.timeScale = action.timeScale;
  27325. return this.stopWarping();
  27326. }
  27327. halt( duration ) {
  27328. return this.warp( this._effectiveTimeScale, 0, duration );
  27329. }
  27330. warp( startTimeScale, endTimeScale, duration ) {
  27331. const mixer = this._mixer,
  27332. now = mixer.time,
  27333. timeScale = this.timeScale;
  27334. let interpolant = this._timeScaleInterpolant;
  27335. if ( interpolant === null ) {
  27336. interpolant = mixer._lendControlInterpolant();
  27337. this._timeScaleInterpolant = interpolant;
  27338. }
  27339. const times = interpolant.parameterPositions,
  27340. values = interpolant.sampleValues;
  27341. times[ 0 ] = now;
  27342. times[ 1 ] = now + duration;
  27343. values[ 0 ] = startTimeScale / timeScale;
  27344. values[ 1 ] = endTimeScale / timeScale;
  27345. return this;
  27346. }
  27347. stopWarping() {
  27348. const timeScaleInterpolant = this._timeScaleInterpolant;
  27349. if ( timeScaleInterpolant !== null ) {
  27350. this._timeScaleInterpolant = null;
  27351. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27352. }
  27353. return this;
  27354. }
  27355. // Object Accessors
  27356. getMixer() {
  27357. return this._mixer;
  27358. }
  27359. getClip() {
  27360. return this._clip;
  27361. }
  27362. getRoot() {
  27363. return this._localRoot || this._mixer._root;
  27364. }
  27365. // Interna
  27366. _update( time, deltaTime, timeDirection, accuIndex ) {
  27367. // called by the mixer
  27368. if ( ! this.enabled ) {
  27369. // call ._updateWeight() to update ._effectiveWeight
  27370. this._updateWeight( time );
  27371. return;
  27372. }
  27373. const startTime = this._startTime;
  27374. if ( startTime !== null ) {
  27375. // check for scheduled start of action
  27376. const timeRunning = ( time - startTime ) * timeDirection;
  27377. if ( timeRunning < 0 || timeDirection === 0 ) {
  27378. deltaTime = 0;
  27379. } else {
  27380. this._startTime = null; // unschedule
  27381. deltaTime = timeDirection * timeRunning;
  27382. }
  27383. }
  27384. // apply time scale and advance time
  27385. deltaTime *= this._updateTimeScale( time );
  27386. const clipTime = this._updateTime( deltaTime );
  27387. // note: _updateTime may disable the action resulting in
  27388. // an effective weight of 0
  27389. const weight = this._updateWeight( time );
  27390. if ( weight > 0 ) {
  27391. const interpolants = this._interpolants;
  27392. const propertyMixers = this._propertyBindings;
  27393. switch ( this.blendMode ) {
  27394. case AdditiveAnimationBlendMode:
  27395. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27396. interpolants[ j ].evaluate( clipTime );
  27397. propertyMixers[ j ].accumulateAdditive( weight );
  27398. }
  27399. break;
  27400. case NormalAnimationBlendMode:
  27401. default:
  27402. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27403. interpolants[ j ].evaluate( clipTime );
  27404. propertyMixers[ j ].accumulate( accuIndex, weight );
  27405. }
  27406. }
  27407. }
  27408. }
  27409. _updateWeight( time ) {
  27410. let weight = 0;
  27411. if ( this.enabled ) {
  27412. weight = this.weight;
  27413. const interpolant = this._weightInterpolant;
  27414. if ( interpolant !== null ) {
  27415. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27416. weight *= interpolantValue;
  27417. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27418. this.stopFading();
  27419. if ( interpolantValue === 0 ) {
  27420. // faded out, disable
  27421. this.enabled = false;
  27422. }
  27423. }
  27424. }
  27425. }
  27426. this._effectiveWeight = weight;
  27427. return weight;
  27428. }
  27429. _updateTimeScale( time ) {
  27430. let timeScale = 0;
  27431. if ( ! this.paused ) {
  27432. timeScale = this.timeScale;
  27433. const interpolant = this._timeScaleInterpolant;
  27434. if ( interpolant !== null ) {
  27435. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27436. timeScale *= interpolantValue;
  27437. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27438. this.stopWarping();
  27439. if ( timeScale === 0 ) {
  27440. // motion has halted, pause
  27441. this.paused = true;
  27442. } else {
  27443. // warp done - apply final time scale
  27444. this.timeScale = timeScale;
  27445. }
  27446. }
  27447. }
  27448. }
  27449. this._effectiveTimeScale = timeScale;
  27450. return timeScale;
  27451. }
  27452. _updateTime( deltaTime ) {
  27453. const duration = this._clip.duration;
  27454. const loop = this.loop;
  27455. let time = this.time + deltaTime;
  27456. let loopCount = this._loopCount;
  27457. const pingPong = ( loop === LoopPingPong );
  27458. if ( deltaTime === 0 ) {
  27459. if ( loopCount === - 1 ) return time;
  27460. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27461. }
  27462. if ( loop === LoopOnce ) {
  27463. if ( loopCount === - 1 ) {
  27464. // just started
  27465. this._loopCount = 0;
  27466. this._setEndings( true, true, false );
  27467. }
  27468. handle_stop: {
  27469. if ( time >= duration ) {
  27470. time = duration;
  27471. } else if ( time < 0 ) {
  27472. time = 0;
  27473. } else {
  27474. this.time = time;
  27475. break handle_stop;
  27476. }
  27477. if ( this.clampWhenFinished ) this.paused = true;
  27478. else this.enabled = false;
  27479. this.time = time;
  27480. this._mixer.dispatchEvent( {
  27481. type: 'finished', action: this,
  27482. direction: deltaTime < 0 ? - 1 : 1
  27483. } );
  27484. }
  27485. } else { // repetitive Repeat or PingPong
  27486. if ( loopCount === - 1 ) {
  27487. // just started
  27488. if ( deltaTime >= 0 ) {
  27489. loopCount = 0;
  27490. this._setEndings( true, this.repetitions === 0, pingPong );
  27491. } else {
  27492. // when looping in reverse direction, the initial
  27493. // transition through zero counts as a repetition,
  27494. // so leave loopCount at -1
  27495. this._setEndings( this.repetitions === 0, true, pingPong );
  27496. }
  27497. }
  27498. if ( time >= duration || time < 0 ) {
  27499. // wrap around
  27500. const loopDelta = Math.floor( time / duration ); // signed
  27501. time -= duration * loopDelta;
  27502. loopCount += Math.abs( loopDelta );
  27503. const pending = this.repetitions - loopCount;
  27504. if ( pending <= 0 ) {
  27505. // have to stop (switch state, clamp time, fire event)
  27506. if ( this.clampWhenFinished ) this.paused = true;
  27507. else this.enabled = false;
  27508. time = deltaTime > 0 ? duration : 0;
  27509. this.time = time;
  27510. this._mixer.dispatchEvent( {
  27511. type: 'finished', action: this,
  27512. direction: deltaTime > 0 ? 1 : - 1
  27513. } );
  27514. } else {
  27515. // keep running
  27516. if ( pending === 1 ) {
  27517. // entering the last round
  27518. const atStart = deltaTime < 0;
  27519. this._setEndings( atStart, ! atStart, pingPong );
  27520. } else {
  27521. this._setEndings( false, false, pingPong );
  27522. }
  27523. this._loopCount = loopCount;
  27524. this.time = time;
  27525. this._mixer.dispatchEvent( {
  27526. type: 'loop', action: this, loopDelta: loopDelta
  27527. } );
  27528. }
  27529. } else {
  27530. this.time = time;
  27531. }
  27532. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27533. // invert time for the "pong round"
  27534. return duration - time;
  27535. }
  27536. }
  27537. return time;
  27538. }
  27539. _setEndings( atStart, atEnd, pingPong ) {
  27540. const settings = this._interpolantSettings;
  27541. if ( pingPong ) {
  27542. settings.endingStart = ZeroSlopeEnding;
  27543. settings.endingEnd = ZeroSlopeEnding;
  27544. } else {
  27545. // assuming for LoopOnce atStart == atEnd == true
  27546. if ( atStart ) {
  27547. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27548. } else {
  27549. settings.endingStart = WrapAroundEnding;
  27550. }
  27551. if ( atEnd ) {
  27552. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27553. } else {
  27554. settings.endingEnd = WrapAroundEnding;
  27555. }
  27556. }
  27557. }
  27558. _scheduleFading( duration, weightNow, weightThen ) {
  27559. const mixer = this._mixer, now = mixer.time;
  27560. let interpolant = this._weightInterpolant;
  27561. if ( interpolant === null ) {
  27562. interpolant = mixer._lendControlInterpolant();
  27563. this._weightInterpolant = interpolant;
  27564. }
  27565. const times = interpolant.parameterPositions,
  27566. values = interpolant.sampleValues;
  27567. times[ 0 ] = now;
  27568. values[ 0 ] = weightNow;
  27569. times[ 1 ] = now + duration;
  27570. values[ 1 ] = weightThen;
  27571. return this;
  27572. }
  27573. }
  27574. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27575. class AnimationMixer extends EventDispatcher {
  27576. constructor( root ) {
  27577. super();
  27578. this._root = root;
  27579. this._initMemoryManager();
  27580. this._accuIndex = 0;
  27581. this.time = 0;
  27582. this.timeScale = 1.0;
  27583. }
  27584. _bindAction( action, prototypeAction ) {
  27585. const root = action._localRoot || this._root,
  27586. tracks = action._clip.tracks,
  27587. nTracks = tracks.length,
  27588. bindings = action._propertyBindings,
  27589. interpolants = action._interpolants,
  27590. rootUuid = root.uuid,
  27591. bindingsByRoot = this._bindingsByRootAndName;
  27592. let bindingsByName = bindingsByRoot[ rootUuid ];
  27593. if ( bindingsByName === undefined ) {
  27594. bindingsByName = {};
  27595. bindingsByRoot[ rootUuid ] = bindingsByName;
  27596. }
  27597. for ( let i = 0; i !== nTracks; ++ i ) {
  27598. const track = tracks[ i ],
  27599. trackName = track.name;
  27600. let binding = bindingsByName[ trackName ];
  27601. if ( binding !== undefined ) {
  27602. ++ binding.referenceCount;
  27603. bindings[ i ] = binding;
  27604. } else {
  27605. binding = bindings[ i ];
  27606. if ( binding !== undefined ) {
  27607. // existing binding, make sure the cache knows
  27608. if ( binding._cacheIndex === null ) {
  27609. ++ binding.referenceCount;
  27610. this._addInactiveBinding( binding, rootUuid, trackName );
  27611. }
  27612. continue;
  27613. }
  27614. const path = prototypeAction && prototypeAction.
  27615. _propertyBindings[ i ].binding.parsedPath;
  27616. binding = new PropertyMixer(
  27617. PropertyBinding.create( root, trackName, path ),
  27618. track.ValueTypeName, track.getValueSize() );
  27619. ++ binding.referenceCount;
  27620. this._addInactiveBinding( binding, rootUuid, trackName );
  27621. bindings[ i ] = binding;
  27622. }
  27623. interpolants[ i ].resultBuffer = binding.buffer;
  27624. }
  27625. }
  27626. _activateAction( action ) {
  27627. if ( ! this._isActiveAction( action ) ) {
  27628. if ( action._cacheIndex === null ) {
  27629. // this action has been forgotten by the cache, but the user
  27630. // appears to be still using it -> rebind
  27631. const rootUuid = ( action._localRoot || this._root ).uuid,
  27632. clipUuid = action._clip.uuid,
  27633. actionsForClip = this._actionsByClip[ clipUuid ];
  27634. this._bindAction( action,
  27635. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27636. this._addInactiveAction( action, clipUuid, rootUuid );
  27637. }
  27638. const bindings = action._propertyBindings;
  27639. // increment reference counts / sort out state
  27640. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27641. const binding = bindings[ i ];
  27642. if ( binding.useCount ++ === 0 ) {
  27643. this._lendBinding( binding );
  27644. binding.saveOriginalState();
  27645. }
  27646. }
  27647. this._lendAction( action );
  27648. }
  27649. }
  27650. _deactivateAction( action ) {
  27651. if ( this._isActiveAction( action ) ) {
  27652. const bindings = action._propertyBindings;
  27653. // decrement reference counts / sort out state
  27654. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27655. const binding = bindings[ i ];
  27656. if ( -- binding.useCount === 0 ) {
  27657. binding.restoreOriginalState();
  27658. this._takeBackBinding( binding );
  27659. }
  27660. }
  27661. this._takeBackAction( action );
  27662. }
  27663. }
  27664. // Memory manager
  27665. _initMemoryManager() {
  27666. this._actions = []; // 'nActiveActions' followed by inactive ones
  27667. this._nActiveActions = 0;
  27668. this._actionsByClip = {};
  27669. // inside:
  27670. // {
  27671. // knownActions: Array< AnimationAction > - used as prototypes
  27672. // actionByRoot: AnimationAction - lookup
  27673. // }
  27674. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27675. this._nActiveBindings = 0;
  27676. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27677. this._controlInterpolants = []; // same game as above
  27678. this._nActiveControlInterpolants = 0;
  27679. const scope = this;
  27680. this.stats = {
  27681. actions: {
  27682. get total() {
  27683. return scope._actions.length;
  27684. },
  27685. get inUse() {
  27686. return scope._nActiveActions;
  27687. }
  27688. },
  27689. bindings: {
  27690. get total() {
  27691. return scope._bindings.length;
  27692. },
  27693. get inUse() {
  27694. return scope._nActiveBindings;
  27695. }
  27696. },
  27697. controlInterpolants: {
  27698. get total() {
  27699. return scope._controlInterpolants.length;
  27700. },
  27701. get inUse() {
  27702. return scope._nActiveControlInterpolants;
  27703. }
  27704. }
  27705. };
  27706. }
  27707. // Memory management for AnimationAction objects
  27708. _isActiveAction( action ) {
  27709. const index = action._cacheIndex;
  27710. return index !== null && index < this._nActiveActions;
  27711. }
  27712. _addInactiveAction( action, clipUuid, rootUuid ) {
  27713. const actions = this._actions,
  27714. actionsByClip = this._actionsByClip;
  27715. let actionsForClip = actionsByClip[ clipUuid ];
  27716. if ( actionsForClip === undefined ) {
  27717. actionsForClip = {
  27718. knownActions: [ action ],
  27719. actionByRoot: {}
  27720. };
  27721. action._byClipCacheIndex = 0;
  27722. actionsByClip[ clipUuid ] = actionsForClip;
  27723. } else {
  27724. const knownActions = actionsForClip.knownActions;
  27725. action._byClipCacheIndex = knownActions.length;
  27726. knownActions.push( action );
  27727. }
  27728. action._cacheIndex = actions.length;
  27729. actions.push( action );
  27730. actionsForClip.actionByRoot[ rootUuid ] = action;
  27731. }
  27732. _removeInactiveAction( action ) {
  27733. const actions = this._actions,
  27734. lastInactiveAction = actions[ actions.length - 1 ],
  27735. cacheIndex = action._cacheIndex;
  27736. lastInactiveAction._cacheIndex = cacheIndex;
  27737. actions[ cacheIndex ] = lastInactiveAction;
  27738. actions.pop();
  27739. action._cacheIndex = null;
  27740. const clipUuid = action._clip.uuid,
  27741. actionsByClip = this._actionsByClip,
  27742. actionsForClip = actionsByClip[ clipUuid ],
  27743. knownActionsForClip = actionsForClip.knownActions,
  27744. lastKnownAction =
  27745. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27746. byClipCacheIndex = action._byClipCacheIndex;
  27747. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27748. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27749. knownActionsForClip.pop();
  27750. action._byClipCacheIndex = null;
  27751. const actionByRoot = actionsForClip.actionByRoot,
  27752. rootUuid = ( action._localRoot || this._root ).uuid;
  27753. delete actionByRoot[ rootUuid ];
  27754. if ( knownActionsForClip.length === 0 ) {
  27755. delete actionsByClip[ clipUuid ];
  27756. }
  27757. this._removeInactiveBindingsForAction( action );
  27758. }
  27759. _removeInactiveBindingsForAction( action ) {
  27760. const bindings = action._propertyBindings;
  27761. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27762. const binding = bindings[ i ];
  27763. if ( -- binding.referenceCount === 0 ) {
  27764. this._removeInactiveBinding( binding );
  27765. }
  27766. }
  27767. }
  27768. _lendAction( action ) {
  27769. // [ active actions | inactive actions ]
  27770. // [ active actions >| inactive actions ]
  27771. // s a
  27772. // <-swap->
  27773. // a s
  27774. const actions = this._actions,
  27775. prevIndex = action._cacheIndex,
  27776. lastActiveIndex = this._nActiveActions ++,
  27777. firstInactiveAction = actions[ lastActiveIndex ];
  27778. action._cacheIndex = lastActiveIndex;
  27779. actions[ lastActiveIndex ] = action;
  27780. firstInactiveAction._cacheIndex = prevIndex;
  27781. actions[ prevIndex ] = firstInactiveAction;
  27782. }
  27783. _takeBackAction( action ) {
  27784. // [ active actions | inactive actions ]
  27785. // [ active actions |< inactive actions ]
  27786. // a s
  27787. // <-swap->
  27788. // s a
  27789. const actions = this._actions,
  27790. prevIndex = action._cacheIndex,
  27791. firstInactiveIndex = -- this._nActiveActions,
  27792. lastActiveAction = actions[ firstInactiveIndex ];
  27793. action._cacheIndex = firstInactiveIndex;
  27794. actions[ firstInactiveIndex ] = action;
  27795. lastActiveAction._cacheIndex = prevIndex;
  27796. actions[ prevIndex ] = lastActiveAction;
  27797. }
  27798. // Memory management for PropertyMixer objects
  27799. _addInactiveBinding( binding, rootUuid, trackName ) {
  27800. const bindingsByRoot = this._bindingsByRootAndName,
  27801. bindings = this._bindings;
  27802. let bindingByName = bindingsByRoot[ rootUuid ];
  27803. if ( bindingByName === undefined ) {
  27804. bindingByName = {};
  27805. bindingsByRoot[ rootUuid ] = bindingByName;
  27806. }
  27807. bindingByName[ trackName ] = binding;
  27808. binding._cacheIndex = bindings.length;
  27809. bindings.push( binding );
  27810. }
  27811. _removeInactiveBinding( binding ) {
  27812. const bindings = this._bindings,
  27813. propBinding = binding.binding,
  27814. rootUuid = propBinding.rootNode.uuid,
  27815. trackName = propBinding.path,
  27816. bindingsByRoot = this._bindingsByRootAndName,
  27817. bindingByName = bindingsByRoot[ rootUuid ],
  27818. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27819. cacheIndex = binding._cacheIndex;
  27820. lastInactiveBinding._cacheIndex = cacheIndex;
  27821. bindings[ cacheIndex ] = lastInactiveBinding;
  27822. bindings.pop();
  27823. delete bindingByName[ trackName ];
  27824. if ( Object.keys( bindingByName ).length === 0 ) {
  27825. delete bindingsByRoot[ rootUuid ];
  27826. }
  27827. }
  27828. _lendBinding( binding ) {
  27829. const bindings = this._bindings,
  27830. prevIndex = binding._cacheIndex,
  27831. lastActiveIndex = this._nActiveBindings ++,
  27832. firstInactiveBinding = bindings[ lastActiveIndex ];
  27833. binding._cacheIndex = lastActiveIndex;
  27834. bindings[ lastActiveIndex ] = binding;
  27835. firstInactiveBinding._cacheIndex = prevIndex;
  27836. bindings[ prevIndex ] = firstInactiveBinding;
  27837. }
  27838. _takeBackBinding( binding ) {
  27839. const bindings = this._bindings,
  27840. prevIndex = binding._cacheIndex,
  27841. firstInactiveIndex = -- this._nActiveBindings,
  27842. lastActiveBinding = bindings[ firstInactiveIndex ];
  27843. binding._cacheIndex = firstInactiveIndex;
  27844. bindings[ firstInactiveIndex ] = binding;
  27845. lastActiveBinding._cacheIndex = prevIndex;
  27846. bindings[ prevIndex ] = lastActiveBinding;
  27847. }
  27848. // Memory management of Interpolants for weight and time scale
  27849. _lendControlInterpolant() {
  27850. const interpolants = this._controlInterpolants,
  27851. lastActiveIndex = this._nActiveControlInterpolants ++;
  27852. let interpolant = interpolants[ lastActiveIndex ];
  27853. if ( interpolant === undefined ) {
  27854. interpolant = new LinearInterpolant(
  27855. new Float32Array( 2 ), new Float32Array( 2 ),
  27856. 1, _controlInterpolantsResultBuffer );
  27857. interpolant.__cacheIndex = lastActiveIndex;
  27858. interpolants[ lastActiveIndex ] = interpolant;
  27859. }
  27860. return interpolant;
  27861. }
  27862. _takeBackControlInterpolant( interpolant ) {
  27863. const interpolants = this._controlInterpolants,
  27864. prevIndex = interpolant.__cacheIndex,
  27865. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27866. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27867. interpolant.__cacheIndex = firstInactiveIndex;
  27868. interpolants[ firstInactiveIndex ] = interpolant;
  27869. lastActiveInterpolant.__cacheIndex = prevIndex;
  27870. interpolants[ prevIndex ] = lastActiveInterpolant;
  27871. }
  27872. // return an action for a clip optionally using a custom root target
  27873. // object (this method allocates a lot of dynamic memory in case a
  27874. // previously unknown clip/root combination is specified)
  27875. clipAction( clip, optionalRoot, blendMode ) {
  27876. const root = optionalRoot || this._root,
  27877. rootUuid = root.uuid;
  27878. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27879. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27880. const actionsForClip = this._actionsByClip[ clipUuid ];
  27881. let prototypeAction = null;
  27882. if ( blendMode === undefined ) {
  27883. if ( clipObject !== null ) {
  27884. blendMode = clipObject.blendMode;
  27885. } else {
  27886. blendMode = NormalAnimationBlendMode;
  27887. }
  27888. }
  27889. if ( actionsForClip !== undefined ) {
  27890. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27891. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27892. return existingAction;
  27893. }
  27894. // we know the clip, so we don't have to parse all
  27895. // the bindings again but can just copy
  27896. prototypeAction = actionsForClip.knownActions[ 0 ];
  27897. // also, take the clip from the prototype action
  27898. if ( clipObject === null )
  27899. clipObject = prototypeAction._clip;
  27900. }
  27901. // clip must be known when specified via string
  27902. if ( clipObject === null ) return null;
  27903. // allocate all resources required to run it
  27904. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27905. this._bindAction( newAction, prototypeAction );
  27906. // and make the action known to the memory manager
  27907. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27908. return newAction;
  27909. }
  27910. // get an existing action
  27911. existingAction( clip, optionalRoot ) {
  27912. const root = optionalRoot || this._root,
  27913. rootUuid = root.uuid,
  27914. clipObject = typeof clip === 'string' ?
  27915. AnimationClip.findByName( root, clip ) : clip,
  27916. clipUuid = clipObject ? clipObject.uuid : clip,
  27917. actionsForClip = this._actionsByClip[ clipUuid ];
  27918. if ( actionsForClip !== undefined ) {
  27919. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27920. }
  27921. return null;
  27922. }
  27923. // deactivates all previously scheduled actions
  27924. stopAllAction() {
  27925. const actions = this._actions,
  27926. nActions = this._nActiveActions;
  27927. for ( let i = nActions - 1; i >= 0; -- i ) {
  27928. actions[ i ].stop();
  27929. }
  27930. return this;
  27931. }
  27932. // advance the time and update apply the animation
  27933. update( deltaTime ) {
  27934. deltaTime *= this.timeScale;
  27935. const actions = this._actions,
  27936. nActions = this._nActiveActions,
  27937. time = this.time += deltaTime,
  27938. timeDirection = Math.sign( deltaTime ),
  27939. accuIndex = this._accuIndex ^= 1;
  27940. // run active actions
  27941. for ( let i = 0; i !== nActions; ++ i ) {
  27942. const action = actions[ i ];
  27943. action._update( time, deltaTime, timeDirection, accuIndex );
  27944. }
  27945. // update scene graph
  27946. const bindings = this._bindings,
  27947. nBindings = this._nActiveBindings;
  27948. for ( let i = 0; i !== nBindings; ++ i ) {
  27949. bindings[ i ].apply( accuIndex );
  27950. }
  27951. return this;
  27952. }
  27953. // Allows you to seek to a specific time in an animation.
  27954. setTime( timeInSeconds ) {
  27955. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27956. for ( let i = 0; i < this._actions.length; i ++ ) {
  27957. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27958. }
  27959. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27960. }
  27961. // return this mixer's root target object
  27962. getRoot() {
  27963. return this._root;
  27964. }
  27965. // free all resources specific to a particular clip
  27966. uncacheClip( clip ) {
  27967. const actions = this._actions,
  27968. clipUuid = clip.uuid,
  27969. actionsByClip = this._actionsByClip,
  27970. actionsForClip = actionsByClip[ clipUuid ];
  27971. if ( actionsForClip !== undefined ) {
  27972. // note: just calling _removeInactiveAction would mess up the
  27973. // iteration state and also require updating the state we can
  27974. // just throw away
  27975. const actionsToRemove = actionsForClip.knownActions;
  27976. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27977. const action = actionsToRemove[ i ];
  27978. this._deactivateAction( action );
  27979. const cacheIndex = action._cacheIndex,
  27980. lastInactiveAction = actions[ actions.length - 1 ];
  27981. action._cacheIndex = null;
  27982. action._byClipCacheIndex = null;
  27983. lastInactiveAction._cacheIndex = cacheIndex;
  27984. actions[ cacheIndex ] = lastInactiveAction;
  27985. actions.pop();
  27986. this._removeInactiveBindingsForAction( action );
  27987. }
  27988. delete actionsByClip[ clipUuid ];
  27989. }
  27990. }
  27991. // free all resources specific to a particular root target object
  27992. uncacheRoot( root ) {
  27993. const rootUuid = root.uuid,
  27994. actionsByClip = this._actionsByClip;
  27995. for ( const clipUuid in actionsByClip ) {
  27996. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27997. action = actionByRoot[ rootUuid ];
  27998. if ( action !== undefined ) {
  27999. this._deactivateAction( action );
  28000. this._removeInactiveAction( action );
  28001. }
  28002. }
  28003. const bindingsByRoot = this._bindingsByRootAndName,
  28004. bindingByName = bindingsByRoot[ rootUuid ];
  28005. if ( bindingByName !== undefined ) {
  28006. for ( const trackName in bindingByName ) {
  28007. const binding = bindingByName[ trackName ];
  28008. binding.restoreOriginalState();
  28009. this._removeInactiveBinding( binding );
  28010. }
  28011. }
  28012. }
  28013. // remove a targeted clip from the cache
  28014. uncacheAction( clip, optionalRoot ) {
  28015. const action = this.existingAction( clip, optionalRoot );
  28016. if ( action !== null ) {
  28017. this._deactivateAction( action );
  28018. this._removeInactiveAction( action );
  28019. }
  28020. }
  28021. }
  28022. class Uniform {
  28023. constructor( value ) {
  28024. this.value = value;
  28025. }
  28026. clone() {
  28027. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28028. }
  28029. }
  28030. let id = 0;
  28031. class UniformsGroup extends EventDispatcher {
  28032. constructor() {
  28033. super();
  28034. this.isUniformsGroup = true;
  28035. Object.defineProperty( this, 'id', { value: id ++ } );
  28036. this.name = '';
  28037. this.usage = StaticDrawUsage;
  28038. this.uniforms = [];
  28039. }
  28040. add( uniform ) {
  28041. this.uniforms.push( uniform );
  28042. return this;
  28043. }
  28044. remove( uniform ) {
  28045. const index = this.uniforms.indexOf( uniform );
  28046. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28047. return this;
  28048. }
  28049. setName( name ) {
  28050. this.name = name;
  28051. return this;
  28052. }
  28053. setUsage( value ) {
  28054. this.usage = value;
  28055. return this;
  28056. }
  28057. dispose() {
  28058. this.dispatchEvent( { type: 'dispose' } );
  28059. return this;
  28060. }
  28061. copy( source ) {
  28062. this.name = source.name;
  28063. this.usage = source.usage;
  28064. const uniformsSource = source.uniforms;
  28065. this.uniforms.length = 0;
  28066. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28067. this.uniforms.push( uniformsSource[ i ].clone() );
  28068. }
  28069. return this;
  28070. }
  28071. clone() {
  28072. return new this.constructor().copy( this );
  28073. }
  28074. }
  28075. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28076. constructor( array, stride, meshPerAttribute = 1 ) {
  28077. super( array, stride );
  28078. this.isInstancedInterleavedBuffer = true;
  28079. this.meshPerAttribute = meshPerAttribute;
  28080. }
  28081. copy( source ) {
  28082. super.copy( source );
  28083. this.meshPerAttribute = source.meshPerAttribute;
  28084. return this;
  28085. }
  28086. clone( data ) {
  28087. const ib = super.clone( data );
  28088. ib.meshPerAttribute = this.meshPerAttribute;
  28089. return ib;
  28090. }
  28091. toJSON( data ) {
  28092. const json = super.toJSON( data );
  28093. json.isInstancedInterleavedBuffer = true;
  28094. json.meshPerAttribute = this.meshPerAttribute;
  28095. return json;
  28096. }
  28097. }
  28098. class GLBufferAttribute {
  28099. constructor( buffer, type, itemSize, elementSize, count ) {
  28100. this.isGLBufferAttribute = true;
  28101. this.name = '';
  28102. this.buffer = buffer;
  28103. this.type = type;
  28104. this.itemSize = itemSize;
  28105. this.elementSize = elementSize;
  28106. this.count = count;
  28107. this.version = 0;
  28108. }
  28109. set needsUpdate( value ) {
  28110. if ( value === true ) this.version ++;
  28111. }
  28112. setBuffer( buffer ) {
  28113. this.buffer = buffer;
  28114. return this;
  28115. }
  28116. setType( type, elementSize ) {
  28117. this.type = type;
  28118. this.elementSize = elementSize;
  28119. return this;
  28120. }
  28121. setItemSize( itemSize ) {
  28122. this.itemSize = itemSize;
  28123. return this;
  28124. }
  28125. setCount( count ) {
  28126. this.count = count;
  28127. return this;
  28128. }
  28129. }
  28130. class Raycaster {
  28131. constructor( origin, direction, near = 0, far = Infinity ) {
  28132. this.ray = new Ray( origin, direction );
  28133. // direction is assumed to be normalized (for accurate distance calculations)
  28134. this.near = near;
  28135. this.far = far;
  28136. this.camera = null;
  28137. this.layers = new Layers();
  28138. this.params = {
  28139. Mesh: {},
  28140. Line: { threshold: 1 },
  28141. LOD: {},
  28142. Points: { threshold: 1 },
  28143. Sprite: {}
  28144. };
  28145. }
  28146. set( origin, direction ) {
  28147. // direction is assumed to be normalized (for accurate distance calculations)
  28148. this.ray.set( origin, direction );
  28149. }
  28150. setFromCamera( coords, camera ) {
  28151. if ( camera.isPerspectiveCamera ) {
  28152. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28153. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28154. this.camera = camera;
  28155. } else if ( camera.isOrthographicCamera ) {
  28156. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28157. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28158. this.camera = camera;
  28159. } else {
  28160. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28161. }
  28162. }
  28163. intersectObject( object, recursive = true, intersects = [] ) {
  28164. intersectObject( object, this, intersects, recursive );
  28165. intersects.sort( ascSort );
  28166. return intersects;
  28167. }
  28168. intersectObjects( objects, recursive = true, intersects = [] ) {
  28169. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28170. intersectObject( objects[ i ], this, intersects, recursive );
  28171. }
  28172. intersects.sort( ascSort );
  28173. return intersects;
  28174. }
  28175. }
  28176. function ascSort( a, b ) {
  28177. return a.distance - b.distance;
  28178. }
  28179. function intersectObject( object, raycaster, intersects, recursive ) {
  28180. if ( object.layers.test( raycaster.layers ) ) {
  28181. object.raycast( raycaster, intersects );
  28182. }
  28183. if ( recursive === true ) {
  28184. const children = object.children;
  28185. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28186. intersectObject( children[ i ], raycaster, intersects, true );
  28187. }
  28188. }
  28189. }
  28190. /**
  28191. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28192. *
  28193. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28194. * The azimuthal angle (theta) is measured from the positive z-axis.
  28195. */
  28196. class Spherical {
  28197. constructor( radius = 1, phi = 0, theta = 0 ) {
  28198. this.radius = radius;
  28199. this.phi = phi; // polar angle
  28200. this.theta = theta; // azimuthal angle
  28201. return this;
  28202. }
  28203. set( radius, phi, theta ) {
  28204. this.radius = radius;
  28205. this.phi = phi;
  28206. this.theta = theta;
  28207. return this;
  28208. }
  28209. copy( other ) {
  28210. this.radius = other.radius;
  28211. this.phi = other.phi;
  28212. this.theta = other.theta;
  28213. return this;
  28214. }
  28215. // restrict phi to be between EPS and PI-EPS
  28216. makeSafe() {
  28217. const EPS = 0.000001;
  28218. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28219. return this;
  28220. }
  28221. setFromVector3( v ) {
  28222. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28223. }
  28224. setFromCartesianCoords( x, y, z ) {
  28225. this.radius = Math.sqrt( x * x + y * y + z * z );
  28226. if ( this.radius === 0 ) {
  28227. this.theta = 0;
  28228. this.phi = 0;
  28229. } else {
  28230. this.theta = Math.atan2( x, z );
  28231. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28232. }
  28233. return this;
  28234. }
  28235. clone() {
  28236. return new this.constructor().copy( this );
  28237. }
  28238. }
  28239. /**
  28240. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28241. */
  28242. class Cylindrical {
  28243. constructor( radius = 1, theta = 0, y = 0 ) {
  28244. this.radius = radius; // distance from the origin to a point in the x-z plane
  28245. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28246. this.y = y; // height above the x-z plane
  28247. return this;
  28248. }
  28249. set( radius, theta, y ) {
  28250. this.radius = radius;
  28251. this.theta = theta;
  28252. this.y = y;
  28253. return this;
  28254. }
  28255. copy( other ) {
  28256. this.radius = other.radius;
  28257. this.theta = other.theta;
  28258. this.y = other.y;
  28259. return this;
  28260. }
  28261. setFromVector3( v ) {
  28262. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28263. }
  28264. setFromCartesianCoords( x, y, z ) {
  28265. this.radius = Math.sqrt( x * x + z * z );
  28266. this.theta = Math.atan2( x, z );
  28267. this.y = y;
  28268. return this;
  28269. }
  28270. clone() {
  28271. return new this.constructor().copy( this );
  28272. }
  28273. }
  28274. const _vector$4 = /*@__PURE__*/ new Vector2();
  28275. class Box2 {
  28276. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28277. this.isBox2 = true;
  28278. this.min = min;
  28279. this.max = max;
  28280. }
  28281. set( min, max ) {
  28282. this.min.copy( min );
  28283. this.max.copy( max );
  28284. return this;
  28285. }
  28286. setFromPoints( points ) {
  28287. this.makeEmpty();
  28288. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28289. this.expandByPoint( points[ i ] );
  28290. }
  28291. return this;
  28292. }
  28293. setFromCenterAndSize( center, size ) {
  28294. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28295. this.min.copy( center ).sub( halfSize );
  28296. this.max.copy( center ).add( halfSize );
  28297. return this;
  28298. }
  28299. clone() {
  28300. return new this.constructor().copy( this );
  28301. }
  28302. copy( box ) {
  28303. this.min.copy( box.min );
  28304. this.max.copy( box.max );
  28305. return this;
  28306. }
  28307. makeEmpty() {
  28308. this.min.x = this.min.y = + Infinity;
  28309. this.max.x = this.max.y = - Infinity;
  28310. return this;
  28311. }
  28312. isEmpty() {
  28313. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28314. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28315. }
  28316. getCenter( target ) {
  28317. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28318. }
  28319. getSize( target ) {
  28320. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28321. }
  28322. expandByPoint( point ) {
  28323. this.min.min( point );
  28324. this.max.max( point );
  28325. return this;
  28326. }
  28327. expandByVector( vector ) {
  28328. this.min.sub( vector );
  28329. this.max.add( vector );
  28330. return this;
  28331. }
  28332. expandByScalar( scalar ) {
  28333. this.min.addScalar( - scalar );
  28334. this.max.addScalar( scalar );
  28335. return this;
  28336. }
  28337. containsPoint( point ) {
  28338. return point.x < this.min.x || point.x > this.max.x ||
  28339. point.y < this.min.y || point.y > this.max.y ? false : true;
  28340. }
  28341. containsBox( box ) {
  28342. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28343. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28344. }
  28345. getParameter( point, target ) {
  28346. // This can potentially have a divide by zero if the box
  28347. // has a size dimension of 0.
  28348. return target.set(
  28349. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28350. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28351. );
  28352. }
  28353. intersectsBox( box ) {
  28354. // using 4 splitting planes to rule out intersections
  28355. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28356. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28357. }
  28358. clampPoint( point, target ) {
  28359. return target.copy( point ).clamp( this.min, this.max );
  28360. }
  28361. distanceToPoint( point ) {
  28362. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28363. return clampedPoint.sub( point ).length();
  28364. }
  28365. intersect( box ) {
  28366. this.min.max( box.min );
  28367. this.max.min( box.max );
  28368. return this;
  28369. }
  28370. union( box ) {
  28371. this.min.min( box.min );
  28372. this.max.max( box.max );
  28373. return this;
  28374. }
  28375. translate( offset ) {
  28376. this.min.add( offset );
  28377. this.max.add( offset );
  28378. return this;
  28379. }
  28380. equals( box ) {
  28381. return box.min.equals( this.min ) && box.max.equals( this.max );
  28382. }
  28383. }
  28384. const _startP = /*@__PURE__*/ new Vector3();
  28385. const _startEnd = /*@__PURE__*/ new Vector3();
  28386. class Line3 {
  28387. constructor( start = new Vector3(), end = new Vector3() ) {
  28388. this.start = start;
  28389. this.end = end;
  28390. }
  28391. set( start, end ) {
  28392. this.start.copy( start );
  28393. this.end.copy( end );
  28394. return this;
  28395. }
  28396. copy( line ) {
  28397. this.start.copy( line.start );
  28398. this.end.copy( line.end );
  28399. return this;
  28400. }
  28401. getCenter( target ) {
  28402. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28403. }
  28404. delta( target ) {
  28405. return target.subVectors( this.end, this.start );
  28406. }
  28407. distanceSq() {
  28408. return this.start.distanceToSquared( this.end );
  28409. }
  28410. distance() {
  28411. return this.start.distanceTo( this.end );
  28412. }
  28413. at( t, target ) {
  28414. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28415. }
  28416. closestPointToPointParameter( point, clampToLine ) {
  28417. _startP.subVectors( point, this.start );
  28418. _startEnd.subVectors( this.end, this.start );
  28419. const startEnd2 = _startEnd.dot( _startEnd );
  28420. const startEnd_startP = _startEnd.dot( _startP );
  28421. let t = startEnd_startP / startEnd2;
  28422. if ( clampToLine ) {
  28423. t = clamp( t, 0, 1 );
  28424. }
  28425. return t;
  28426. }
  28427. closestPointToPoint( point, clampToLine, target ) {
  28428. const t = this.closestPointToPointParameter( point, clampToLine );
  28429. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28430. }
  28431. applyMatrix4( matrix ) {
  28432. this.start.applyMatrix4( matrix );
  28433. this.end.applyMatrix4( matrix );
  28434. return this;
  28435. }
  28436. equals( line ) {
  28437. return line.start.equals( this.start ) && line.end.equals( this.end );
  28438. }
  28439. clone() {
  28440. return new this.constructor().copy( this );
  28441. }
  28442. }
  28443. const _vector$3 = /*@__PURE__*/ new Vector3();
  28444. class SpotLightHelper extends Object3D {
  28445. constructor( light, color ) {
  28446. super();
  28447. this.light = light;
  28448. this.matrix = light.matrixWorld;
  28449. this.matrixAutoUpdate = false;
  28450. this.color = color;
  28451. this.type = 'SpotLightHelper';
  28452. const geometry = new BufferGeometry();
  28453. const positions = [
  28454. 0, 0, 0, 0, 0, 1,
  28455. 0, 0, 0, 1, 0, 1,
  28456. 0, 0, 0, - 1, 0, 1,
  28457. 0, 0, 0, 0, 1, 1,
  28458. 0, 0, 0, 0, - 1, 1
  28459. ];
  28460. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28461. const p1 = ( i / l ) * Math.PI * 2;
  28462. const p2 = ( j / l ) * Math.PI * 2;
  28463. positions.push(
  28464. Math.cos( p1 ), Math.sin( p1 ), 1,
  28465. Math.cos( p2 ), Math.sin( p2 ), 1
  28466. );
  28467. }
  28468. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28469. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28470. this.cone = new LineSegments( geometry, material );
  28471. this.add( this.cone );
  28472. this.update();
  28473. }
  28474. dispose() {
  28475. this.cone.geometry.dispose();
  28476. this.cone.material.dispose();
  28477. }
  28478. update() {
  28479. this.light.updateWorldMatrix( true, false );
  28480. this.light.target.updateWorldMatrix( true, false );
  28481. const coneLength = this.light.distance ? this.light.distance : 1000;
  28482. const coneWidth = coneLength * Math.tan( this.light.angle );
  28483. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28484. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28485. this.cone.lookAt( _vector$3 );
  28486. if ( this.color !== undefined ) {
  28487. this.cone.material.color.set( this.color );
  28488. } else {
  28489. this.cone.material.color.copy( this.light.color );
  28490. }
  28491. }
  28492. }
  28493. const _vector$2 = /*@__PURE__*/ new Vector3();
  28494. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28495. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28496. class SkeletonHelper extends LineSegments {
  28497. constructor( object ) {
  28498. const bones = getBoneList( object );
  28499. const geometry = new BufferGeometry();
  28500. const vertices = [];
  28501. const colors = [];
  28502. const color1 = new Color( 0, 0, 1 );
  28503. const color2 = new Color( 0, 1, 0 );
  28504. for ( let i = 0; i < bones.length; i ++ ) {
  28505. const bone = bones[ i ];
  28506. if ( bone.parent && bone.parent.isBone ) {
  28507. vertices.push( 0, 0, 0 );
  28508. vertices.push( 0, 0, 0 );
  28509. colors.push( color1.r, color1.g, color1.b );
  28510. colors.push( color2.r, color2.g, color2.b );
  28511. }
  28512. }
  28513. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28514. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28515. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28516. super( geometry, material );
  28517. this.isSkeletonHelper = true;
  28518. this.type = 'SkeletonHelper';
  28519. this.root = object;
  28520. this.bones = bones;
  28521. this.matrix = object.matrixWorld;
  28522. this.matrixAutoUpdate = false;
  28523. }
  28524. updateMatrixWorld( force ) {
  28525. const bones = this.bones;
  28526. const geometry = this.geometry;
  28527. const position = geometry.getAttribute( 'position' );
  28528. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28529. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28530. const bone = bones[ i ];
  28531. if ( bone.parent && bone.parent.isBone ) {
  28532. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28533. _vector$2.setFromMatrixPosition( _boneMatrix );
  28534. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28535. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28536. _vector$2.setFromMatrixPosition( _boneMatrix );
  28537. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28538. j += 2;
  28539. }
  28540. }
  28541. geometry.getAttribute( 'position' ).needsUpdate = true;
  28542. super.updateMatrixWorld( force );
  28543. }
  28544. dispose() {
  28545. this.geometry.dispose();
  28546. this.material.dispose();
  28547. }
  28548. }
  28549. function getBoneList( object ) {
  28550. const boneList = [];
  28551. if ( object.isBone === true ) {
  28552. boneList.push( object );
  28553. }
  28554. for ( let i = 0; i < object.children.length; i ++ ) {
  28555. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28556. }
  28557. return boneList;
  28558. }
  28559. class PointLightHelper extends Mesh {
  28560. constructor( light, sphereSize, color ) {
  28561. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28562. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28563. super( geometry, material );
  28564. this.light = light;
  28565. this.color = color;
  28566. this.type = 'PointLightHelper';
  28567. this.matrix = this.light.matrixWorld;
  28568. this.matrixAutoUpdate = false;
  28569. this.update();
  28570. /*
  28571. // TODO: delete this comment?
  28572. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28573. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28574. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28575. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28576. const d = light.distance;
  28577. if ( d === 0.0 ) {
  28578. this.lightDistance.visible = false;
  28579. } else {
  28580. this.lightDistance.scale.set( d, d, d );
  28581. }
  28582. this.add( this.lightDistance );
  28583. */
  28584. }
  28585. dispose() {
  28586. this.geometry.dispose();
  28587. this.material.dispose();
  28588. }
  28589. update() {
  28590. this.light.updateWorldMatrix( true, false );
  28591. if ( this.color !== undefined ) {
  28592. this.material.color.set( this.color );
  28593. } else {
  28594. this.material.color.copy( this.light.color );
  28595. }
  28596. /*
  28597. const d = this.light.distance;
  28598. if ( d === 0.0 ) {
  28599. this.lightDistance.visible = false;
  28600. } else {
  28601. this.lightDistance.visible = true;
  28602. this.lightDistance.scale.set( d, d, d );
  28603. }
  28604. */
  28605. }
  28606. }
  28607. const _vector$1 = /*@__PURE__*/ new Vector3();
  28608. const _color1 = /*@__PURE__*/ new Color();
  28609. const _color2 = /*@__PURE__*/ new Color();
  28610. class HemisphereLightHelper extends Object3D {
  28611. constructor( light, size, color ) {
  28612. super();
  28613. this.light = light;
  28614. this.matrix = light.matrixWorld;
  28615. this.matrixAutoUpdate = false;
  28616. this.color = color;
  28617. this.type = 'HemisphereLightHelper';
  28618. const geometry = new OctahedronGeometry( size );
  28619. geometry.rotateY( Math.PI * 0.5 );
  28620. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28621. if ( this.color === undefined ) this.material.vertexColors = true;
  28622. const position = geometry.getAttribute( 'position' );
  28623. const colors = new Float32Array( position.count * 3 );
  28624. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28625. this.add( new Mesh( geometry, this.material ) );
  28626. this.update();
  28627. }
  28628. dispose() {
  28629. this.children[ 0 ].geometry.dispose();
  28630. this.children[ 0 ].material.dispose();
  28631. }
  28632. update() {
  28633. const mesh = this.children[ 0 ];
  28634. if ( this.color !== undefined ) {
  28635. this.material.color.set( this.color );
  28636. } else {
  28637. const colors = mesh.geometry.getAttribute( 'color' );
  28638. _color1.copy( this.light.color );
  28639. _color2.copy( this.light.groundColor );
  28640. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28641. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28642. colors.setXYZ( i, color.r, color.g, color.b );
  28643. }
  28644. colors.needsUpdate = true;
  28645. }
  28646. this.light.updateWorldMatrix( true, false );
  28647. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28648. }
  28649. }
  28650. class GridHelper extends LineSegments {
  28651. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28652. color1 = new Color( color1 );
  28653. color2 = new Color( color2 );
  28654. const center = divisions / 2;
  28655. const step = size / divisions;
  28656. const halfSize = size / 2;
  28657. const vertices = [], colors = [];
  28658. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28659. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28660. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28661. const color = i === center ? color1 : color2;
  28662. color.toArray( colors, j ); j += 3;
  28663. color.toArray( colors, j ); j += 3;
  28664. color.toArray( colors, j ); j += 3;
  28665. color.toArray( colors, j ); j += 3;
  28666. }
  28667. const geometry = new BufferGeometry();
  28668. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28669. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28670. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28671. super( geometry, material );
  28672. this.type = 'GridHelper';
  28673. }
  28674. dispose() {
  28675. this.geometry.dispose();
  28676. this.material.dispose();
  28677. }
  28678. }
  28679. class PolarGridHelper extends LineSegments {
  28680. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28681. color1 = new Color( color1 );
  28682. color2 = new Color( color2 );
  28683. const vertices = [];
  28684. const colors = [];
  28685. // create the sectors
  28686. if ( sectors > 1 ) {
  28687. for ( let i = 0; i < sectors; i ++ ) {
  28688. const v = ( i / sectors ) * ( Math.PI * 2 );
  28689. const x = Math.sin( v ) * radius;
  28690. const z = Math.cos( v ) * radius;
  28691. vertices.push( 0, 0, 0 );
  28692. vertices.push( x, 0, z );
  28693. const color = ( i & 1 ) ? color1 : color2;
  28694. colors.push( color.r, color.g, color.b );
  28695. colors.push( color.r, color.g, color.b );
  28696. }
  28697. }
  28698. // create the rings
  28699. for ( let i = 0; i < rings; i ++ ) {
  28700. const color = ( i & 1 ) ? color1 : color2;
  28701. const r = radius - ( radius / rings * i );
  28702. for ( let j = 0; j < divisions; j ++ ) {
  28703. // first vertex
  28704. let v = ( j / divisions ) * ( Math.PI * 2 );
  28705. let x = Math.sin( v ) * r;
  28706. let z = Math.cos( v ) * r;
  28707. vertices.push( x, 0, z );
  28708. colors.push( color.r, color.g, color.b );
  28709. // second vertex
  28710. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28711. x = Math.sin( v ) * r;
  28712. z = Math.cos( v ) * r;
  28713. vertices.push( x, 0, z );
  28714. colors.push( color.r, color.g, color.b );
  28715. }
  28716. }
  28717. const geometry = new BufferGeometry();
  28718. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28719. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28720. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28721. super( geometry, material );
  28722. this.type = 'PolarGridHelper';
  28723. }
  28724. dispose() {
  28725. this.geometry.dispose();
  28726. this.material.dispose();
  28727. }
  28728. }
  28729. const _v1 = /*@__PURE__*/ new Vector3();
  28730. const _v2 = /*@__PURE__*/ new Vector3();
  28731. const _v3 = /*@__PURE__*/ new Vector3();
  28732. class DirectionalLightHelper extends Object3D {
  28733. constructor( light, size, color ) {
  28734. super();
  28735. this.light = light;
  28736. this.matrix = light.matrixWorld;
  28737. this.matrixAutoUpdate = false;
  28738. this.color = color;
  28739. this.type = 'DirectionalLightHelper';
  28740. if ( size === undefined ) size = 1;
  28741. let geometry = new BufferGeometry();
  28742. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28743. - size, size, 0,
  28744. size, size, 0,
  28745. size, - size, 0,
  28746. - size, - size, 0,
  28747. - size, size, 0
  28748. ], 3 ) );
  28749. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28750. this.lightPlane = new Line( geometry, material );
  28751. this.add( this.lightPlane );
  28752. geometry = new BufferGeometry();
  28753. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28754. this.targetLine = new Line( geometry, material );
  28755. this.add( this.targetLine );
  28756. this.update();
  28757. }
  28758. dispose() {
  28759. this.lightPlane.geometry.dispose();
  28760. this.lightPlane.material.dispose();
  28761. this.targetLine.geometry.dispose();
  28762. this.targetLine.material.dispose();
  28763. }
  28764. update() {
  28765. this.light.updateWorldMatrix( true, false );
  28766. this.light.target.updateWorldMatrix( true, false );
  28767. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28768. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28769. _v3.subVectors( _v2, _v1 );
  28770. this.lightPlane.lookAt( _v2 );
  28771. if ( this.color !== undefined ) {
  28772. this.lightPlane.material.color.set( this.color );
  28773. this.targetLine.material.color.set( this.color );
  28774. } else {
  28775. this.lightPlane.material.color.copy( this.light.color );
  28776. this.targetLine.material.color.copy( this.light.color );
  28777. }
  28778. this.targetLine.lookAt( _v2 );
  28779. this.targetLine.scale.z = _v3.length();
  28780. }
  28781. }
  28782. const _vector = /*@__PURE__*/ new Vector3();
  28783. const _camera = /*@__PURE__*/ new Camera();
  28784. /**
  28785. * - shows frustum, line of sight and up of the camera
  28786. * - suitable for fast updates
  28787. * - based on frustum visualization in lightgl.js shadowmap example
  28788. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28789. */
  28790. class CameraHelper extends LineSegments {
  28791. constructor( camera ) {
  28792. const geometry = new BufferGeometry();
  28793. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28794. const vertices = [];
  28795. const colors = [];
  28796. const pointMap = {};
  28797. // near
  28798. addLine( 'n1', 'n2' );
  28799. addLine( 'n2', 'n4' );
  28800. addLine( 'n4', 'n3' );
  28801. addLine( 'n3', 'n1' );
  28802. // far
  28803. addLine( 'f1', 'f2' );
  28804. addLine( 'f2', 'f4' );
  28805. addLine( 'f4', 'f3' );
  28806. addLine( 'f3', 'f1' );
  28807. // sides
  28808. addLine( 'n1', 'f1' );
  28809. addLine( 'n2', 'f2' );
  28810. addLine( 'n3', 'f3' );
  28811. addLine( 'n4', 'f4' );
  28812. // cone
  28813. addLine( 'p', 'n1' );
  28814. addLine( 'p', 'n2' );
  28815. addLine( 'p', 'n3' );
  28816. addLine( 'p', 'n4' );
  28817. // up
  28818. addLine( 'u1', 'u2' );
  28819. addLine( 'u2', 'u3' );
  28820. addLine( 'u3', 'u1' );
  28821. // target
  28822. addLine( 'c', 't' );
  28823. addLine( 'p', 'c' );
  28824. // cross
  28825. addLine( 'cn1', 'cn2' );
  28826. addLine( 'cn3', 'cn4' );
  28827. addLine( 'cf1', 'cf2' );
  28828. addLine( 'cf3', 'cf4' );
  28829. function addLine( a, b ) {
  28830. addPoint( a );
  28831. addPoint( b );
  28832. }
  28833. function addPoint( id ) {
  28834. vertices.push( 0, 0, 0 );
  28835. colors.push( 0, 0, 0 );
  28836. if ( pointMap[ id ] === undefined ) {
  28837. pointMap[ id ] = [];
  28838. }
  28839. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28840. }
  28841. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28842. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28843. super( geometry, material );
  28844. this.type = 'CameraHelper';
  28845. this.camera = camera;
  28846. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28847. this.matrix = camera.matrixWorld;
  28848. this.matrixAutoUpdate = false;
  28849. this.pointMap = pointMap;
  28850. this.update();
  28851. // colors
  28852. const colorFrustum = new Color( 0xffaa00 );
  28853. const colorCone = new Color( 0xff0000 );
  28854. const colorUp = new Color( 0x00aaff );
  28855. const colorTarget = new Color( 0xffffff );
  28856. const colorCross = new Color( 0x333333 );
  28857. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28858. }
  28859. setColors( frustum, cone, up, target, cross ) {
  28860. const geometry = this.geometry;
  28861. const colorAttribute = geometry.getAttribute( 'color' );
  28862. // near
  28863. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  28864. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  28865. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  28866. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  28867. // far
  28868. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  28869. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  28870. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  28871. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  28872. // sides
  28873. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  28874. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  28875. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  28876. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  28877. // cone
  28878. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  28879. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  28880. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  28881. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  28882. // up
  28883. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  28884. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  28885. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  28886. // target
  28887. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  28888. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  28889. // cross
  28890. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  28891. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  28892. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  28893. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  28894. colorAttribute.needsUpdate = true;
  28895. }
  28896. update() {
  28897. const geometry = this.geometry;
  28898. const pointMap = this.pointMap;
  28899. const w = 1, h = 1;
  28900. // we need just camera projection matrix inverse
  28901. // world matrix must be identity
  28902. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28903. // center / target
  28904. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28905. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28906. // near
  28907. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28908. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28909. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28910. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28911. // far
  28912. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28913. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28914. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28915. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28916. // up
  28917. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28918. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28919. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28920. // cross
  28921. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28922. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28923. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28924. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28925. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28926. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28927. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28928. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28929. geometry.getAttribute( 'position' ).needsUpdate = true;
  28930. }
  28931. dispose() {
  28932. this.geometry.dispose();
  28933. this.material.dispose();
  28934. }
  28935. }
  28936. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28937. _vector.set( x, y, z ).unproject( camera );
  28938. const points = pointMap[ point ];
  28939. if ( points !== undefined ) {
  28940. const position = geometry.getAttribute( 'position' );
  28941. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28942. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28943. }
  28944. }
  28945. }
  28946. const _box = /*@__PURE__*/ new Box3();
  28947. class BoxHelper extends LineSegments {
  28948. constructor( object, color = 0xffff00 ) {
  28949. 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 ] );
  28950. const positions = new Float32Array( 8 * 3 );
  28951. const geometry = new BufferGeometry();
  28952. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28953. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28954. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28955. this.object = object;
  28956. this.type = 'BoxHelper';
  28957. this.matrixAutoUpdate = false;
  28958. this.update();
  28959. }
  28960. update( object ) {
  28961. if ( object !== undefined ) {
  28962. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28963. }
  28964. if ( this.object !== undefined ) {
  28965. _box.setFromObject( this.object );
  28966. }
  28967. if ( _box.isEmpty() ) return;
  28968. const min = _box.min;
  28969. const max = _box.max;
  28970. /*
  28971. 5____4
  28972. 1/___0/|
  28973. | 6__|_7
  28974. 2/___3/
  28975. 0: max.x, max.y, max.z
  28976. 1: min.x, max.y, max.z
  28977. 2: min.x, min.y, max.z
  28978. 3: max.x, min.y, max.z
  28979. 4: max.x, max.y, min.z
  28980. 5: min.x, max.y, min.z
  28981. 6: min.x, min.y, min.z
  28982. 7: max.x, min.y, min.z
  28983. */
  28984. const position = this.geometry.attributes.position;
  28985. const array = position.array;
  28986. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28987. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28988. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28989. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28990. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28991. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28992. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28993. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28994. position.needsUpdate = true;
  28995. this.geometry.computeBoundingSphere();
  28996. }
  28997. setFromObject( object ) {
  28998. this.object = object;
  28999. this.update();
  29000. return this;
  29001. }
  29002. copy( source, recursive ) {
  29003. super.copy( source, recursive );
  29004. this.object = source.object;
  29005. return this;
  29006. }
  29007. dispose() {
  29008. this.geometry.dispose();
  29009. this.material.dispose();
  29010. }
  29011. }
  29012. class Box3Helper extends LineSegments {
  29013. constructor( box, color = 0xffff00 ) {
  29014. 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 ] );
  29015. 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 ];
  29016. const geometry = new BufferGeometry();
  29017. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29018. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29019. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29020. this.box = box;
  29021. this.type = 'Box3Helper';
  29022. this.geometry.computeBoundingSphere();
  29023. }
  29024. updateMatrixWorld( force ) {
  29025. const box = this.box;
  29026. if ( box.isEmpty() ) return;
  29027. box.getCenter( this.position );
  29028. box.getSize( this.scale );
  29029. this.scale.multiplyScalar( 0.5 );
  29030. super.updateMatrixWorld( force );
  29031. }
  29032. dispose() {
  29033. this.geometry.dispose();
  29034. this.material.dispose();
  29035. }
  29036. }
  29037. class PlaneHelper extends Line {
  29038. constructor( plane, size = 1, hex = 0xffff00 ) {
  29039. const color = hex;
  29040. 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 ];
  29041. const geometry = new BufferGeometry();
  29042. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29043. geometry.computeBoundingSphere();
  29044. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29045. this.type = 'PlaneHelper';
  29046. this.plane = plane;
  29047. this.size = size;
  29048. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29049. const geometry2 = new BufferGeometry();
  29050. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29051. geometry2.computeBoundingSphere();
  29052. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29053. }
  29054. updateMatrixWorld( force ) {
  29055. this.position.set( 0, 0, 0 );
  29056. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29057. this.lookAt( this.plane.normal );
  29058. this.translateZ( - this.plane.constant );
  29059. super.updateMatrixWorld( force );
  29060. }
  29061. dispose() {
  29062. this.geometry.dispose();
  29063. this.material.dispose();
  29064. this.children[ 0 ].geometry.dispose();
  29065. this.children[ 0 ].material.dispose();
  29066. }
  29067. }
  29068. const _axis = /*@__PURE__*/ new Vector3();
  29069. let _lineGeometry, _coneGeometry;
  29070. class ArrowHelper extends Object3D {
  29071. // dir is assumed to be normalized
  29072. 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 ) {
  29073. super();
  29074. this.type = 'ArrowHelper';
  29075. if ( _lineGeometry === undefined ) {
  29076. _lineGeometry = new BufferGeometry();
  29077. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29078. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29079. _coneGeometry.translate( 0, - 0.5, 0 );
  29080. }
  29081. this.position.copy( origin );
  29082. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29083. this.line.matrixAutoUpdate = false;
  29084. this.add( this.line );
  29085. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29086. this.cone.matrixAutoUpdate = false;
  29087. this.add( this.cone );
  29088. this.setDirection( dir );
  29089. this.setLength( length, headLength, headWidth );
  29090. }
  29091. setDirection( dir ) {
  29092. // dir is assumed to be normalized
  29093. if ( dir.y > 0.99999 ) {
  29094. this.quaternion.set( 0, 0, 0, 1 );
  29095. } else if ( dir.y < - 0.99999 ) {
  29096. this.quaternion.set( 1, 0, 0, 0 );
  29097. } else {
  29098. _axis.set( dir.z, 0, - dir.x ).normalize();
  29099. const radians = Math.acos( dir.y );
  29100. this.quaternion.setFromAxisAngle( _axis, radians );
  29101. }
  29102. }
  29103. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29104. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29105. this.line.updateMatrix();
  29106. this.cone.scale.set( headWidth, headLength, headWidth );
  29107. this.cone.position.y = length;
  29108. this.cone.updateMatrix();
  29109. }
  29110. setColor( color ) {
  29111. this.line.material.color.set( color );
  29112. this.cone.material.color.set( color );
  29113. }
  29114. copy( source ) {
  29115. super.copy( source, false );
  29116. this.line.copy( source.line );
  29117. this.cone.copy( source.cone );
  29118. return this;
  29119. }
  29120. dispose() {
  29121. this.line.geometry.dispose();
  29122. this.line.material.dispose();
  29123. this.cone.geometry.dispose();
  29124. this.cone.material.dispose();
  29125. }
  29126. }
  29127. class AxesHelper extends LineSegments {
  29128. constructor( size = 1 ) {
  29129. const vertices = [
  29130. 0, 0, 0, size, 0, 0,
  29131. 0, 0, 0, 0, size, 0,
  29132. 0, 0, 0, 0, 0, size
  29133. ];
  29134. const colors = [
  29135. 1, 0, 0, 1, 0.6, 0,
  29136. 0, 1, 0, 0.6, 1, 0,
  29137. 0, 0, 1, 0, 0.6, 1
  29138. ];
  29139. const geometry = new BufferGeometry();
  29140. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29141. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29142. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29143. super( geometry, material );
  29144. this.type = 'AxesHelper';
  29145. }
  29146. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29147. const color = new Color();
  29148. const array = this.geometry.attributes.color.array;
  29149. color.set( xAxisColor );
  29150. color.toArray( array, 0 );
  29151. color.toArray( array, 3 );
  29152. color.set( yAxisColor );
  29153. color.toArray( array, 6 );
  29154. color.toArray( array, 9 );
  29155. color.set( zAxisColor );
  29156. color.toArray( array, 12 );
  29157. color.toArray( array, 15 );
  29158. this.geometry.attributes.color.needsUpdate = true;
  29159. return this;
  29160. }
  29161. dispose() {
  29162. this.geometry.dispose();
  29163. this.material.dispose();
  29164. }
  29165. }
  29166. class ShapePath {
  29167. constructor() {
  29168. this.type = 'ShapePath';
  29169. this.color = new Color();
  29170. this.subPaths = [];
  29171. this.currentPath = null;
  29172. }
  29173. moveTo( x, y ) {
  29174. this.currentPath = new Path();
  29175. this.subPaths.push( this.currentPath );
  29176. this.currentPath.moveTo( x, y );
  29177. return this;
  29178. }
  29179. lineTo( x, y ) {
  29180. this.currentPath.lineTo( x, y );
  29181. return this;
  29182. }
  29183. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29184. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29185. return this;
  29186. }
  29187. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29188. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29189. return this;
  29190. }
  29191. splineThru( pts ) {
  29192. this.currentPath.splineThru( pts );
  29193. return this;
  29194. }
  29195. toShapes( isCCW ) {
  29196. function toShapesNoHoles( inSubpaths ) {
  29197. const shapes = [];
  29198. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29199. const tmpPath = inSubpaths[ i ];
  29200. const tmpShape = new Shape();
  29201. tmpShape.curves = tmpPath.curves;
  29202. shapes.push( tmpShape );
  29203. }
  29204. return shapes;
  29205. }
  29206. function isPointInsidePolygon( inPt, inPolygon ) {
  29207. const polyLen = inPolygon.length;
  29208. // inPt on polygon contour => immediate success or
  29209. // toggling of inside/outside at every single! intersection point of an edge
  29210. // with the horizontal line through inPt, left of inPt
  29211. // not counting lowerY endpoints of edges and whole edges on that line
  29212. let inside = false;
  29213. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29214. let edgeLowPt = inPolygon[ p ];
  29215. let edgeHighPt = inPolygon[ q ];
  29216. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29217. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29218. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29219. // not parallel
  29220. if ( edgeDy < 0 ) {
  29221. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29222. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29223. }
  29224. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29225. if ( inPt.y === edgeLowPt.y ) {
  29226. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29227. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29228. } else {
  29229. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29230. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29231. if ( perpEdge < 0 ) continue;
  29232. inside = ! inside; // true intersection left of inPt
  29233. }
  29234. } else {
  29235. // parallel or collinear
  29236. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29237. // edge lies on the same horizontal line as inPt
  29238. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29239. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29240. // continue;
  29241. }
  29242. }
  29243. return inside;
  29244. }
  29245. const isClockWise = ShapeUtils.isClockWise;
  29246. const subPaths = this.subPaths;
  29247. if ( subPaths.length === 0 ) return [];
  29248. let solid, tmpPath, tmpShape;
  29249. const shapes = [];
  29250. if ( subPaths.length === 1 ) {
  29251. tmpPath = subPaths[ 0 ];
  29252. tmpShape = new Shape();
  29253. tmpShape.curves = tmpPath.curves;
  29254. shapes.push( tmpShape );
  29255. return shapes;
  29256. }
  29257. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29258. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29259. // console.log("Holes first", holesFirst);
  29260. const betterShapeHoles = [];
  29261. const newShapes = [];
  29262. let newShapeHoles = [];
  29263. let mainIdx = 0;
  29264. let tmpPoints;
  29265. newShapes[ mainIdx ] = undefined;
  29266. newShapeHoles[ mainIdx ] = [];
  29267. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29268. tmpPath = subPaths[ i ];
  29269. tmpPoints = tmpPath.getPoints();
  29270. solid = isClockWise( tmpPoints );
  29271. solid = isCCW ? ! solid : solid;
  29272. if ( solid ) {
  29273. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29274. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29275. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29276. if ( holesFirst ) mainIdx ++;
  29277. newShapeHoles[ mainIdx ] = [];
  29278. //console.log('cw', i);
  29279. } else {
  29280. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29281. //console.log('ccw', i);
  29282. }
  29283. }
  29284. // only Holes? -> probably all Shapes with wrong orientation
  29285. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29286. if ( newShapes.length > 1 ) {
  29287. let ambiguous = false;
  29288. let toChange = 0;
  29289. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29290. betterShapeHoles[ sIdx ] = [];
  29291. }
  29292. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29293. const sho = newShapeHoles[ sIdx ];
  29294. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29295. const ho = sho[ hIdx ];
  29296. let hole_unassigned = true;
  29297. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29298. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29299. if ( sIdx !== s2Idx ) toChange ++;
  29300. if ( hole_unassigned ) {
  29301. hole_unassigned = false;
  29302. betterShapeHoles[ s2Idx ].push( ho );
  29303. } else {
  29304. ambiguous = true;
  29305. }
  29306. }
  29307. }
  29308. if ( hole_unassigned ) {
  29309. betterShapeHoles[ sIdx ].push( ho );
  29310. }
  29311. }
  29312. }
  29313. if ( toChange > 0 && ambiguous === false ) {
  29314. newShapeHoles = betterShapeHoles;
  29315. }
  29316. }
  29317. let tmpHoles;
  29318. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29319. tmpShape = newShapes[ i ].s;
  29320. shapes.push( tmpShape );
  29321. tmpHoles = newShapeHoles[ i ];
  29322. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29323. tmpShape.holes.push( tmpHoles[ j ].h );
  29324. }
  29325. }
  29326. //console.log("shape", shapes);
  29327. return shapes;
  29328. }
  29329. }
  29330. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29331. const _tables = /*@__PURE__*/ _generateTables();
  29332. function _generateTables() {
  29333. // float32 to float16 helpers
  29334. const buffer = new ArrayBuffer( 4 );
  29335. const floatView = new Float32Array( buffer );
  29336. const uint32View = new Uint32Array( buffer );
  29337. const baseTable = new Uint32Array( 512 );
  29338. const shiftTable = new Uint32Array( 512 );
  29339. for ( let i = 0; i < 256; ++ i ) {
  29340. const e = i - 127;
  29341. // very small number (0, -0)
  29342. if ( e < - 27 ) {
  29343. baseTable[ i ] = 0x0000;
  29344. baseTable[ i | 0x100 ] = 0x8000;
  29345. shiftTable[ i ] = 24;
  29346. shiftTable[ i | 0x100 ] = 24;
  29347. // small number (denorm)
  29348. } else if ( e < - 14 ) {
  29349. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29350. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29351. shiftTable[ i ] = - e - 1;
  29352. shiftTable[ i | 0x100 ] = - e - 1;
  29353. // normal number
  29354. } else if ( e <= 15 ) {
  29355. baseTable[ i ] = ( e + 15 ) << 10;
  29356. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29357. shiftTable[ i ] = 13;
  29358. shiftTable[ i | 0x100 ] = 13;
  29359. // large number (Infinity, -Infinity)
  29360. } else if ( e < 128 ) {
  29361. baseTable[ i ] = 0x7c00;
  29362. baseTable[ i | 0x100 ] = 0xfc00;
  29363. shiftTable[ i ] = 24;
  29364. shiftTable[ i | 0x100 ] = 24;
  29365. // stay (NaN, Infinity, -Infinity)
  29366. } else {
  29367. baseTable[ i ] = 0x7c00;
  29368. baseTable[ i | 0x100 ] = 0xfc00;
  29369. shiftTable[ i ] = 13;
  29370. shiftTable[ i | 0x100 ] = 13;
  29371. }
  29372. }
  29373. // float16 to float32 helpers
  29374. const mantissaTable = new Uint32Array( 2048 );
  29375. const exponentTable = new Uint32Array( 64 );
  29376. const offsetTable = new Uint32Array( 64 );
  29377. for ( let i = 1; i < 1024; ++ i ) {
  29378. let m = i << 13; // zero pad mantissa bits
  29379. let e = 0; // zero exponent
  29380. // normalized
  29381. while ( ( m & 0x00800000 ) === 0 ) {
  29382. m <<= 1;
  29383. e -= 0x00800000; // decrement exponent
  29384. }
  29385. m &= ~ 0x00800000; // clear leading 1 bit
  29386. e += 0x38800000; // adjust bias
  29387. mantissaTable[ i ] = m | e;
  29388. }
  29389. for ( let i = 1024; i < 2048; ++ i ) {
  29390. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29391. }
  29392. for ( let i = 1; i < 31; ++ i ) {
  29393. exponentTable[ i ] = i << 23;
  29394. }
  29395. exponentTable[ 31 ] = 0x47800000;
  29396. exponentTable[ 32 ] = 0x80000000;
  29397. for ( let i = 33; i < 63; ++ i ) {
  29398. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29399. }
  29400. exponentTable[ 63 ] = 0xc7800000;
  29401. for ( let i = 1; i < 64; ++ i ) {
  29402. if ( i !== 32 ) {
  29403. offsetTable[ i ] = 1024;
  29404. }
  29405. }
  29406. return {
  29407. floatView: floatView,
  29408. uint32View: uint32View,
  29409. baseTable: baseTable,
  29410. shiftTable: shiftTable,
  29411. mantissaTable: mantissaTable,
  29412. exponentTable: exponentTable,
  29413. offsetTable: offsetTable
  29414. };
  29415. }
  29416. // float32 to float16
  29417. function toHalfFloat( val ) {
  29418. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29419. val = clamp( val, - 65504, 65504 );
  29420. _tables.floatView[ 0 ] = val;
  29421. const f = _tables.uint32View[ 0 ];
  29422. const e = ( f >> 23 ) & 0x1ff;
  29423. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29424. }
  29425. // float16 to float32
  29426. function fromHalfFloat( val ) {
  29427. const m = val >> 10;
  29428. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29429. return _tables.floatView[ 0 ];
  29430. }
  29431. var DataUtils = /*#__PURE__*/Object.freeze({
  29432. __proto__: null,
  29433. fromHalfFloat: fromHalfFloat,
  29434. toHalfFloat: toHalfFloat
  29435. });
  29436. // r144
  29437. class BoxBufferGeometry extends BoxGeometry {
  29438. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29439. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29440. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29441. }
  29442. }
  29443. // r144
  29444. class CapsuleBufferGeometry extends CapsuleGeometry {
  29445. constructor( radius, length, capSegments, radialSegments ) {
  29446. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29447. super( radius, length, capSegments, radialSegments );
  29448. }
  29449. }
  29450. // r144
  29451. class CircleBufferGeometry extends CircleGeometry {
  29452. constructor( radius, segments, thetaStart, thetaLength ) {
  29453. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29454. super( radius, segments, thetaStart, thetaLength );
  29455. }
  29456. }
  29457. // r144
  29458. class ConeBufferGeometry extends ConeGeometry {
  29459. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29460. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29461. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29462. }
  29463. }
  29464. // r144
  29465. class CylinderBufferGeometry extends CylinderGeometry {
  29466. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29467. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29468. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29469. }
  29470. }
  29471. // r144
  29472. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29473. constructor( radius, detail ) {
  29474. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29475. super( radius, detail );
  29476. }
  29477. }
  29478. // r144
  29479. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29480. constructor( shapes, options ) {
  29481. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29482. super( shapes, options );
  29483. }
  29484. }
  29485. // r144
  29486. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29487. constructor( radius, detail ) {
  29488. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29489. super( radius, detail );
  29490. }
  29491. }
  29492. // r144
  29493. class LatheBufferGeometry extends LatheGeometry {
  29494. constructor( points, segments, phiStart, phiLength ) {
  29495. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29496. super( points, segments, phiStart, phiLength );
  29497. }
  29498. }
  29499. // r144
  29500. class OctahedronBufferGeometry extends OctahedronGeometry {
  29501. constructor( radius, detail ) {
  29502. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29503. super( radius, detail );
  29504. }
  29505. }
  29506. // r144
  29507. class PlaneBufferGeometry extends PlaneGeometry {
  29508. constructor( width, height, widthSegments, heightSegments ) {
  29509. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29510. super( width, height, widthSegments, heightSegments );
  29511. }
  29512. }
  29513. // r144
  29514. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29515. constructor( vertices, indices, radius, detail ) {
  29516. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29517. super( vertices, indices, radius, detail );
  29518. }
  29519. }
  29520. // r144
  29521. class RingBufferGeometry extends RingGeometry {
  29522. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29523. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29524. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29525. }
  29526. }
  29527. // r144
  29528. class ShapeBufferGeometry extends ShapeGeometry {
  29529. constructor( shapes, curveSegments ) {
  29530. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29531. super( shapes, curveSegments );
  29532. }
  29533. }
  29534. // r144
  29535. class SphereBufferGeometry extends SphereGeometry {
  29536. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29537. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29538. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29539. }
  29540. }
  29541. // r144
  29542. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29543. constructor( radius, detail ) {
  29544. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29545. super( radius, detail );
  29546. }
  29547. }
  29548. // r144
  29549. class TorusBufferGeometry extends TorusGeometry {
  29550. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29551. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29552. super( radius, tube, radialSegments, tubularSegments, arc );
  29553. }
  29554. }
  29555. // r144
  29556. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29557. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29558. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29559. super( radius, tube, tubularSegments, radialSegments, p, q );
  29560. }
  29561. }
  29562. // r144
  29563. class TubeBufferGeometry extends TubeGeometry {
  29564. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29565. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29566. super( path, tubularSegments, radius, radialSegments, closed );
  29567. }
  29568. }
  29569. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29570. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29571. revision: REVISION,
  29572. } } ) );
  29573. }
  29574. if ( typeof window !== 'undefined' ) {
  29575. if ( window.__THREE__ ) {
  29576. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29577. } else {
  29578. window.__THREE__ = REVISION;
  29579. }
  29580. }
  29581. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29582. exports.AddEquation = AddEquation;
  29583. exports.AddOperation = AddOperation;
  29584. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29585. exports.AdditiveBlending = AdditiveBlending;
  29586. exports.AlphaFormat = AlphaFormat;
  29587. exports.AlwaysDepth = AlwaysDepth;
  29588. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29589. exports.AmbientLight = AmbientLight;
  29590. exports.AmbientLightProbe = AmbientLightProbe;
  29591. exports.AnimationClip = AnimationClip;
  29592. exports.AnimationLoader = AnimationLoader;
  29593. exports.AnimationMixer = AnimationMixer;
  29594. exports.AnimationObjectGroup = AnimationObjectGroup;
  29595. exports.AnimationUtils = AnimationUtils;
  29596. exports.ArcCurve = ArcCurve;
  29597. exports.ArrayCamera = ArrayCamera;
  29598. exports.ArrowHelper = ArrowHelper;
  29599. exports.Audio = Audio;
  29600. exports.AudioAnalyser = AudioAnalyser;
  29601. exports.AudioContext = AudioContext;
  29602. exports.AudioListener = AudioListener;
  29603. exports.AudioLoader = AudioLoader;
  29604. exports.AxesHelper = AxesHelper;
  29605. exports.BackSide = BackSide;
  29606. exports.BasicDepthPacking = BasicDepthPacking;
  29607. exports.BasicShadowMap = BasicShadowMap;
  29608. exports.Bone = Bone;
  29609. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29610. exports.Box2 = Box2;
  29611. exports.Box3 = Box3;
  29612. exports.Box3Helper = Box3Helper;
  29613. exports.BoxBufferGeometry = BoxBufferGeometry;
  29614. exports.BoxGeometry = BoxGeometry;
  29615. exports.BoxHelper = BoxHelper;
  29616. exports.BufferAttribute = BufferAttribute;
  29617. exports.BufferGeometry = BufferGeometry;
  29618. exports.BufferGeometryLoader = BufferGeometryLoader;
  29619. exports.ByteType = ByteType;
  29620. exports.Cache = Cache;
  29621. exports.Camera = Camera;
  29622. exports.CameraHelper = CameraHelper;
  29623. exports.CanvasTexture = CanvasTexture;
  29624. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  29625. exports.CapsuleGeometry = CapsuleGeometry;
  29626. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29627. exports.CineonToneMapping = CineonToneMapping;
  29628. exports.CircleBufferGeometry = CircleBufferGeometry;
  29629. exports.CircleGeometry = CircleGeometry;
  29630. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29631. exports.Clock = Clock;
  29632. exports.Color = Color;
  29633. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29634. exports.ColorManagement = ColorManagement;
  29635. exports.CompressedArrayTexture = CompressedArrayTexture;
  29636. exports.CompressedTexture = CompressedTexture;
  29637. exports.CompressedTextureLoader = CompressedTextureLoader;
  29638. exports.ConeBufferGeometry = ConeBufferGeometry;
  29639. exports.ConeGeometry = ConeGeometry;
  29640. exports.CubeCamera = CubeCamera;
  29641. exports.CubeReflectionMapping = CubeReflectionMapping;
  29642. exports.CubeRefractionMapping = CubeRefractionMapping;
  29643. exports.CubeTexture = CubeTexture;
  29644. exports.CubeTextureLoader = CubeTextureLoader;
  29645. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29646. exports.CubicBezierCurve = CubicBezierCurve;
  29647. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29648. exports.CubicInterpolant = CubicInterpolant;
  29649. exports.CullFaceBack = CullFaceBack;
  29650. exports.CullFaceFront = CullFaceFront;
  29651. exports.CullFaceFrontBack = CullFaceFrontBack;
  29652. exports.CullFaceNone = CullFaceNone;
  29653. exports.Curve = Curve;
  29654. exports.CurvePath = CurvePath;
  29655. exports.CustomBlending = CustomBlending;
  29656. exports.CustomToneMapping = CustomToneMapping;
  29657. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29658. exports.CylinderGeometry = CylinderGeometry;
  29659. exports.Cylindrical = Cylindrical;
  29660. exports.Data3DTexture = Data3DTexture;
  29661. exports.DataArrayTexture = DataArrayTexture;
  29662. exports.DataTexture = DataTexture;
  29663. exports.DataTextureLoader = DataTextureLoader;
  29664. exports.DataUtils = DataUtils;
  29665. exports.DecrementStencilOp = DecrementStencilOp;
  29666. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29667. exports.DefaultLoadingManager = DefaultLoadingManager;
  29668. exports.DepthFormat = DepthFormat;
  29669. exports.DepthStencilFormat = DepthStencilFormat;
  29670. exports.DepthTexture = DepthTexture;
  29671. exports.DirectionalLight = DirectionalLight;
  29672. exports.DirectionalLightHelper = DirectionalLightHelper;
  29673. exports.DiscreteInterpolant = DiscreteInterpolant;
  29674. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  29675. exports.DodecahedronGeometry = DodecahedronGeometry;
  29676. exports.DoubleSide = DoubleSide;
  29677. exports.DstAlphaFactor = DstAlphaFactor;
  29678. exports.DstColorFactor = DstColorFactor;
  29679. exports.DynamicCopyUsage = DynamicCopyUsage;
  29680. exports.DynamicDrawUsage = DynamicDrawUsage;
  29681. exports.DynamicReadUsage = DynamicReadUsage;
  29682. exports.EdgesGeometry = EdgesGeometry;
  29683. exports.EllipseCurve = EllipseCurve;
  29684. exports.EqualDepth = EqualDepth;
  29685. exports.EqualStencilFunc = EqualStencilFunc;
  29686. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29687. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29688. exports.Euler = Euler;
  29689. exports.EventDispatcher = EventDispatcher;
  29690. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  29691. exports.ExtrudeGeometry = ExtrudeGeometry;
  29692. exports.FileLoader = FileLoader;
  29693. exports.Float16BufferAttribute = Float16BufferAttribute;
  29694. exports.Float32BufferAttribute = Float32BufferAttribute;
  29695. exports.Float64BufferAttribute = Float64BufferAttribute;
  29696. exports.FloatType = FloatType;
  29697. exports.Fog = Fog;
  29698. exports.FogExp2 = FogExp2;
  29699. exports.FramebufferTexture = FramebufferTexture;
  29700. exports.FrontSide = FrontSide;
  29701. exports.Frustum = Frustum;
  29702. exports.GLBufferAttribute = GLBufferAttribute;
  29703. exports.GLSL1 = GLSL1;
  29704. exports.GLSL3 = GLSL3;
  29705. exports.GreaterDepth = GreaterDepth;
  29706. exports.GreaterEqualDepth = GreaterEqualDepth;
  29707. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29708. exports.GreaterStencilFunc = GreaterStencilFunc;
  29709. exports.GridHelper = GridHelper;
  29710. exports.Group = Group;
  29711. exports.HalfFloatType = HalfFloatType;
  29712. exports.HemisphereLight = HemisphereLight;
  29713. exports.HemisphereLightHelper = HemisphereLightHelper;
  29714. exports.HemisphereLightProbe = HemisphereLightProbe;
  29715. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  29716. exports.IcosahedronGeometry = IcosahedronGeometry;
  29717. exports.ImageBitmapLoader = ImageBitmapLoader;
  29718. exports.ImageLoader = ImageLoader;
  29719. exports.ImageUtils = ImageUtils;
  29720. exports.IncrementStencilOp = IncrementStencilOp;
  29721. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29722. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29723. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29724. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29725. exports.InstancedMesh = InstancedMesh;
  29726. exports.Int16BufferAttribute = Int16BufferAttribute;
  29727. exports.Int32BufferAttribute = Int32BufferAttribute;
  29728. exports.Int8BufferAttribute = Int8BufferAttribute;
  29729. exports.IntType = IntType;
  29730. exports.InterleavedBuffer = InterleavedBuffer;
  29731. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29732. exports.Interpolant = Interpolant;
  29733. exports.InterpolateDiscrete = InterpolateDiscrete;
  29734. exports.InterpolateLinear = InterpolateLinear;
  29735. exports.InterpolateSmooth = InterpolateSmooth;
  29736. exports.InvertStencilOp = InvertStencilOp;
  29737. exports.KeepStencilOp = KeepStencilOp;
  29738. exports.KeyframeTrack = KeyframeTrack;
  29739. exports.LOD = LOD;
  29740. exports.LatheBufferGeometry = LatheBufferGeometry;
  29741. exports.LatheGeometry = LatheGeometry;
  29742. exports.Layers = Layers;
  29743. exports.LessDepth = LessDepth;
  29744. exports.LessEqualDepth = LessEqualDepth;
  29745. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29746. exports.LessStencilFunc = LessStencilFunc;
  29747. exports.Light = Light;
  29748. exports.LightProbe = LightProbe;
  29749. exports.Line = Line;
  29750. exports.Line3 = Line3;
  29751. exports.LineBasicMaterial = LineBasicMaterial;
  29752. exports.LineCurve = LineCurve;
  29753. exports.LineCurve3 = LineCurve3;
  29754. exports.LineDashedMaterial = LineDashedMaterial;
  29755. exports.LineLoop = LineLoop;
  29756. exports.LineSegments = LineSegments;
  29757. exports.LinearEncoding = LinearEncoding;
  29758. exports.LinearFilter = LinearFilter;
  29759. exports.LinearInterpolant = LinearInterpolant;
  29760. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29761. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29762. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29763. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29764. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  29765. exports.LinearToneMapping = LinearToneMapping;
  29766. exports.Loader = Loader;
  29767. exports.LoaderUtils = LoaderUtils;
  29768. exports.LoadingManager = LoadingManager;
  29769. exports.LoopOnce = LoopOnce;
  29770. exports.LoopPingPong = LoopPingPong;
  29771. exports.LoopRepeat = LoopRepeat;
  29772. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29773. exports.LuminanceFormat = LuminanceFormat;
  29774. exports.MOUSE = MOUSE;
  29775. exports.Material = Material;
  29776. exports.MaterialLoader = MaterialLoader;
  29777. exports.MathUtils = MathUtils;
  29778. exports.Matrix3 = Matrix3;
  29779. exports.Matrix4 = Matrix4;
  29780. exports.MaxEquation = MaxEquation;
  29781. exports.Mesh = Mesh;
  29782. exports.MeshBasicMaterial = MeshBasicMaterial;
  29783. exports.MeshDepthMaterial = MeshDepthMaterial;
  29784. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29785. exports.MeshLambertMaterial = MeshLambertMaterial;
  29786. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29787. exports.MeshNormalMaterial = MeshNormalMaterial;
  29788. exports.MeshPhongMaterial = MeshPhongMaterial;
  29789. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29790. exports.MeshStandardMaterial = MeshStandardMaterial;
  29791. exports.MeshToonMaterial = MeshToonMaterial;
  29792. exports.MinEquation = MinEquation;
  29793. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29794. exports.MixOperation = MixOperation;
  29795. exports.MultiplyBlending = MultiplyBlending;
  29796. exports.MultiplyOperation = MultiplyOperation;
  29797. exports.NearestFilter = NearestFilter;
  29798. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29799. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29800. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29801. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29802. exports.NeverDepth = NeverDepth;
  29803. exports.NeverStencilFunc = NeverStencilFunc;
  29804. exports.NoBlending = NoBlending;
  29805. exports.NoColorSpace = NoColorSpace;
  29806. exports.NoToneMapping = NoToneMapping;
  29807. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29808. exports.NormalBlending = NormalBlending;
  29809. exports.NotEqualDepth = NotEqualDepth;
  29810. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29811. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29812. exports.Object3D = Object3D;
  29813. exports.ObjectLoader = ObjectLoader;
  29814. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29815. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  29816. exports.OctahedronGeometry = OctahedronGeometry;
  29817. exports.OneFactor = OneFactor;
  29818. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29819. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29820. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29821. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29822. exports.OrthographicCamera = OrthographicCamera;
  29823. exports.PCFShadowMap = PCFShadowMap;
  29824. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29825. exports.PMREMGenerator = PMREMGenerator;
  29826. exports.Path = Path;
  29827. exports.PerspectiveCamera = PerspectiveCamera;
  29828. exports.Plane = Plane;
  29829. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  29830. exports.PlaneGeometry = PlaneGeometry;
  29831. exports.PlaneHelper = PlaneHelper;
  29832. exports.PointLight = PointLight;
  29833. exports.PointLightHelper = PointLightHelper;
  29834. exports.Points = Points;
  29835. exports.PointsMaterial = PointsMaterial;
  29836. exports.PolarGridHelper = PolarGridHelper;
  29837. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  29838. exports.PolyhedronGeometry = PolyhedronGeometry;
  29839. exports.PositionalAudio = PositionalAudio;
  29840. exports.PropertyBinding = PropertyBinding;
  29841. exports.PropertyMixer = PropertyMixer;
  29842. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29843. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29844. exports.Quaternion = Quaternion;
  29845. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29846. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29847. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  29848. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  29849. exports.REVISION = REVISION;
  29850. exports.RGBADepthPacking = RGBADepthPacking;
  29851. exports.RGBAFormat = RGBAFormat;
  29852. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29853. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29854. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29855. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29856. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29857. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29858. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29859. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29860. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29861. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29862. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29863. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29864. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29865. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29866. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29867. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29868. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29869. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29870. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29871. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29872. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29873. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29874. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29875. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29876. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29877. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29878. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29879. exports.RGFormat = RGFormat;
  29880. exports.RGIntegerFormat = RGIntegerFormat;
  29881. exports.RawShaderMaterial = RawShaderMaterial;
  29882. exports.Ray = Ray;
  29883. exports.Raycaster = Raycaster;
  29884. exports.RectAreaLight = RectAreaLight;
  29885. exports.RedFormat = RedFormat;
  29886. exports.RedIntegerFormat = RedIntegerFormat;
  29887. exports.ReinhardToneMapping = ReinhardToneMapping;
  29888. exports.RepeatWrapping = RepeatWrapping;
  29889. exports.ReplaceStencilOp = ReplaceStencilOp;
  29890. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29891. exports.RingBufferGeometry = RingBufferGeometry;
  29892. exports.RingGeometry = RingGeometry;
  29893. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  29894. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  29895. exports.SRGBColorSpace = SRGBColorSpace;
  29896. exports.Scene = Scene;
  29897. exports.ShaderChunk = ShaderChunk;
  29898. exports.ShaderLib = ShaderLib;
  29899. exports.ShaderMaterial = ShaderMaterial;
  29900. exports.ShadowMaterial = ShadowMaterial;
  29901. exports.Shape = Shape;
  29902. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29903. exports.ShapeGeometry = ShapeGeometry;
  29904. exports.ShapePath = ShapePath;
  29905. exports.ShapeUtils = ShapeUtils;
  29906. exports.ShortType = ShortType;
  29907. exports.Skeleton = Skeleton;
  29908. exports.SkeletonHelper = SkeletonHelper;
  29909. exports.SkinnedMesh = SkinnedMesh;
  29910. exports.Source = Source;
  29911. exports.Sphere = Sphere;
  29912. exports.SphereBufferGeometry = SphereBufferGeometry;
  29913. exports.SphereGeometry = SphereGeometry;
  29914. exports.Spherical = Spherical;
  29915. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29916. exports.SplineCurve = SplineCurve;
  29917. exports.SpotLight = SpotLight;
  29918. exports.SpotLightHelper = SpotLightHelper;
  29919. exports.Sprite = Sprite;
  29920. exports.SpriteMaterial = SpriteMaterial;
  29921. exports.SrcAlphaFactor = SrcAlphaFactor;
  29922. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29923. exports.SrcColorFactor = SrcColorFactor;
  29924. exports.StaticCopyUsage = StaticCopyUsage;
  29925. exports.StaticDrawUsage = StaticDrawUsage;
  29926. exports.StaticReadUsage = StaticReadUsage;
  29927. exports.StereoCamera = StereoCamera;
  29928. exports.StreamCopyUsage = StreamCopyUsage;
  29929. exports.StreamDrawUsage = StreamDrawUsage;
  29930. exports.StreamReadUsage = StreamReadUsage;
  29931. exports.StringKeyframeTrack = StringKeyframeTrack;
  29932. exports.SubtractEquation = SubtractEquation;
  29933. exports.SubtractiveBlending = SubtractiveBlending;
  29934. exports.TOUCH = TOUCH;
  29935. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29936. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29937. exports.TetrahedronGeometry = TetrahedronGeometry;
  29938. exports.Texture = Texture;
  29939. exports.TextureLoader = TextureLoader;
  29940. exports.TorusBufferGeometry = TorusBufferGeometry;
  29941. exports.TorusGeometry = TorusGeometry;
  29942. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29943. exports.TorusKnotGeometry = TorusKnotGeometry;
  29944. exports.Triangle = Triangle;
  29945. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29946. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29947. exports.TrianglesDrawMode = TrianglesDrawMode;
  29948. exports.TubeBufferGeometry = TubeBufferGeometry;
  29949. exports.TubeGeometry = TubeGeometry;
  29950. exports.TwoPassDoubleSide = TwoPassDoubleSide;
  29951. exports.UVMapping = UVMapping;
  29952. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29953. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29954. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29955. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29956. exports.Uniform = Uniform;
  29957. exports.UniformsGroup = UniformsGroup;
  29958. exports.UniformsLib = UniformsLib;
  29959. exports.UniformsUtils = UniformsUtils;
  29960. exports.UnsignedByteType = UnsignedByteType;
  29961. exports.UnsignedInt248Type = UnsignedInt248Type;
  29962. exports.UnsignedIntType = UnsignedIntType;
  29963. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29964. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29965. exports.UnsignedShortType = UnsignedShortType;
  29966. exports.VSMShadowMap = VSMShadowMap;
  29967. exports.Vector2 = Vector2;
  29968. exports.Vector3 = Vector3;
  29969. exports.Vector4 = Vector4;
  29970. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29971. exports.VideoTexture = VideoTexture;
  29972. exports.WebGL1Renderer = WebGL1Renderer;
  29973. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  29974. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  29975. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29976. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29977. exports.WebGLRenderTarget = WebGLRenderTarget;
  29978. exports.WebGLRenderer = WebGLRenderer;
  29979. exports.WebGLUtils = WebGLUtils;
  29980. exports.WireframeGeometry = WireframeGeometry;
  29981. exports.WrapAroundEnding = WrapAroundEnding;
  29982. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29983. exports.ZeroFactor = ZeroFactor;
  29984. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29985. exports.ZeroStencilOp = ZeroStencilOp;
  29986. exports._SRGBAFormat = _SRGBAFormat;
  29987. exports.sRGBEncoding = sRGBEncoding;