three.cjs 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '150dev';
  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. // RGB-to-RGB transforms, defined as `FN[InputColorSpace][OutputColorSpace] → conversionFn`.
  924. const FN = {
  925. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  926. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  927. };
  928. const ColorManagement = {
  929. enabled: false,
  930. get legacyMode() {
  931. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r147.' );
  932. return ! this.enabled;
  933. },
  934. set legacyMode( legacyMode ) {
  935. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r147.' );
  936. this.enabled = ! legacyMode;
  937. },
  938. get workingColorSpace() {
  939. return LinearSRGBColorSpace;
  940. },
  941. set workingColorSpace( colorSpace ) {
  942. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  943. },
  944. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  945. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  946. return color;
  947. }
  948. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  949. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  950. color.r = fn( color.r );
  951. color.g = fn( color.g );
  952. color.b = fn( color.b );
  953. return color;
  954. }
  955. throw new Error( 'Unsupported color space conversion.' );
  956. },
  957. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  958. return this.convert( color, this.workingColorSpace, targetColorSpace );
  959. },
  960. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  961. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  962. },
  963. };
  964. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  965. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  966. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  967. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  968. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  969. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  970. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  971. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  972. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  973. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  974. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  975. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  976. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  977. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  978. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  979. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  980. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  981. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  982. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  983. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  984. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  985. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  986. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  987. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  988. const _rgb$1 = { r: 0, g: 0, b: 0 };
  989. const _hslA = { h: 0, s: 0, l: 0 };
  990. const _hslB = { h: 0, s: 0, l: 0 };
  991. function hue2rgb( p, q, t ) {
  992. if ( t < 0 ) t += 1;
  993. if ( t > 1 ) t -= 1;
  994. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  995. if ( t < 1 / 2 ) return q;
  996. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  997. return p;
  998. }
  999. function toComponents( source, target ) {
  1000. target.r = source.r;
  1001. target.g = source.g;
  1002. target.b = source.b;
  1003. return target;
  1004. }
  1005. class Color {
  1006. constructor( r, g, b ) {
  1007. this.isColor = true;
  1008. this.r = 1;
  1009. this.g = 1;
  1010. this.b = 1;
  1011. if ( g === undefined && b === undefined ) {
  1012. // r is THREE.Color, hex or string
  1013. return this.set( r );
  1014. }
  1015. return this.setRGB( r, g, b );
  1016. }
  1017. set( value ) {
  1018. if ( value && value.isColor ) {
  1019. this.copy( value );
  1020. } else if ( typeof value === 'number' ) {
  1021. this.setHex( value );
  1022. } else if ( typeof value === 'string' ) {
  1023. this.setStyle( value );
  1024. }
  1025. return this;
  1026. }
  1027. setScalar( scalar ) {
  1028. this.r = scalar;
  1029. this.g = scalar;
  1030. this.b = scalar;
  1031. return this;
  1032. }
  1033. setHex( hex, colorSpace = SRGBColorSpace ) {
  1034. hex = Math.floor( hex );
  1035. this.r = ( hex >> 16 & 255 ) / 255;
  1036. this.g = ( hex >> 8 & 255 ) / 255;
  1037. this.b = ( hex & 255 ) / 255;
  1038. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1039. return this;
  1040. }
  1041. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  1042. this.r = r;
  1043. this.g = g;
  1044. this.b = b;
  1045. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1046. return this;
  1047. }
  1048. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  1049. // h,s,l ranges are in 0.0 - 1.0
  1050. h = euclideanModulo( h, 1 );
  1051. s = clamp( s, 0, 1 );
  1052. l = clamp( l, 0, 1 );
  1053. if ( s === 0 ) {
  1054. this.r = this.g = this.b = l;
  1055. } else {
  1056. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1057. const q = ( 2 * l ) - p;
  1058. this.r = hue2rgb( q, p, h + 1 / 3 );
  1059. this.g = hue2rgb( q, p, h );
  1060. this.b = hue2rgb( q, p, h - 1 / 3 );
  1061. }
  1062. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1063. return this;
  1064. }
  1065. setStyle( style, colorSpace = SRGBColorSpace ) {
  1066. function handleAlpha( string ) {
  1067. if ( string === undefined ) return;
  1068. if ( parseFloat( string ) < 1 ) {
  1069. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1070. }
  1071. }
  1072. let m;
  1073. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1074. // rgb / hsl
  1075. let color;
  1076. const name = m[ 1 ];
  1077. const components = m[ 2 ];
  1078. switch ( name ) {
  1079. case 'rgb':
  1080. case 'rgba':
  1081. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1082. // rgb(255,0,0) rgba(255,0,0,0.5)
  1083. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1084. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1085. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1086. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1087. handleAlpha( color[ 4 ] );
  1088. return this;
  1089. }
  1090. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1091. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1092. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1093. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1094. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1095. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1096. handleAlpha( color[ 4 ] );
  1097. return this;
  1098. }
  1099. break;
  1100. case 'hsl':
  1101. case 'hsla':
  1102. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1103. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1104. const h = parseFloat( color[ 1 ] ) / 360;
  1105. const s = parseFloat( color[ 2 ] ) / 100;
  1106. const l = parseFloat( color[ 3 ] ) / 100;
  1107. handleAlpha( color[ 4 ] );
  1108. return this.setHSL( h, s, l, colorSpace );
  1109. }
  1110. break;
  1111. }
  1112. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1113. // hex color
  1114. const hex = m[ 1 ];
  1115. const size = hex.length;
  1116. if ( size === 3 ) {
  1117. // #ff0
  1118. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1119. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1120. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1121. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1122. return this;
  1123. } else if ( size === 6 ) {
  1124. // #ff0000
  1125. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1126. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1127. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1128. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1129. return this;
  1130. }
  1131. }
  1132. if ( style && style.length > 0 ) {
  1133. return this.setColorName( style, colorSpace );
  1134. }
  1135. return this;
  1136. }
  1137. setColorName( style, colorSpace = SRGBColorSpace ) {
  1138. // color keywords
  1139. const hex = _colorKeywords[ style.toLowerCase() ];
  1140. if ( hex !== undefined ) {
  1141. // red
  1142. this.setHex( hex, colorSpace );
  1143. } else {
  1144. // unknown color
  1145. console.warn( 'THREE.Color: Unknown color ' + style );
  1146. }
  1147. return this;
  1148. }
  1149. clone() {
  1150. return new this.constructor( this.r, this.g, this.b );
  1151. }
  1152. copy( color ) {
  1153. this.r = color.r;
  1154. this.g = color.g;
  1155. this.b = color.b;
  1156. return this;
  1157. }
  1158. copySRGBToLinear( color ) {
  1159. this.r = SRGBToLinear( color.r );
  1160. this.g = SRGBToLinear( color.g );
  1161. this.b = SRGBToLinear( color.b );
  1162. return this;
  1163. }
  1164. copyLinearToSRGB( color ) {
  1165. this.r = LinearToSRGB( color.r );
  1166. this.g = LinearToSRGB( color.g );
  1167. this.b = LinearToSRGB( color.b );
  1168. return this;
  1169. }
  1170. convertSRGBToLinear() {
  1171. this.copySRGBToLinear( this );
  1172. return this;
  1173. }
  1174. convertLinearToSRGB() {
  1175. this.copyLinearToSRGB( this );
  1176. return this;
  1177. }
  1178. getHex( colorSpace = SRGBColorSpace ) {
  1179. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1180. 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;
  1181. }
  1182. getHexString( colorSpace = SRGBColorSpace ) {
  1183. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1184. }
  1185. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  1186. // h,s,l ranges are in 0.0 - 1.0
  1187. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1188. const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b;
  1189. const max = Math.max( r, g, b );
  1190. const min = Math.min( r, g, b );
  1191. let hue, saturation;
  1192. const lightness = ( min + max ) / 2.0;
  1193. if ( min === max ) {
  1194. hue = 0;
  1195. saturation = 0;
  1196. } else {
  1197. const delta = max - min;
  1198. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1199. switch ( max ) {
  1200. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1201. case g: hue = ( b - r ) / delta + 2; break;
  1202. case b: hue = ( r - g ) / delta + 4; break;
  1203. }
  1204. hue /= 6;
  1205. }
  1206. target.h = hue;
  1207. target.s = saturation;
  1208. target.l = lightness;
  1209. return target;
  1210. }
  1211. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  1212. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1213. target.r = _rgb$1.r;
  1214. target.g = _rgb$1.g;
  1215. target.b = _rgb$1.b;
  1216. return target;
  1217. }
  1218. getStyle( colorSpace = SRGBColorSpace ) {
  1219. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1220. if ( colorSpace !== SRGBColorSpace ) {
  1221. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1222. return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`;
  1223. }
  1224. return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`;
  1225. }
  1226. offsetHSL( h, s, l ) {
  1227. this.getHSL( _hslA );
  1228. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1229. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1230. return this;
  1231. }
  1232. add( color ) {
  1233. this.r += color.r;
  1234. this.g += color.g;
  1235. this.b += color.b;
  1236. return this;
  1237. }
  1238. addColors( color1, color2 ) {
  1239. this.r = color1.r + color2.r;
  1240. this.g = color1.g + color2.g;
  1241. this.b = color1.b + color2.b;
  1242. return this;
  1243. }
  1244. addScalar( s ) {
  1245. this.r += s;
  1246. this.g += s;
  1247. this.b += s;
  1248. return this;
  1249. }
  1250. sub( color ) {
  1251. this.r = Math.max( 0, this.r - color.r );
  1252. this.g = Math.max( 0, this.g - color.g );
  1253. this.b = Math.max( 0, this.b - color.b );
  1254. return this;
  1255. }
  1256. multiply( color ) {
  1257. this.r *= color.r;
  1258. this.g *= color.g;
  1259. this.b *= color.b;
  1260. return this;
  1261. }
  1262. multiplyScalar( s ) {
  1263. this.r *= s;
  1264. this.g *= s;
  1265. this.b *= s;
  1266. return this;
  1267. }
  1268. lerp( color, alpha ) {
  1269. this.r += ( color.r - this.r ) * alpha;
  1270. this.g += ( color.g - this.g ) * alpha;
  1271. this.b += ( color.b - this.b ) * alpha;
  1272. return this;
  1273. }
  1274. lerpColors( color1, color2, alpha ) {
  1275. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1276. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1277. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1278. return this;
  1279. }
  1280. lerpHSL( color, alpha ) {
  1281. this.getHSL( _hslA );
  1282. color.getHSL( _hslB );
  1283. const h = lerp( _hslA.h, _hslB.h, alpha );
  1284. const s = lerp( _hslA.s, _hslB.s, alpha );
  1285. const l = lerp( _hslA.l, _hslB.l, alpha );
  1286. this.setHSL( h, s, l );
  1287. return this;
  1288. }
  1289. equals( c ) {
  1290. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1291. }
  1292. fromArray( array, offset = 0 ) {
  1293. this.r = array[ offset ];
  1294. this.g = array[ offset + 1 ];
  1295. this.b = array[ offset + 2 ];
  1296. return this;
  1297. }
  1298. toArray( array = [], offset = 0 ) {
  1299. array[ offset ] = this.r;
  1300. array[ offset + 1 ] = this.g;
  1301. array[ offset + 2 ] = this.b;
  1302. return array;
  1303. }
  1304. fromBufferAttribute( attribute, index ) {
  1305. this.r = attribute.getX( index );
  1306. this.g = attribute.getY( index );
  1307. this.b = attribute.getZ( index );
  1308. return this;
  1309. }
  1310. toJSON() {
  1311. return this.getHex();
  1312. }
  1313. *[ Symbol.iterator ]() {
  1314. yield this.r;
  1315. yield this.g;
  1316. yield this.b;
  1317. }
  1318. }
  1319. Color.NAMES = _colorKeywords;
  1320. let _canvas;
  1321. class ImageUtils {
  1322. static getDataURL( image ) {
  1323. if ( /^data:/i.test( image.src ) ) {
  1324. return image.src;
  1325. }
  1326. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1327. return image.src;
  1328. }
  1329. let canvas;
  1330. if ( image instanceof HTMLCanvasElement ) {
  1331. canvas = image;
  1332. } else {
  1333. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1334. _canvas.width = image.width;
  1335. _canvas.height = image.height;
  1336. const context = _canvas.getContext( '2d' );
  1337. if ( image instanceof ImageData ) {
  1338. context.putImageData( image, 0, 0 );
  1339. } else {
  1340. context.drawImage( image, 0, 0, image.width, image.height );
  1341. }
  1342. canvas = _canvas;
  1343. }
  1344. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1345. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1346. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1347. } else {
  1348. return canvas.toDataURL( 'image/png' );
  1349. }
  1350. }
  1351. static sRGBToLinear( image ) {
  1352. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1353. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1354. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1355. const canvas = createElementNS( 'canvas' );
  1356. canvas.width = image.width;
  1357. canvas.height = image.height;
  1358. const context = canvas.getContext( '2d' );
  1359. context.drawImage( image, 0, 0, image.width, image.height );
  1360. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1361. const data = imageData.data;
  1362. for ( let i = 0; i < data.length; i ++ ) {
  1363. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1364. }
  1365. context.putImageData( imageData, 0, 0 );
  1366. return canvas;
  1367. } else if ( image.data ) {
  1368. const data = image.data.slice( 0 );
  1369. for ( let i = 0; i < data.length; i ++ ) {
  1370. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1371. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1372. } else {
  1373. // assuming float
  1374. data[ i ] = SRGBToLinear( data[ i ] );
  1375. }
  1376. }
  1377. return {
  1378. data: data,
  1379. width: image.width,
  1380. height: image.height
  1381. };
  1382. } else {
  1383. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1384. return image;
  1385. }
  1386. }
  1387. }
  1388. class Source {
  1389. constructor( data = null ) {
  1390. this.isSource = true;
  1391. this.uuid = generateUUID();
  1392. this.data = data;
  1393. this.version = 0;
  1394. }
  1395. set needsUpdate( value ) {
  1396. if ( value === true ) this.version ++;
  1397. }
  1398. toJSON( meta ) {
  1399. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1400. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1401. return meta.images[ this.uuid ];
  1402. }
  1403. const output = {
  1404. uuid: this.uuid,
  1405. url: ''
  1406. };
  1407. const data = this.data;
  1408. if ( data !== null ) {
  1409. let url;
  1410. if ( Array.isArray( data ) ) {
  1411. // cube texture
  1412. url = [];
  1413. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1414. if ( data[ i ].isDataTexture ) {
  1415. url.push( serializeImage( data[ i ].image ) );
  1416. } else {
  1417. url.push( serializeImage( data[ i ] ) );
  1418. }
  1419. }
  1420. } else {
  1421. // texture
  1422. url = serializeImage( data );
  1423. }
  1424. output.url = url;
  1425. }
  1426. if ( ! isRootObject ) {
  1427. meta.images[ this.uuid ] = output;
  1428. }
  1429. return output;
  1430. }
  1431. }
  1432. function serializeImage( image ) {
  1433. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1434. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1435. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1436. // default images
  1437. return ImageUtils.getDataURL( image );
  1438. } else {
  1439. if ( image.data ) {
  1440. // images of DataTexture
  1441. return {
  1442. data: Array.from( image.data ),
  1443. width: image.width,
  1444. height: image.height,
  1445. type: image.data.constructor.name
  1446. };
  1447. } else {
  1448. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1449. return {};
  1450. }
  1451. }
  1452. }
  1453. let textureId = 0;
  1454. class Texture extends EventDispatcher {
  1455. 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 ) {
  1456. super();
  1457. this.isTexture = true;
  1458. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1459. this.uuid = generateUUID();
  1460. this.name = '';
  1461. this.source = new Source( image );
  1462. this.mipmaps = [];
  1463. this.mapping = mapping;
  1464. this.wrapS = wrapS;
  1465. this.wrapT = wrapT;
  1466. this.magFilter = magFilter;
  1467. this.minFilter = minFilter;
  1468. this.anisotropy = anisotropy;
  1469. this.format = format;
  1470. this.internalFormat = null;
  1471. this.type = type;
  1472. this.offset = new Vector2( 0, 0 );
  1473. this.repeat = new Vector2( 1, 1 );
  1474. this.center = new Vector2( 0, 0 );
  1475. this.rotation = 0;
  1476. this.matrixAutoUpdate = true;
  1477. this.matrix = new Matrix3();
  1478. this.generateMipmaps = true;
  1479. this.premultiplyAlpha = false;
  1480. this.flipY = true;
  1481. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1482. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1483. //
  1484. // Also changing the encoding after already used by a Material will not automatically make the Material
  1485. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1486. this.encoding = encoding;
  1487. this.userData = {};
  1488. this.version = 0;
  1489. this.onUpdate = null;
  1490. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1491. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1492. }
  1493. get image() {
  1494. return this.source.data;
  1495. }
  1496. set image( value ) {
  1497. this.source.data = value;
  1498. }
  1499. updateMatrix() {
  1500. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1501. }
  1502. clone() {
  1503. return new this.constructor().copy( this );
  1504. }
  1505. copy( source ) {
  1506. this.name = source.name;
  1507. this.source = source.source;
  1508. this.mipmaps = source.mipmaps.slice( 0 );
  1509. this.mapping = source.mapping;
  1510. this.wrapS = source.wrapS;
  1511. this.wrapT = source.wrapT;
  1512. this.magFilter = source.magFilter;
  1513. this.minFilter = source.minFilter;
  1514. this.anisotropy = source.anisotropy;
  1515. this.format = source.format;
  1516. this.internalFormat = source.internalFormat;
  1517. this.type = source.type;
  1518. this.offset.copy( source.offset );
  1519. this.repeat.copy( source.repeat );
  1520. this.center.copy( source.center );
  1521. this.rotation = source.rotation;
  1522. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1523. this.matrix.copy( source.matrix );
  1524. this.generateMipmaps = source.generateMipmaps;
  1525. this.premultiplyAlpha = source.premultiplyAlpha;
  1526. this.flipY = source.flipY;
  1527. this.unpackAlignment = source.unpackAlignment;
  1528. this.encoding = source.encoding;
  1529. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1530. this.needsUpdate = true;
  1531. return this;
  1532. }
  1533. toJSON( meta ) {
  1534. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1535. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1536. return meta.textures[ this.uuid ];
  1537. }
  1538. const output = {
  1539. metadata: {
  1540. version: 4.5,
  1541. type: 'Texture',
  1542. generator: 'Texture.toJSON'
  1543. },
  1544. uuid: this.uuid,
  1545. name: this.name,
  1546. image: this.source.toJSON( meta ).uuid,
  1547. mapping: this.mapping,
  1548. repeat: [ this.repeat.x, this.repeat.y ],
  1549. offset: [ this.offset.x, this.offset.y ],
  1550. center: [ this.center.x, this.center.y ],
  1551. rotation: this.rotation,
  1552. wrap: [ this.wrapS, this.wrapT ],
  1553. format: this.format,
  1554. type: this.type,
  1555. encoding: this.encoding,
  1556. minFilter: this.minFilter,
  1557. magFilter: this.magFilter,
  1558. anisotropy: this.anisotropy,
  1559. flipY: this.flipY,
  1560. generateMipmaps: this.generateMipmaps,
  1561. premultiplyAlpha: this.premultiplyAlpha,
  1562. unpackAlignment: this.unpackAlignment
  1563. };
  1564. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1565. if ( ! isRootObject ) {
  1566. meta.textures[ this.uuid ] = output;
  1567. }
  1568. return output;
  1569. }
  1570. dispose() {
  1571. this.dispatchEvent( { type: 'dispose' } );
  1572. }
  1573. transformUv( uv ) {
  1574. if ( this.mapping !== UVMapping ) return uv;
  1575. uv.applyMatrix3( this.matrix );
  1576. if ( uv.x < 0 || uv.x > 1 ) {
  1577. switch ( this.wrapS ) {
  1578. case RepeatWrapping:
  1579. uv.x = uv.x - Math.floor( uv.x );
  1580. break;
  1581. case ClampToEdgeWrapping:
  1582. uv.x = uv.x < 0 ? 0 : 1;
  1583. break;
  1584. case MirroredRepeatWrapping:
  1585. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1586. uv.x = Math.ceil( uv.x ) - uv.x;
  1587. } else {
  1588. uv.x = uv.x - Math.floor( uv.x );
  1589. }
  1590. break;
  1591. }
  1592. }
  1593. if ( uv.y < 0 || uv.y > 1 ) {
  1594. switch ( this.wrapT ) {
  1595. case RepeatWrapping:
  1596. uv.y = uv.y - Math.floor( uv.y );
  1597. break;
  1598. case ClampToEdgeWrapping:
  1599. uv.y = uv.y < 0 ? 0 : 1;
  1600. break;
  1601. case MirroredRepeatWrapping:
  1602. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1603. uv.y = Math.ceil( uv.y ) - uv.y;
  1604. } else {
  1605. uv.y = uv.y - Math.floor( uv.y );
  1606. }
  1607. break;
  1608. }
  1609. }
  1610. if ( this.flipY ) {
  1611. uv.y = 1 - uv.y;
  1612. }
  1613. return uv;
  1614. }
  1615. set needsUpdate( value ) {
  1616. if ( value === true ) {
  1617. this.version ++;
  1618. this.source.needsUpdate = true;
  1619. }
  1620. }
  1621. }
  1622. Texture.DEFAULT_IMAGE = null;
  1623. Texture.DEFAULT_MAPPING = UVMapping;
  1624. Texture.DEFAULT_ANISOTROPY = 1;
  1625. class Vector4 {
  1626. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1627. Vector4.prototype.isVector4 = true;
  1628. this.x = x;
  1629. this.y = y;
  1630. this.z = z;
  1631. this.w = w;
  1632. }
  1633. get width() {
  1634. return this.z;
  1635. }
  1636. set width( value ) {
  1637. this.z = value;
  1638. }
  1639. get height() {
  1640. return this.w;
  1641. }
  1642. set height( value ) {
  1643. this.w = value;
  1644. }
  1645. set( x, y, z, w ) {
  1646. this.x = x;
  1647. this.y = y;
  1648. this.z = z;
  1649. this.w = w;
  1650. return this;
  1651. }
  1652. setScalar( scalar ) {
  1653. this.x = scalar;
  1654. this.y = scalar;
  1655. this.z = scalar;
  1656. this.w = scalar;
  1657. return this;
  1658. }
  1659. setX( x ) {
  1660. this.x = x;
  1661. return this;
  1662. }
  1663. setY( y ) {
  1664. this.y = y;
  1665. return this;
  1666. }
  1667. setZ( z ) {
  1668. this.z = z;
  1669. return this;
  1670. }
  1671. setW( w ) {
  1672. this.w = w;
  1673. return this;
  1674. }
  1675. setComponent( index, value ) {
  1676. switch ( index ) {
  1677. case 0: this.x = value; break;
  1678. case 1: this.y = value; break;
  1679. case 2: this.z = value; break;
  1680. case 3: this.w = value; break;
  1681. default: throw new Error( 'index is out of range: ' + index );
  1682. }
  1683. return this;
  1684. }
  1685. getComponent( index ) {
  1686. switch ( index ) {
  1687. case 0: return this.x;
  1688. case 1: return this.y;
  1689. case 2: return this.z;
  1690. case 3: return this.w;
  1691. default: throw new Error( 'index is out of range: ' + index );
  1692. }
  1693. }
  1694. clone() {
  1695. return new this.constructor( this.x, this.y, this.z, this.w );
  1696. }
  1697. copy( v ) {
  1698. this.x = v.x;
  1699. this.y = v.y;
  1700. this.z = v.z;
  1701. this.w = ( v.w !== undefined ) ? v.w : 1;
  1702. return this;
  1703. }
  1704. add( v ) {
  1705. this.x += v.x;
  1706. this.y += v.y;
  1707. this.z += v.z;
  1708. this.w += v.w;
  1709. return this;
  1710. }
  1711. addScalar( s ) {
  1712. this.x += s;
  1713. this.y += s;
  1714. this.z += s;
  1715. this.w += s;
  1716. return this;
  1717. }
  1718. addVectors( a, b ) {
  1719. this.x = a.x + b.x;
  1720. this.y = a.y + b.y;
  1721. this.z = a.z + b.z;
  1722. this.w = a.w + b.w;
  1723. return this;
  1724. }
  1725. addScaledVector( v, s ) {
  1726. this.x += v.x * s;
  1727. this.y += v.y * s;
  1728. this.z += v.z * s;
  1729. this.w += v.w * s;
  1730. return this;
  1731. }
  1732. sub( v ) {
  1733. this.x -= v.x;
  1734. this.y -= v.y;
  1735. this.z -= v.z;
  1736. this.w -= v.w;
  1737. return this;
  1738. }
  1739. subScalar( s ) {
  1740. this.x -= s;
  1741. this.y -= s;
  1742. this.z -= s;
  1743. this.w -= s;
  1744. return this;
  1745. }
  1746. subVectors( a, b ) {
  1747. this.x = a.x - b.x;
  1748. this.y = a.y - b.y;
  1749. this.z = a.z - b.z;
  1750. this.w = a.w - b.w;
  1751. return this;
  1752. }
  1753. multiply( v ) {
  1754. this.x *= v.x;
  1755. this.y *= v.y;
  1756. this.z *= v.z;
  1757. this.w *= v.w;
  1758. return this;
  1759. }
  1760. multiplyScalar( scalar ) {
  1761. this.x *= scalar;
  1762. this.y *= scalar;
  1763. this.z *= scalar;
  1764. this.w *= scalar;
  1765. return this;
  1766. }
  1767. applyMatrix4( m ) {
  1768. const x = this.x, y = this.y, z = this.z, w = this.w;
  1769. const e = m.elements;
  1770. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1771. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1772. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1773. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1774. return this;
  1775. }
  1776. divideScalar( scalar ) {
  1777. return this.multiplyScalar( 1 / scalar );
  1778. }
  1779. setAxisAngleFromQuaternion( q ) {
  1780. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1781. // q is assumed to be normalized
  1782. this.w = 2 * Math.acos( q.w );
  1783. const s = Math.sqrt( 1 - q.w * q.w );
  1784. if ( s < 0.0001 ) {
  1785. this.x = 1;
  1786. this.y = 0;
  1787. this.z = 0;
  1788. } else {
  1789. this.x = q.x / s;
  1790. this.y = q.y / s;
  1791. this.z = q.z / s;
  1792. }
  1793. return this;
  1794. }
  1795. setAxisAngleFromRotationMatrix( m ) {
  1796. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1797. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1798. let angle, x, y, z; // variables for result
  1799. const epsilon = 0.01, // margin to allow for rounding errors
  1800. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1801. te = m.elements,
  1802. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1803. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1804. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1805. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1806. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1807. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1808. // singularity found
  1809. // first check for identity matrix which must have +1 for all terms
  1810. // in leading diagonal and zero in other terms
  1811. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1812. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1813. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1814. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1815. // this singularity is identity matrix so angle = 0
  1816. this.set( 1, 0, 0, 0 );
  1817. return this; // zero angle, arbitrary axis
  1818. }
  1819. // otherwise this singularity is angle = 180
  1820. angle = Math.PI;
  1821. const xx = ( m11 + 1 ) / 2;
  1822. const yy = ( m22 + 1 ) / 2;
  1823. const zz = ( m33 + 1 ) / 2;
  1824. const xy = ( m12 + m21 ) / 4;
  1825. const xz = ( m13 + m31 ) / 4;
  1826. const yz = ( m23 + m32 ) / 4;
  1827. if ( ( xx > yy ) && ( xx > zz ) ) {
  1828. // m11 is the largest diagonal term
  1829. if ( xx < epsilon ) {
  1830. x = 0;
  1831. y = 0.707106781;
  1832. z = 0.707106781;
  1833. } else {
  1834. x = Math.sqrt( xx );
  1835. y = xy / x;
  1836. z = xz / x;
  1837. }
  1838. } else if ( yy > zz ) {
  1839. // m22 is the largest diagonal term
  1840. if ( yy < epsilon ) {
  1841. x = 0.707106781;
  1842. y = 0;
  1843. z = 0.707106781;
  1844. } else {
  1845. y = Math.sqrt( yy );
  1846. x = xy / y;
  1847. z = yz / y;
  1848. }
  1849. } else {
  1850. // m33 is the largest diagonal term so base result on this
  1851. if ( zz < epsilon ) {
  1852. x = 0.707106781;
  1853. y = 0.707106781;
  1854. z = 0;
  1855. } else {
  1856. z = Math.sqrt( zz );
  1857. x = xz / z;
  1858. y = yz / z;
  1859. }
  1860. }
  1861. this.set( x, y, z, angle );
  1862. return this; // return 180 deg rotation
  1863. }
  1864. // as we have reached here there are no singularities so we can handle normally
  1865. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1866. ( m13 - m31 ) * ( m13 - m31 ) +
  1867. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1868. if ( Math.abs( s ) < 0.001 ) s = 1;
  1869. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1870. // caught by singularity test above, but I've left it in just in case
  1871. this.x = ( m32 - m23 ) / s;
  1872. this.y = ( m13 - m31 ) / s;
  1873. this.z = ( m21 - m12 ) / s;
  1874. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1875. return this;
  1876. }
  1877. min( v ) {
  1878. this.x = Math.min( this.x, v.x );
  1879. this.y = Math.min( this.y, v.y );
  1880. this.z = Math.min( this.z, v.z );
  1881. this.w = Math.min( this.w, v.w );
  1882. return this;
  1883. }
  1884. max( v ) {
  1885. this.x = Math.max( this.x, v.x );
  1886. this.y = Math.max( this.y, v.y );
  1887. this.z = Math.max( this.z, v.z );
  1888. this.w = Math.max( this.w, v.w );
  1889. return this;
  1890. }
  1891. clamp( min, max ) {
  1892. // assumes min < max, componentwise
  1893. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1894. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1895. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1896. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1897. return this;
  1898. }
  1899. clampScalar( minVal, maxVal ) {
  1900. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1901. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1902. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1903. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1904. return this;
  1905. }
  1906. clampLength( min, max ) {
  1907. const length = this.length();
  1908. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1909. }
  1910. floor() {
  1911. this.x = Math.floor( this.x );
  1912. this.y = Math.floor( this.y );
  1913. this.z = Math.floor( this.z );
  1914. this.w = Math.floor( this.w );
  1915. return this;
  1916. }
  1917. ceil() {
  1918. this.x = Math.ceil( this.x );
  1919. this.y = Math.ceil( this.y );
  1920. this.z = Math.ceil( this.z );
  1921. this.w = Math.ceil( this.w );
  1922. return this;
  1923. }
  1924. round() {
  1925. this.x = Math.round( this.x );
  1926. this.y = Math.round( this.y );
  1927. this.z = Math.round( this.z );
  1928. this.w = Math.round( this.w );
  1929. return this;
  1930. }
  1931. roundToZero() {
  1932. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1933. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1934. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1935. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1936. return this;
  1937. }
  1938. negate() {
  1939. this.x = - this.x;
  1940. this.y = - this.y;
  1941. this.z = - this.z;
  1942. this.w = - this.w;
  1943. return this;
  1944. }
  1945. dot( v ) {
  1946. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1947. }
  1948. lengthSq() {
  1949. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1950. }
  1951. length() {
  1952. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1953. }
  1954. manhattanLength() {
  1955. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1956. }
  1957. normalize() {
  1958. return this.divideScalar( this.length() || 1 );
  1959. }
  1960. setLength( length ) {
  1961. return this.normalize().multiplyScalar( length );
  1962. }
  1963. lerp( v, alpha ) {
  1964. this.x += ( v.x - this.x ) * alpha;
  1965. this.y += ( v.y - this.y ) * alpha;
  1966. this.z += ( v.z - this.z ) * alpha;
  1967. this.w += ( v.w - this.w ) * alpha;
  1968. return this;
  1969. }
  1970. lerpVectors( v1, v2, alpha ) {
  1971. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1972. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1973. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1974. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1975. return this;
  1976. }
  1977. equals( v ) {
  1978. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1979. }
  1980. fromArray( array, offset = 0 ) {
  1981. this.x = array[ offset ];
  1982. this.y = array[ offset + 1 ];
  1983. this.z = array[ offset + 2 ];
  1984. this.w = array[ offset + 3 ];
  1985. return this;
  1986. }
  1987. toArray( array = [], offset = 0 ) {
  1988. array[ offset ] = this.x;
  1989. array[ offset + 1 ] = this.y;
  1990. array[ offset + 2 ] = this.z;
  1991. array[ offset + 3 ] = this.w;
  1992. return array;
  1993. }
  1994. fromBufferAttribute( attribute, index ) {
  1995. this.x = attribute.getX( index );
  1996. this.y = attribute.getY( index );
  1997. this.z = attribute.getZ( index );
  1998. this.w = attribute.getW( index );
  1999. return this;
  2000. }
  2001. random() {
  2002. this.x = Math.random();
  2003. this.y = Math.random();
  2004. this.z = Math.random();
  2005. this.w = Math.random();
  2006. return this;
  2007. }
  2008. *[ Symbol.iterator ]() {
  2009. yield this.x;
  2010. yield this.y;
  2011. yield this.z;
  2012. yield this.w;
  2013. }
  2014. }
  2015. /*
  2016. In options, we can specify:
  2017. * Texture parameters for an auto-generated target texture
  2018. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2019. */
  2020. class WebGLRenderTarget extends EventDispatcher {
  2021. constructor( width = 1, height = 1, options = {} ) {
  2022. super();
  2023. this.isWebGLRenderTarget = true;
  2024. this.width = width;
  2025. this.height = height;
  2026. this.depth = 1;
  2027. this.scissor = new Vector4( 0, 0, width, height );
  2028. this.scissorTest = false;
  2029. this.viewport = new Vector4( 0, 0, width, height );
  2030. const image = { width: width, height: height, depth: 1 };
  2031. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2032. this.texture.isRenderTargetTexture = true;
  2033. this.texture.flipY = false;
  2034. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2035. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2036. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2037. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2038. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2039. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2040. this.samples = options.samples !== undefined ? options.samples : 0;
  2041. }
  2042. setSize( width, height, depth = 1 ) {
  2043. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2044. this.width = width;
  2045. this.height = height;
  2046. this.depth = depth;
  2047. this.texture.image.width = width;
  2048. this.texture.image.height = height;
  2049. this.texture.image.depth = depth;
  2050. this.dispose();
  2051. }
  2052. this.viewport.set( 0, 0, width, height );
  2053. this.scissor.set( 0, 0, width, height );
  2054. }
  2055. clone() {
  2056. return new this.constructor().copy( this );
  2057. }
  2058. copy( source ) {
  2059. this.width = source.width;
  2060. this.height = source.height;
  2061. this.depth = source.depth;
  2062. this.viewport.copy( source.viewport );
  2063. this.texture = source.texture.clone();
  2064. this.texture.isRenderTargetTexture = true;
  2065. // ensure image object is not shared, see #20328
  2066. const image = Object.assign( {}, source.texture.image );
  2067. this.texture.source = new Source( image );
  2068. this.depthBuffer = source.depthBuffer;
  2069. this.stencilBuffer = source.stencilBuffer;
  2070. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2071. this.samples = source.samples;
  2072. return this;
  2073. }
  2074. dispose() {
  2075. this.dispatchEvent( { type: 'dispose' } );
  2076. }
  2077. }
  2078. class DataArrayTexture extends Texture {
  2079. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2080. super( null );
  2081. this.isDataArrayTexture = true;
  2082. this.image = { data, width, height, depth };
  2083. this.magFilter = NearestFilter;
  2084. this.minFilter = NearestFilter;
  2085. this.wrapR = ClampToEdgeWrapping;
  2086. this.generateMipmaps = false;
  2087. this.flipY = false;
  2088. this.unpackAlignment = 1;
  2089. }
  2090. }
  2091. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2092. constructor( width = 1, height = 1, depth = 1 ) {
  2093. super( width, height );
  2094. this.isWebGLArrayRenderTarget = true;
  2095. this.depth = depth;
  2096. this.texture = new DataArrayTexture( null, width, height, depth );
  2097. this.texture.isRenderTargetTexture = true;
  2098. }
  2099. }
  2100. class Data3DTexture extends Texture {
  2101. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2102. // We're going to add .setXXX() methods for setting properties later.
  2103. // Users can still set in DataTexture3D directly.
  2104. //
  2105. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2106. // texture.anisotropy = 16;
  2107. //
  2108. // See #14839
  2109. super( null );
  2110. this.isData3DTexture = true;
  2111. this.image = { data, width, height, depth };
  2112. this.magFilter = NearestFilter;
  2113. this.minFilter = NearestFilter;
  2114. this.wrapR = ClampToEdgeWrapping;
  2115. this.generateMipmaps = false;
  2116. this.flipY = false;
  2117. this.unpackAlignment = 1;
  2118. }
  2119. }
  2120. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2121. constructor( width = 1, height = 1, depth = 1 ) {
  2122. super( width, height );
  2123. this.isWebGL3DRenderTarget = true;
  2124. this.depth = depth;
  2125. this.texture = new Data3DTexture( null, width, height, depth );
  2126. this.texture.isRenderTargetTexture = true;
  2127. }
  2128. }
  2129. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2130. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2131. super( width, height, options );
  2132. this.isWebGLMultipleRenderTargets = true;
  2133. const texture = this.texture;
  2134. this.texture = [];
  2135. for ( let i = 0; i < count; i ++ ) {
  2136. this.texture[ i ] = texture.clone();
  2137. this.texture[ i ].isRenderTargetTexture = true;
  2138. }
  2139. }
  2140. setSize( width, height, depth = 1 ) {
  2141. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2142. this.width = width;
  2143. this.height = height;
  2144. this.depth = depth;
  2145. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2146. this.texture[ i ].image.width = width;
  2147. this.texture[ i ].image.height = height;
  2148. this.texture[ i ].image.depth = depth;
  2149. }
  2150. this.dispose();
  2151. }
  2152. this.viewport.set( 0, 0, width, height );
  2153. this.scissor.set( 0, 0, width, height );
  2154. return this;
  2155. }
  2156. copy( source ) {
  2157. this.dispose();
  2158. this.width = source.width;
  2159. this.height = source.height;
  2160. this.depth = source.depth;
  2161. this.viewport.set( 0, 0, this.width, this.height );
  2162. this.scissor.set( 0, 0, this.width, this.height );
  2163. this.depthBuffer = source.depthBuffer;
  2164. this.stencilBuffer = source.stencilBuffer;
  2165. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2166. this.texture.length = 0;
  2167. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2168. this.texture[ i ] = source.texture[ i ].clone();
  2169. this.texture[ i ].isRenderTargetTexture = true;
  2170. }
  2171. return this;
  2172. }
  2173. }
  2174. class Quaternion {
  2175. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2176. this.isQuaternion = true;
  2177. this._x = x;
  2178. this._y = y;
  2179. this._z = z;
  2180. this._w = w;
  2181. }
  2182. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2183. // fuzz-free, array-based Quaternion SLERP operation
  2184. let x0 = src0[ srcOffset0 + 0 ],
  2185. y0 = src0[ srcOffset0 + 1 ],
  2186. z0 = src0[ srcOffset0 + 2 ],
  2187. w0 = src0[ srcOffset0 + 3 ];
  2188. const x1 = src1[ srcOffset1 + 0 ],
  2189. y1 = src1[ srcOffset1 + 1 ],
  2190. z1 = src1[ srcOffset1 + 2 ],
  2191. w1 = src1[ srcOffset1 + 3 ];
  2192. if ( t === 0 ) {
  2193. dst[ dstOffset + 0 ] = x0;
  2194. dst[ dstOffset + 1 ] = y0;
  2195. dst[ dstOffset + 2 ] = z0;
  2196. dst[ dstOffset + 3 ] = w0;
  2197. return;
  2198. }
  2199. if ( t === 1 ) {
  2200. dst[ dstOffset + 0 ] = x1;
  2201. dst[ dstOffset + 1 ] = y1;
  2202. dst[ dstOffset + 2 ] = z1;
  2203. dst[ dstOffset + 3 ] = w1;
  2204. return;
  2205. }
  2206. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2207. let s = 1 - t;
  2208. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2209. dir = ( cos >= 0 ? 1 : - 1 ),
  2210. sqrSin = 1 - cos * cos;
  2211. // Skip the Slerp for tiny steps to avoid numeric problems:
  2212. if ( sqrSin > Number.EPSILON ) {
  2213. const sin = Math.sqrt( sqrSin ),
  2214. len = Math.atan2( sin, cos * dir );
  2215. s = Math.sin( s * len ) / sin;
  2216. t = Math.sin( t * len ) / sin;
  2217. }
  2218. const tDir = t * dir;
  2219. x0 = x0 * s + x1 * tDir;
  2220. y0 = y0 * s + y1 * tDir;
  2221. z0 = z0 * s + z1 * tDir;
  2222. w0 = w0 * s + w1 * tDir;
  2223. // Normalize in case we just did a lerp:
  2224. if ( s === 1 - t ) {
  2225. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2226. x0 *= f;
  2227. y0 *= f;
  2228. z0 *= f;
  2229. w0 *= f;
  2230. }
  2231. }
  2232. dst[ dstOffset ] = x0;
  2233. dst[ dstOffset + 1 ] = y0;
  2234. dst[ dstOffset + 2 ] = z0;
  2235. dst[ dstOffset + 3 ] = w0;
  2236. }
  2237. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2238. const x0 = src0[ srcOffset0 ];
  2239. const y0 = src0[ srcOffset0 + 1 ];
  2240. const z0 = src0[ srcOffset0 + 2 ];
  2241. const w0 = src0[ srcOffset0 + 3 ];
  2242. const x1 = src1[ srcOffset1 ];
  2243. const y1 = src1[ srcOffset1 + 1 ];
  2244. const z1 = src1[ srcOffset1 + 2 ];
  2245. const w1 = src1[ srcOffset1 + 3 ];
  2246. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2247. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2248. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2249. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2250. return dst;
  2251. }
  2252. get x() {
  2253. return this._x;
  2254. }
  2255. set x( value ) {
  2256. this._x = value;
  2257. this._onChangeCallback();
  2258. }
  2259. get y() {
  2260. return this._y;
  2261. }
  2262. set y( value ) {
  2263. this._y = value;
  2264. this._onChangeCallback();
  2265. }
  2266. get z() {
  2267. return this._z;
  2268. }
  2269. set z( value ) {
  2270. this._z = value;
  2271. this._onChangeCallback();
  2272. }
  2273. get w() {
  2274. return this._w;
  2275. }
  2276. set w( value ) {
  2277. this._w = value;
  2278. this._onChangeCallback();
  2279. }
  2280. set( x, y, z, w ) {
  2281. this._x = x;
  2282. this._y = y;
  2283. this._z = z;
  2284. this._w = w;
  2285. this._onChangeCallback();
  2286. return this;
  2287. }
  2288. clone() {
  2289. return new this.constructor( this._x, this._y, this._z, this._w );
  2290. }
  2291. copy( quaternion ) {
  2292. this._x = quaternion.x;
  2293. this._y = quaternion.y;
  2294. this._z = quaternion.z;
  2295. this._w = quaternion.w;
  2296. this._onChangeCallback();
  2297. return this;
  2298. }
  2299. setFromEuler( euler, update ) {
  2300. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2301. // http://www.mathworks.com/matlabcentral/fileexchange/
  2302. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2303. // content/SpinCalc.m
  2304. const cos = Math.cos;
  2305. const sin = Math.sin;
  2306. const c1 = cos( x / 2 );
  2307. const c2 = cos( y / 2 );
  2308. const c3 = cos( z / 2 );
  2309. const s1 = sin( x / 2 );
  2310. const s2 = sin( y / 2 );
  2311. const s3 = sin( z / 2 );
  2312. switch ( order ) {
  2313. case 'XYZ':
  2314. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2315. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2316. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2317. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2318. break;
  2319. case 'YXZ':
  2320. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2321. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2322. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2323. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2324. break;
  2325. case 'ZXY':
  2326. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2327. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2328. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2329. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2330. break;
  2331. case 'ZYX':
  2332. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2333. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2334. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2335. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2336. break;
  2337. case 'YZX':
  2338. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2339. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2340. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2341. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2342. break;
  2343. case 'XZY':
  2344. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2345. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2346. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2347. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2348. break;
  2349. default:
  2350. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2351. }
  2352. if ( update !== false ) this._onChangeCallback();
  2353. return this;
  2354. }
  2355. setFromAxisAngle( axis, angle ) {
  2356. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2357. // assumes axis is normalized
  2358. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2359. this._x = axis.x * s;
  2360. this._y = axis.y * s;
  2361. this._z = axis.z * s;
  2362. this._w = Math.cos( halfAngle );
  2363. this._onChangeCallback();
  2364. return this;
  2365. }
  2366. setFromRotationMatrix( m ) {
  2367. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2368. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2369. const te = m.elements,
  2370. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2371. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2372. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2373. trace = m11 + m22 + m33;
  2374. if ( trace > 0 ) {
  2375. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2376. this._w = 0.25 / s;
  2377. this._x = ( m32 - m23 ) * s;
  2378. this._y = ( m13 - m31 ) * s;
  2379. this._z = ( m21 - m12 ) * s;
  2380. } else if ( m11 > m22 && m11 > m33 ) {
  2381. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2382. this._w = ( m32 - m23 ) / s;
  2383. this._x = 0.25 * s;
  2384. this._y = ( m12 + m21 ) / s;
  2385. this._z = ( m13 + m31 ) / s;
  2386. } else if ( m22 > m33 ) {
  2387. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2388. this._w = ( m13 - m31 ) / s;
  2389. this._x = ( m12 + m21 ) / s;
  2390. this._y = 0.25 * s;
  2391. this._z = ( m23 + m32 ) / s;
  2392. } else {
  2393. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2394. this._w = ( m21 - m12 ) / s;
  2395. this._x = ( m13 + m31 ) / s;
  2396. this._y = ( m23 + m32 ) / s;
  2397. this._z = 0.25 * s;
  2398. }
  2399. this._onChangeCallback();
  2400. return this;
  2401. }
  2402. setFromUnitVectors( vFrom, vTo ) {
  2403. // assumes direction vectors vFrom and vTo are normalized
  2404. let r = vFrom.dot( vTo ) + 1;
  2405. if ( r < Number.EPSILON ) {
  2406. // vFrom and vTo point in opposite directions
  2407. r = 0;
  2408. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2409. this._x = - vFrom.y;
  2410. this._y = vFrom.x;
  2411. this._z = 0;
  2412. this._w = r;
  2413. } else {
  2414. this._x = 0;
  2415. this._y = - vFrom.z;
  2416. this._z = vFrom.y;
  2417. this._w = r;
  2418. }
  2419. } else {
  2420. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2421. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2422. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2423. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2424. this._w = r;
  2425. }
  2426. return this.normalize();
  2427. }
  2428. angleTo( q ) {
  2429. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2430. }
  2431. rotateTowards( q, step ) {
  2432. const angle = this.angleTo( q );
  2433. if ( angle === 0 ) return this;
  2434. const t = Math.min( 1, step / angle );
  2435. this.slerp( q, t );
  2436. return this;
  2437. }
  2438. identity() {
  2439. return this.set( 0, 0, 0, 1 );
  2440. }
  2441. invert() {
  2442. // quaternion is assumed to have unit length
  2443. return this.conjugate();
  2444. }
  2445. conjugate() {
  2446. this._x *= - 1;
  2447. this._y *= - 1;
  2448. this._z *= - 1;
  2449. this._onChangeCallback();
  2450. return this;
  2451. }
  2452. dot( v ) {
  2453. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2454. }
  2455. lengthSq() {
  2456. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2457. }
  2458. length() {
  2459. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2460. }
  2461. normalize() {
  2462. let l = this.length();
  2463. if ( l === 0 ) {
  2464. this._x = 0;
  2465. this._y = 0;
  2466. this._z = 0;
  2467. this._w = 1;
  2468. } else {
  2469. l = 1 / l;
  2470. this._x = this._x * l;
  2471. this._y = this._y * l;
  2472. this._z = this._z * l;
  2473. this._w = this._w * l;
  2474. }
  2475. this._onChangeCallback();
  2476. return this;
  2477. }
  2478. multiply( q ) {
  2479. return this.multiplyQuaternions( this, q );
  2480. }
  2481. premultiply( q ) {
  2482. return this.multiplyQuaternions( q, this );
  2483. }
  2484. multiplyQuaternions( a, b ) {
  2485. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2486. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2487. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2488. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2489. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2490. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2491. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2492. this._onChangeCallback();
  2493. return this;
  2494. }
  2495. slerp( qb, t ) {
  2496. if ( t === 0 ) return this;
  2497. if ( t === 1 ) return this.copy( qb );
  2498. const x = this._x, y = this._y, z = this._z, w = this._w;
  2499. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2500. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2501. if ( cosHalfTheta < 0 ) {
  2502. this._w = - qb._w;
  2503. this._x = - qb._x;
  2504. this._y = - qb._y;
  2505. this._z = - qb._z;
  2506. cosHalfTheta = - cosHalfTheta;
  2507. } else {
  2508. this.copy( qb );
  2509. }
  2510. if ( cosHalfTheta >= 1.0 ) {
  2511. this._w = w;
  2512. this._x = x;
  2513. this._y = y;
  2514. this._z = z;
  2515. return this;
  2516. }
  2517. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2518. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2519. const s = 1 - t;
  2520. this._w = s * w + t * this._w;
  2521. this._x = s * x + t * this._x;
  2522. this._y = s * y + t * this._y;
  2523. this._z = s * z + t * this._z;
  2524. this.normalize();
  2525. this._onChangeCallback();
  2526. return this;
  2527. }
  2528. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2529. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2530. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2531. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2532. this._w = ( w * ratioA + this._w * ratioB );
  2533. this._x = ( x * ratioA + this._x * ratioB );
  2534. this._y = ( y * ratioA + this._y * ratioB );
  2535. this._z = ( z * ratioA + this._z * ratioB );
  2536. this._onChangeCallback();
  2537. return this;
  2538. }
  2539. slerpQuaternions( qa, qb, t ) {
  2540. return this.copy( qa ).slerp( qb, t );
  2541. }
  2542. random() {
  2543. // Derived from http://planning.cs.uiuc.edu/node198.html
  2544. // Note, this source uses w, x, y, z ordering,
  2545. // so we swap the order below.
  2546. const u1 = Math.random();
  2547. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2548. const sqrtu1 = Math.sqrt( u1 );
  2549. const u2 = 2 * Math.PI * Math.random();
  2550. const u3 = 2 * Math.PI * Math.random();
  2551. return this.set(
  2552. sqrt1u1 * Math.cos( u2 ),
  2553. sqrtu1 * Math.sin( u3 ),
  2554. sqrtu1 * Math.cos( u3 ),
  2555. sqrt1u1 * Math.sin( u2 ),
  2556. );
  2557. }
  2558. equals( quaternion ) {
  2559. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2560. }
  2561. fromArray( array, offset = 0 ) {
  2562. this._x = array[ offset ];
  2563. this._y = array[ offset + 1 ];
  2564. this._z = array[ offset + 2 ];
  2565. this._w = array[ offset + 3 ];
  2566. this._onChangeCallback();
  2567. return this;
  2568. }
  2569. toArray( array = [], offset = 0 ) {
  2570. array[ offset ] = this._x;
  2571. array[ offset + 1 ] = this._y;
  2572. array[ offset + 2 ] = this._z;
  2573. array[ offset + 3 ] = this._w;
  2574. return array;
  2575. }
  2576. fromBufferAttribute( attribute, index ) {
  2577. this._x = attribute.getX( index );
  2578. this._y = attribute.getY( index );
  2579. this._z = attribute.getZ( index );
  2580. this._w = attribute.getW( index );
  2581. return this;
  2582. }
  2583. _onChange( callback ) {
  2584. this._onChangeCallback = callback;
  2585. return this;
  2586. }
  2587. _onChangeCallback() {}
  2588. *[ Symbol.iterator ]() {
  2589. yield this._x;
  2590. yield this._y;
  2591. yield this._z;
  2592. yield this._w;
  2593. }
  2594. }
  2595. class Vector3 {
  2596. constructor( x = 0, y = 0, z = 0 ) {
  2597. Vector3.prototype.isVector3 = true;
  2598. this.x = x;
  2599. this.y = y;
  2600. this.z = z;
  2601. }
  2602. set( x, y, z ) {
  2603. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2604. this.x = x;
  2605. this.y = y;
  2606. this.z = z;
  2607. return this;
  2608. }
  2609. setScalar( scalar ) {
  2610. this.x = scalar;
  2611. this.y = scalar;
  2612. this.z = scalar;
  2613. return this;
  2614. }
  2615. setX( x ) {
  2616. this.x = x;
  2617. return this;
  2618. }
  2619. setY( y ) {
  2620. this.y = y;
  2621. return this;
  2622. }
  2623. setZ( z ) {
  2624. this.z = z;
  2625. return this;
  2626. }
  2627. setComponent( index, value ) {
  2628. switch ( index ) {
  2629. case 0: this.x = value; break;
  2630. case 1: this.y = value; break;
  2631. case 2: this.z = value; break;
  2632. default: throw new Error( 'index is out of range: ' + index );
  2633. }
  2634. return this;
  2635. }
  2636. getComponent( index ) {
  2637. switch ( index ) {
  2638. case 0: return this.x;
  2639. case 1: return this.y;
  2640. case 2: return this.z;
  2641. default: throw new Error( 'index is out of range: ' + index );
  2642. }
  2643. }
  2644. clone() {
  2645. return new this.constructor( this.x, this.y, this.z );
  2646. }
  2647. copy( v ) {
  2648. this.x = v.x;
  2649. this.y = v.y;
  2650. this.z = v.z;
  2651. return this;
  2652. }
  2653. add( v ) {
  2654. this.x += v.x;
  2655. this.y += v.y;
  2656. this.z += v.z;
  2657. return this;
  2658. }
  2659. addScalar( s ) {
  2660. this.x += s;
  2661. this.y += s;
  2662. this.z += s;
  2663. return this;
  2664. }
  2665. addVectors( a, b ) {
  2666. this.x = a.x + b.x;
  2667. this.y = a.y + b.y;
  2668. this.z = a.z + b.z;
  2669. return this;
  2670. }
  2671. addScaledVector( v, s ) {
  2672. this.x += v.x * s;
  2673. this.y += v.y * s;
  2674. this.z += v.z * s;
  2675. return this;
  2676. }
  2677. sub( v ) {
  2678. this.x -= v.x;
  2679. this.y -= v.y;
  2680. this.z -= v.z;
  2681. return this;
  2682. }
  2683. subScalar( s ) {
  2684. this.x -= s;
  2685. this.y -= s;
  2686. this.z -= s;
  2687. return this;
  2688. }
  2689. subVectors( a, b ) {
  2690. this.x = a.x - b.x;
  2691. this.y = a.y - b.y;
  2692. this.z = a.z - b.z;
  2693. return this;
  2694. }
  2695. multiply( v ) {
  2696. this.x *= v.x;
  2697. this.y *= v.y;
  2698. this.z *= v.z;
  2699. return this;
  2700. }
  2701. multiplyScalar( scalar ) {
  2702. this.x *= scalar;
  2703. this.y *= scalar;
  2704. this.z *= scalar;
  2705. return this;
  2706. }
  2707. multiplyVectors( a, b ) {
  2708. this.x = a.x * b.x;
  2709. this.y = a.y * b.y;
  2710. this.z = a.z * b.z;
  2711. return this;
  2712. }
  2713. applyEuler( euler ) {
  2714. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2715. }
  2716. applyAxisAngle( axis, angle ) {
  2717. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2718. }
  2719. applyMatrix3( m ) {
  2720. const x = this.x, y = this.y, z = this.z;
  2721. const e = m.elements;
  2722. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2723. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2724. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2725. return this;
  2726. }
  2727. applyNormalMatrix( m ) {
  2728. return this.applyMatrix3( m ).normalize();
  2729. }
  2730. applyMatrix4( m ) {
  2731. const x = this.x, y = this.y, z = this.z;
  2732. const e = m.elements;
  2733. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2734. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2735. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2736. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2737. return this;
  2738. }
  2739. applyQuaternion( q ) {
  2740. const x = this.x, y = this.y, z = this.z;
  2741. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2742. // calculate quat * vector
  2743. const ix = qw * x + qy * z - qz * y;
  2744. const iy = qw * y + qz * x - qx * z;
  2745. const iz = qw * z + qx * y - qy * x;
  2746. const iw = - qx * x - qy * y - qz * z;
  2747. // calculate result * inverse quat
  2748. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2749. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2750. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2751. return this;
  2752. }
  2753. project( camera ) {
  2754. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2755. }
  2756. unproject( camera ) {
  2757. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2758. }
  2759. transformDirection( m ) {
  2760. // input: THREE.Matrix4 affine matrix
  2761. // vector interpreted as a direction
  2762. const x = this.x, y = this.y, z = this.z;
  2763. const e = m.elements;
  2764. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2765. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2766. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2767. return this.normalize();
  2768. }
  2769. divide( v ) {
  2770. this.x /= v.x;
  2771. this.y /= v.y;
  2772. this.z /= v.z;
  2773. return this;
  2774. }
  2775. divideScalar( scalar ) {
  2776. return this.multiplyScalar( 1 / scalar );
  2777. }
  2778. min( v ) {
  2779. this.x = Math.min( this.x, v.x );
  2780. this.y = Math.min( this.y, v.y );
  2781. this.z = Math.min( this.z, v.z );
  2782. return this;
  2783. }
  2784. max( v ) {
  2785. this.x = Math.max( this.x, v.x );
  2786. this.y = Math.max( this.y, v.y );
  2787. this.z = Math.max( this.z, v.z );
  2788. return this;
  2789. }
  2790. clamp( min, max ) {
  2791. // assumes min < max, componentwise
  2792. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2793. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2794. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2795. return this;
  2796. }
  2797. clampScalar( minVal, maxVal ) {
  2798. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2799. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2800. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2801. return this;
  2802. }
  2803. clampLength( min, max ) {
  2804. const length = this.length();
  2805. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2806. }
  2807. floor() {
  2808. this.x = Math.floor( this.x );
  2809. this.y = Math.floor( this.y );
  2810. this.z = Math.floor( this.z );
  2811. return this;
  2812. }
  2813. ceil() {
  2814. this.x = Math.ceil( this.x );
  2815. this.y = Math.ceil( this.y );
  2816. this.z = Math.ceil( this.z );
  2817. return this;
  2818. }
  2819. round() {
  2820. this.x = Math.round( this.x );
  2821. this.y = Math.round( this.y );
  2822. this.z = Math.round( this.z );
  2823. return this;
  2824. }
  2825. roundToZero() {
  2826. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2827. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2828. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2829. return this;
  2830. }
  2831. negate() {
  2832. this.x = - this.x;
  2833. this.y = - this.y;
  2834. this.z = - this.z;
  2835. return this;
  2836. }
  2837. dot( v ) {
  2838. return this.x * v.x + this.y * v.y + this.z * v.z;
  2839. }
  2840. // TODO lengthSquared?
  2841. lengthSq() {
  2842. return this.x * this.x + this.y * this.y + this.z * this.z;
  2843. }
  2844. length() {
  2845. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2846. }
  2847. manhattanLength() {
  2848. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2849. }
  2850. normalize() {
  2851. return this.divideScalar( this.length() || 1 );
  2852. }
  2853. setLength( length ) {
  2854. return this.normalize().multiplyScalar( length );
  2855. }
  2856. lerp( v, alpha ) {
  2857. this.x += ( v.x - this.x ) * alpha;
  2858. this.y += ( v.y - this.y ) * alpha;
  2859. this.z += ( v.z - this.z ) * alpha;
  2860. return this;
  2861. }
  2862. lerpVectors( v1, v2, alpha ) {
  2863. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2864. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2865. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2866. return this;
  2867. }
  2868. cross( v ) {
  2869. return this.crossVectors( this, v );
  2870. }
  2871. crossVectors( a, b ) {
  2872. const ax = a.x, ay = a.y, az = a.z;
  2873. const bx = b.x, by = b.y, bz = b.z;
  2874. this.x = ay * bz - az * by;
  2875. this.y = az * bx - ax * bz;
  2876. this.z = ax * by - ay * bx;
  2877. return this;
  2878. }
  2879. projectOnVector( v ) {
  2880. const denominator = v.lengthSq();
  2881. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2882. const scalar = v.dot( this ) / denominator;
  2883. return this.copy( v ).multiplyScalar( scalar );
  2884. }
  2885. projectOnPlane( planeNormal ) {
  2886. _vector$c.copy( this ).projectOnVector( planeNormal );
  2887. return this.sub( _vector$c );
  2888. }
  2889. reflect( normal ) {
  2890. // reflect incident vector off plane orthogonal to normal
  2891. // normal is assumed to have unit length
  2892. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2893. }
  2894. angleTo( v ) {
  2895. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2896. if ( denominator === 0 ) return Math.PI / 2;
  2897. const theta = this.dot( v ) / denominator;
  2898. // clamp, to handle numerical problems
  2899. return Math.acos( clamp( theta, - 1, 1 ) );
  2900. }
  2901. distanceTo( v ) {
  2902. return Math.sqrt( this.distanceToSquared( v ) );
  2903. }
  2904. distanceToSquared( v ) {
  2905. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2906. return dx * dx + dy * dy + dz * dz;
  2907. }
  2908. manhattanDistanceTo( v ) {
  2909. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2910. }
  2911. setFromSpherical( s ) {
  2912. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2913. }
  2914. setFromSphericalCoords( radius, phi, theta ) {
  2915. const sinPhiRadius = Math.sin( phi ) * radius;
  2916. this.x = sinPhiRadius * Math.sin( theta );
  2917. this.y = Math.cos( phi ) * radius;
  2918. this.z = sinPhiRadius * Math.cos( theta );
  2919. return this;
  2920. }
  2921. setFromCylindrical( c ) {
  2922. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2923. }
  2924. setFromCylindricalCoords( radius, theta, y ) {
  2925. this.x = radius * Math.sin( theta );
  2926. this.y = y;
  2927. this.z = radius * Math.cos( theta );
  2928. return this;
  2929. }
  2930. setFromMatrixPosition( m ) {
  2931. const e = m.elements;
  2932. this.x = e[ 12 ];
  2933. this.y = e[ 13 ];
  2934. this.z = e[ 14 ];
  2935. return this;
  2936. }
  2937. setFromMatrixScale( m ) {
  2938. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2939. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2940. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2941. this.x = sx;
  2942. this.y = sy;
  2943. this.z = sz;
  2944. return this;
  2945. }
  2946. setFromMatrixColumn( m, index ) {
  2947. return this.fromArray( m.elements, index * 4 );
  2948. }
  2949. setFromMatrix3Column( m, index ) {
  2950. return this.fromArray( m.elements, index * 3 );
  2951. }
  2952. setFromEuler( e ) {
  2953. this.x = e._x;
  2954. this.y = e._y;
  2955. this.z = e._z;
  2956. return this;
  2957. }
  2958. equals( v ) {
  2959. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2960. }
  2961. fromArray( array, offset = 0 ) {
  2962. this.x = array[ offset ];
  2963. this.y = array[ offset + 1 ];
  2964. this.z = array[ offset + 2 ];
  2965. return this;
  2966. }
  2967. toArray( array = [], offset = 0 ) {
  2968. array[ offset ] = this.x;
  2969. array[ offset + 1 ] = this.y;
  2970. array[ offset + 2 ] = this.z;
  2971. return array;
  2972. }
  2973. fromBufferAttribute( attribute, index ) {
  2974. this.x = attribute.getX( index );
  2975. this.y = attribute.getY( index );
  2976. this.z = attribute.getZ( index );
  2977. return this;
  2978. }
  2979. random() {
  2980. this.x = Math.random();
  2981. this.y = Math.random();
  2982. this.z = Math.random();
  2983. return this;
  2984. }
  2985. randomDirection() {
  2986. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2987. const u = ( Math.random() - 0.5 ) * 2;
  2988. const t = Math.random() * Math.PI * 2;
  2989. const f = Math.sqrt( 1 - u ** 2 );
  2990. this.x = f * Math.cos( t );
  2991. this.y = f * Math.sin( t );
  2992. this.z = u;
  2993. return this;
  2994. }
  2995. *[ Symbol.iterator ]() {
  2996. yield this.x;
  2997. yield this.y;
  2998. yield this.z;
  2999. }
  3000. }
  3001. const _vector$c = /*@__PURE__*/ new Vector3();
  3002. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3003. class Box3 {
  3004. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3005. this.isBox3 = true;
  3006. this.min = min;
  3007. this.max = max;
  3008. }
  3009. set( min, max ) {
  3010. this.min.copy( min );
  3011. this.max.copy( max );
  3012. return this;
  3013. }
  3014. setFromArray( array ) {
  3015. let minX = + Infinity;
  3016. let minY = + Infinity;
  3017. let minZ = + Infinity;
  3018. let maxX = - Infinity;
  3019. let maxY = - Infinity;
  3020. let maxZ = - Infinity;
  3021. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3022. const x = array[ i ];
  3023. const y = array[ i + 1 ];
  3024. const z = array[ i + 2 ];
  3025. if ( x < minX ) minX = x;
  3026. if ( y < minY ) minY = y;
  3027. if ( z < minZ ) minZ = z;
  3028. if ( x > maxX ) maxX = x;
  3029. if ( y > maxY ) maxY = y;
  3030. if ( z > maxZ ) maxZ = z;
  3031. }
  3032. this.min.set( minX, minY, minZ );
  3033. this.max.set( maxX, maxY, maxZ );
  3034. return this;
  3035. }
  3036. setFromBufferAttribute( attribute ) {
  3037. let minX = + Infinity;
  3038. let minY = + Infinity;
  3039. let minZ = + Infinity;
  3040. let maxX = - Infinity;
  3041. let maxY = - Infinity;
  3042. let maxZ = - Infinity;
  3043. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3044. const x = attribute.getX( i );
  3045. const y = attribute.getY( i );
  3046. const z = attribute.getZ( i );
  3047. if ( x < minX ) minX = x;
  3048. if ( y < minY ) minY = y;
  3049. if ( z < minZ ) minZ = z;
  3050. if ( x > maxX ) maxX = x;
  3051. if ( y > maxY ) maxY = y;
  3052. if ( z > maxZ ) maxZ = z;
  3053. }
  3054. this.min.set( minX, minY, minZ );
  3055. this.max.set( maxX, maxY, maxZ );
  3056. return this;
  3057. }
  3058. setFromPoints( points ) {
  3059. this.makeEmpty();
  3060. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3061. this.expandByPoint( points[ i ] );
  3062. }
  3063. return this;
  3064. }
  3065. setFromCenterAndSize( center, size ) {
  3066. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3067. this.min.copy( center ).sub( halfSize );
  3068. this.max.copy( center ).add( halfSize );
  3069. return this;
  3070. }
  3071. setFromObject( object, precise = false ) {
  3072. this.makeEmpty();
  3073. return this.expandByObject( object, precise );
  3074. }
  3075. clone() {
  3076. return new this.constructor().copy( this );
  3077. }
  3078. copy( box ) {
  3079. this.min.copy( box.min );
  3080. this.max.copy( box.max );
  3081. return this;
  3082. }
  3083. makeEmpty() {
  3084. this.min.x = this.min.y = this.min.z = + Infinity;
  3085. this.max.x = this.max.y = this.max.z = - Infinity;
  3086. return this;
  3087. }
  3088. isEmpty() {
  3089. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3090. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3091. }
  3092. getCenter( target ) {
  3093. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3094. }
  3095. getSize( target ) {
  3096. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3097. }
  3098. expandByPoint( point ) {
  3099. this.min.min( point );
  3100. this.max.max( point );
  3101. return this;
  3102. }
  3103. expandByVector( vector ) {
  3104. this.min.sub( vector );
  3105. this.max.add( vector );
  3106. return this;
  3107. }
  3108. expandByScalar( scalar ) {
  3109. this.min.addScalar( - scalar );
  3110. this.max.addScalar( scalar );
  3111. return this;
  3112. }
  3113. expandByObject( object, precise = false ) {
  3114. // Computes the world-axis-aligned bounding box of an object (including its children),
  3115. // accounting for both the object's, and children's, world transforms
  3116. object.updateWorldMatrix( false, false );
  3117. const geometry = object.geometry;
  3118. if ( geometry !== undefined ) {
  3119. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3120. const position = geometry.attributes.position;
  3121. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3122. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3123. this.expandByPoint( _vector$b );
  3124. }
  3125. } else {
  3126. if ( geometry.boundingBox === null ) {
  3127. geometry.computeBoundingBox();
  3128. }
  3129. _box$3.copy( geometry.boundingBox );
  3130. _box$3.applyMatrix4( object.matrixWorld );
  3131. this.union( _box$3 );
  3132. }
  3133. }
  3134. const children = object.children;
  3135. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3136. this.expandByObject( children[ i ], precise );
  3137. }
  3138. return this;
  3139. }
  3140. containsPoint( point ) {
  3141. return point.x < this.min.x || point.x > this.max.x ||
  3142. point.y < this.min.y || point.y > this.max.y ||
  3143. point.z < this.min.z || point.z > this.max.z ? false : true;
  3144. }
  3145. containsBox( box ) {
  3146. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3147. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3148. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3149. }
  3150. getParameter( point, target ) {
  3151. // This can potentially have a divide by zero if the box
  3152. // has a size dimension of 0.
  3153. return target.set(
  3154. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3155. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3156. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3157. );
  3158. }
  3159. intersectsBox( box ) {
  3160. // using 6 splitting planes to rule out intersections.
  3161. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3162. box.max.y < this.min.y || box.min.y > this.max.y ||
  3163. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3164. }
  3165. intersectsSphere( sphere ) {
  3166. // Find the point on the AABB closest to the sphere center.
  3167. this.clampPoint( sphere.center, _vector$b );
  3168. // If that point is inside the sphere, the AABB and sphere intersect.
  3169. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3170. }
  3171. intersectsPlane( plane ) {
  3172. // We compute the minimum and maximum dot product values. If those values
  3173. // are on the same side (back or front) of the plane, then there is no intersection.
  3174. let min, max;
  3175. if ( plane.normal.x > 0 ) {
  3176. min = plane.normal.x * this.min.x;
  3177. max = plane.normal.x * this.max.x;
  3178. } else {
  3179. min = plane.normal.x * this.max.x;
  3180. max = plane.normal.x * this.min.x;
  3181. }
  3182. if ( plane.normal.y > 0 ) {
  3183. min += plane.normal.y * this.min.y;
  3184. max += plane.normal.y * this.max.y;
  3185. } else {
  3186. min += plane.normal.y * this.max.y;
  3187. max += plane.normal.y * this.min.y;
  3188. }
  3189. if ( plane.normal.z > 0 ) {
  3190. min += plane.normal.z * this.min.z;
  3191. max += plane.normal.z * this.max.z;
  3192. } else {
  3193. min += plane.normal.z * this.max.z;
  3194. max += plane.normal.z * this.min.z;
  3195. }
  3196. return ( min <= - plane.constant && max >= - plane.constant );
  3197. }
  3198. intersectsTriangle( triangle ) {
  3199. if ( this.isEmpty() ) {
  3200. return false;
  3201. }
  3202. // compute box center and extents
  3203. this.getCenter( _center );
  3204. _extents.subVectors( this.max, _center );
  3205. // translate triangle to aabb origin
  3206. _v0$2.subVectors( triangle.a, _center );
  3207. _v1$7.subVectors( triangle.b, _center );
  3208. _v2$4.subVectors( triangle.c, _center );
  3209. // compute edge vectors for triangle
  3210. _f0.subVectors( _v1$7, _v0$2 );
  3211. _f1.subVectors( _v2$4, _v1$7 );
  3212. _f2.subVectors( _v0$2, _v2$4 );
  3213. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3214. // 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
  3215. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3216. let axes = [
  3217. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3218. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3219. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3220. ];
  3221. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3222. return false;
  3223. }
  3224. // test 3 face normals from the aabb
  3225. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3226. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3227. return false;
  3228. }
  3229. // finally testing the face normal of the triangle
  3230. // use already existing triangle edge vectors here
  3231. _triangleNormal.crossVectors( _f0, _f1 );
  3232. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3233. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3234. }
  3235. clampPoint( point, target ) {
  3236. return target.copy( point ).clamp( this.min, this.max );
  3237. }
  3238. distanceToPoint( point ) {
  3239. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3240. return clampedPoint.sub( point ).length();
  3241. }
  3242. getBoundingSphere( target ) {
  3243. this.getCenter( target.center );
  3244. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3245. return target;
  3246. }
  3247. intersect( box ) {
  3248. this.min.max( box.min );
  3249. this.max.min( box.max );
  3250. // 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.
  3251. if ( this.isEmpty() ) this.makeEmpty();
  3252. return this;
  3253. }
  3254. union( box ) {
  3255. this.min.min( box.min );
  3256. this.max.max( box.max );
  3257. return this;
  3258. }
  3259. applyMatrix4( matrix ) {
  3260. // transform of empty box is an empty box.
  3261. if ( this.isEmpty() ) return this;
  3262. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3263. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3264. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3265. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3266. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3267. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3268. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3269. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3270. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3271. this.setFromPoints( _points );
  3272. return this;
  3273. }
  3274. translate( offset ) {
  3275. this.min.add( offset );
  3276. this.max.add( offset );
  3277. return this;
  3278. }
  3279. equals( box ) {
  3280. return box.min.equals( this.min ) && box.max.equals( this.max );
  3281. }
  3282. }
  3283. const _points = [
  3284. /*@__PURE__*/ new Vector3(),
  3285. /*@__PURE__*/ new Vector3(),
  3286. /*@__PURE__*/ new Vector3(),
  3287. /*@__PURE__*/ new Vector3(),
  3288. /*@__PURE__*/ new Vector3(),
  3289. /*@__PURE__*/ new Vector3(),
  3290. /*@__PURE__*/ new Vector3(),
  3291. /*@__PURE__*/ new Vector3()
  3292. ];
  3293. const _vector$b = /*@__PURE__*/ new Vector3();
  3294. const _box$3 = /*@__PURE__*/ new Box3();
  3295. // triangle centered vertices
  3296. const _v0$2 = /*@__PURE__*/ new Vector3();
  3297. const _v1$7 = /*@__PURE__*/ new Vector3();
  3298. const _v2$4 = /*@__PURE__*/ new Vector3();
  3299. // triangle edge vectors
  3300. const _f0 = /*@__PURE__*/ new Vector3();
  3301. const _f1 = /*@__PURE__*/ new Vector3();
  3302. const _f2 = /*@__PURE__*/ new Vector3();
  3303. const _center = /*@__PURE__*/ new Vector3();
  3304. const _extents = /*@__PURE__*/ new Vector3();
  3305. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3306. const _testAxis = /*@__PURE__*/ new Vector3();
  3307. function satForAxes( axes, v0, v1, v2, extents ) {
  3308. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3309. _testAxis.fromArray( axes, i );
  3310. // project the aabb onto the separating axis
  3311. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3312. // project all 3 vertices of the triangle onto the separating axis
  3313. const p0 = v0.dot( _testAxis );
  3314. const p1 = v1.dot( _testAxis );
  3315. const p2 = v2.dot( _testAxis );
  3316. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3317. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3318. // points of the projected triangle are outside the projected half-length of the aabb
  3319. // the axis is separating and we can exit
  3320. return false;
  3321. }
  3322. }
  3323. return true;
  3324. }
  3325. const _box$2 = /*@__PURE__*/ new Box3();
  3326. const _v1$6 = /*@__PURE__*/ new Vector3();
  3327. const _v2$3 = /*@__PURE__*/ new Vector3();
  3328. class Sphere {
  3329. constructor( center = new Vector3(), radius = - 1 ) {
  3330. this.center = center;
  3331. this.radius = radius;
  3332. }
  3333. set( center, radius ) {
  3334. this.center.copy( center );
  3335. this.radius = radius;
  3336. return this;
  3337. }
  3338. setFromPoints( points, optionalCenter ) {
  3339. const center = this.center;
  3340. if ( optionalCenter !== undefined ) {
  3341. center.copy( optionalCenter );
  3342. } else {
  3343. _box$2.setFromPoints( points ).getCenter( center );
  3344. }
  3345. let maxRadiusSq = 0;
  3346. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3347. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3348. }
  3349. this.radius = Math.sqrt( maxRadiusSq );
  3350. return this;
  3351. }
  3352. copy( sphere ) {
  3353. this.center.copy( sphere.center );
  3354. this.radius = sphere.radius;
  3355. return this;
  3356. }
  3357. isEmpty() {
  3358. return ( this.radius < 0 );
  3359. }
  3360. makeEmpty() {
  3361. this.center.set( 0, 0, 0 );
  3362. this.radius = - 1;
  3363. return this;
  3364. }
  3365. containsPoint( point ) {
  3366. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3367. }
  3368. distanceToPoint( point ) {
  3369. return ( point.distanceTo( this.center ) - this.radius );
  3370. }
  3371. intersectsSphere( sphere ) {
  3372. const radiusSum = this.radius + sphere.radius;
  3373. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3374. }
  3375. intersectsBox( box ) {
  3376. return box.intersectsSphere( this );
  3377. }
  3378. intersectsPlane( plane ) {
  3379. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3380. }
  3381. clampPoint( point, target ) {
  3382. const deltaLengthSq = this.center.distanceToSquared( point );
  3383. target.copy( point );
  3384. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3385. target.sub( this.center ).normalize();
  3386. target.multiplyScalar( this.radius ).add( this.center );
  3387. }
  3388. return target;
  3389. }
  3390. getBoundingBox( target ) {
  3391. if ( this.isEmpty() ) {
  3392. // Empty sphere produces empty bounding box
  3393. target.makeEmpty();
  3394. return target;
  3395. }
  3396. target.set( this.center, this.center );
  3397. target.expandByScalar( this.radius );
  3398. return target;
  3399. }
  3400. applyMatrix4( matrix ) {
  3401. this.center.applyMatrix4( matrix );
  3402. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3403. return this;
  3404. }
  3405. translate( offset ) {
  3406. this.center.add( offset );
  3407. return this;
  3408. }
  3409. expandByPoint( point ) {
  3410. if ( this.isEmpty() ) {
  3411. this.center.copy( point );
  3412. this.radius = 0;
  3413. return this;
  3414. }
  3415. _v1$6.subVectors( point, this.center );
  3416. const lengthSq = _v1$6.lengthSq();
  3417. if ( lengthSq > ( this.radius * this.radius ) ) {
  3418. // calculate the minimal sphere
  3419. const length = Math.sqrt( lengthSq );
  3420. const delta = ( length - this.radius ) * 0.5;
  3421. this.center.addScaledVector( _v1$6, delta / length );
  3422. this.radius += delta;
  3423. }
  3424. return this;
  3425. }
  3426. union( sphere ) {
  3427. if ( sphere.isEmpty() ) {
  3428. return this;
  3429. }
  3430. if ( this.isEmpty() ) {
  3431. this.copy( sphere );
  3432. return this;
  3433. }
  3434. if ( this.center.equals( sphere.center ) === true ) {
  3435. this.radius = Math.max( this.radius, sphere.radius );
  3436. } else {
  3437. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3438. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3439. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3440. }
  3441. return this;
  3442. }
  3443. equals( sphere ) {
  3444. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3445. }
  3446. clone() {
  3447. return new this.constructor().copy( this );
  3448. }
  3449. }
  3450. const _vector$a = /*@__PURE__*/ new Vector3();
  3451. const _segCenter = /*@__PURE__*/ new Vector3();
  3452. const _segDir = /*@__PURE__*/ new Vector3();
  3453. const _diff = /*@__PURE__*/ new Vector3();
  3454. const _edge1 = /*@__PURE__*/ new Vector3();
  3455. const _edge2 = /*@__PURE__*/ new Vector3();
  3456. const _normal$1 = /*@__PURE__*/ new Vector3();
  3457. class Ray {
  3458. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3459. this.origin = origin;
  3460. this.direction = direction;
  3461. }
  3462. set( origin, direction ) {
  3463. this.origin.copy( origin );
  3464. this.direction.copy( direction );
  3465. return this;
  3466. }
  3467. copy( ray ) {
  3468. this.origin.copy( ray.origin );
  3469. this.direction.copy( ray.direction );
  3470. return this;
  3471. }
  3472. at( t, target ) {
  3473. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3474. }
  3475. lookAt( v ) {
  3476. this.direction.copy( v ).sub( this.origin ).normalize();
  3477. return this;
  3478. }
  3479. recast( t ) {
  3480. this.origin.copy( this.at( t, _vector$a ) );
  3481. return this;
  3482. }
  3483. closestPointToPoint( point, target ) {
  3484. target.subVectors( point, this.origin );
  3485. const directionDistance = target.dot( this.direction );
  3486. if ( directionDistance < 0 ) {
  3487. return target.copy( this.origin );
  3488. }
  3489. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3490. }
  3491. distanceToPoint( point ) {
  3492. return Math.sqrt( this.distanceSqToPoint( point ) );
  3493. }
  3494. distanceSqToPoint( point ) {
  3495. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3496. // point behind the ray
  3497. if ( directionDistance < 0 ) {
  3498. return this.origin.distanceToSquared( point );
  3499. }
  3500. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3501. return _vector$a.distanceToSquared( point );
  3502. }
  3503. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3504. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3505. // It returns the min distance between the ray and the segment
  3506. // defined by v0 and v1
  3507. // It can also set two optional targets :
  3508. // - The closest point on the ray
  3509. // - The closest point on the segment
  3510. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3511. _segDir.copy( v1 ).sub( v0 ).normalize();
  3512. _diff.copy( this.origin ).sub( _segCenter );
  3513. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3514. const a01 = - this.direction.dot( _segDir );
  3515. const b0 = _diff.dot( this.direction );
  3516. const b1 = - _diff.dot( _segDir );
  3517. const c = _diff.lengthSq();
  3518. const det = Math.abs( 1 - a01 * a01 );
  3519. let s0, s1, sqrDist, extDet;
  3520. if ( det > 0 ) {
  3521. // The ray and segment are not parallel.
  3522. s0 = a01 * b1 - b0;
  3523. s1 = a01 * b0 - b1;
  3524. extDet = segExtent * det;
  3525. if ( s0 >= 0 ) {
  3526. if ( s1 >= - extDet ) {
  3527. if ( s1 <= extDet ) {
  3528. // region 0
  3529. // Minimum at interior points of ray and segment.
  3530. const invDet = 1 / det;
  3531. s0 *= invDet;
  3532. s1 *= invDet;
  3533. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3534. } else {
  3535. // region 1
  3536. s1 = segExtent;
  3537. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3538. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3539. }
  3540. } else {
  3541. // region 5
  3542. s1 = - segExtent;
  3543. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3544. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3545. }
  3546. } else {
  3547. if ( s1 <= - extDet ) {
  3548. // region 4
  3549. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3550. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3551. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3552. } else if ( s1 <= extDet ) {
  3553. // region 3
  3554. s0 = 0;
  3555. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3556. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3557. } else {
  3558. // region 2
  3559. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3560. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3561. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3562. }
  3563. }
  3564. } else {
  3565. // Ray and segment are parallel.
  3566. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3567. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3568. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3569. }
  3570. if ( optionalPointOnRay ) {
  3571. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3572. }
  3573. if ( optionalPointOnSegment ) {
  3574. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3575. }
  3576. return sqrDist;
  3577. }
  3578. intersectSphere( sphere, target ) {
  3579. _vector$a.subVectors( sphere.center, this.origin );
  3580. const tca = _vector$a.dot( this.direction );
  3581. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3582. const radius2 = sphere.radius * sphere.radius;
  3583. if ( d2 > radius2 ) return null;
  3584. const thc = Math.sqrt( radius2 - d2 );
  3585. // t0 = first intersect point - entrance on front of sphere
  3586. const t0 = tca - thc;
  3587. // t1 = second intersect point - exit point on back of sphere
  3588. const t1 = tca + thc;
  3589. // test to see if both t0 and t1 are behind the ray - if so, return null
  3590. if ( t0 < 0 && t1 < 0 ) return null;
  3591. // test to see if t0 is behind the ray:
  3592. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3593. // in order to always return an intersect point that is in front of the ray.
  3594. if ( t0 < 0 ) return this.at( t1, target );
  3595. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3596. return this.at( t0, target );
  3597. }
  3598. intersectsSphere( sphere ) {
  3599. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3600. }
  3601. distanceToPlane( plane ) {
  3602. const denominator = plane.normal.dot( this.direction );
  3603. if ( denominator === 0 ) {
  3604. // line is coplanar, return origin
  3605. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3606. return 0;
  3607. }
  3608. // Null is preferable to undefined since undefined means.... it is undefined
  3609. return null;
  3610. }
  3611. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3612. // Return if the ray never intersects the plane
  3613. return t >= 0 ? t : null;
  3614. }
  3615. intersectPlane( plane, target ) {
  3616. const t = this.distanceToPlane( plane );
  3617. if ( t === null ) {
  3618. return null;
  3619. }
  3620. return this.at( t, target );
  3621. }
  3622. intersectsPlane( plane ) {
  3623. // check if the ray lies on the plane first
  3624. const distToPoint = plane.distanceToPoint( this.origin );
  3625. if ( distToPoint === 0 ) {
  3626. return true;
  3627. }
  3628. const denominator = plane.normal.dot( this.direction );
  3629. if ( denominator * distToPoint < 0 ) {
  3630. return true;
  3631. }
  3632. // ray origin is behind the plane (and is pointing behind it)
  3633. return false;
  3634. }
  3635. intersectBox( box, target ) {
  3636. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3637. const invdirx = 1 / this.direction.x,
  3638. invdiry = 1 / this.direction.y,
  3639. invdirz = 1 / this.direction.z;
  3640. const origin = this.origin;
  3641. if ( invdirx >= 0 ) {
  3642. tmin = ( box.min.x - origin.x ) * invdirx;
  3643. tmax = ( box.max.x - origin.x ) * invdirx;
  3644. } else {
  3645. tmin = ( box.max.x - origin.x ) * invdirx;
  3646. tmax = ( box.min.x - origin.x ) * invdirx;
  3647. }
  3648. if ( invdiry >= 0 ) {
  3649. tymin = ( box.min.y - origin.y ) * invdiry;
  3650. tymax = ( box.max.y - origin.y ) * invdiry;
  3651. } else {
  3652. tymin = ( box.max.y - origin.y ) * invdiry;
  3653. tymax = ( box.min.y - origin.y ) * invdiry;
  3654. }
  3655. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3656. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3657. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3658. if ( invdirz >= 0 ) {
  3659. tzmin = ( box.min.z - origin.z ) * invdirz;
  3660. tzmax = ( box.max.z - origin.z ) * invdirz;
  3661. } else {
  3662. tzmin = ( box.max.z - origin.z ) * invdirz;
  3663. tzmax = ( box.min.z - origin.z ) * invdirz;
  3664. }
  3665. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3666. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3667. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3668. //return point closest to the ray (positive side)
  3669. if ( tmax < 0 ) return null;
  3670. return this.at( tmin >= 0 ? tmin : tmax, target );
  3671. }
  3672. intersectsBox( box ) {
  3673. return this.intersectBox( box, _vector$a ) !== null;
  3674. }
  3675. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3676. // Compute the offset origin, edges, and normal.
  3677. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3678. _edge1.subVectors( b, a );
  3679. _edge2.subVectors( c, a );
  3680. _normal$1.crossVectors( _edge1, _edge2 );
  3681. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3682. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3683. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3684. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3685. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3686. let DdN = this.direction.dot( _normal$1 );
  3687. let sign;
  3688. if ( DdN > 0 ) {
  3689. if ( backfaceCulling ) return null;
  3690. sign = 1;
  3691. } else if ( DdN < 0 ) {
  3692. sign = - 1;
  3693. DdN = - DdN;
  3694. } else {
  3695. return null;
  3696. }
  3697. _diff.subVectors( this.origin, a );
  3698. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3699. // b1 < 0, no intersection
  3700. if ( DdQxE2 < 0 ) {
  3701. return null;
  3702. }
  3703. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3704. // b2 < 0, no intersection
  3705. if ( DdE1xQ < 0 ) {
  3706. return null;
  3707. }
  3708. // b1+b2 > 1, no intersection
  3709. if ( DdQxE2 + DdE1xQ > DdN ) {
  3710. return null;
  3711. }
  3712. // Line intersects triangle, check if ray does.
  3713. const QdN = - sign * _diff.dot( _normal$1 );
  3714. // t < 0, no intersection
  3715. if ( QdN < 0 ) {
  3716. return null;
  3717. }
  3718. // Ray intersects triangle.
  3719. return this.at( QdN / DdN, target );
  3720. }
  3721. applyMatrix4( matrix4 ) {
  3722. this.origin.applyMatrix4( matrix4 );
  3723. this.direction.transformDirection( matrix4 );
  3724. return this;
  3725. }
  3726. equals( ray ) {
  3727. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3728. }
  3729. clone() {
  3730. return new this.constructor().copy( this );
  3731. }
  3732. }
  3733. class Matrix4 {
  3734. constructor() {
  3735. Matrix4.prototype.isMatrix4 = true;
  3736. this.elements = [
  3737. 1, 0, 0, 0,
  3738. 0, 1, 0, 0,
  3739. 0, 0, 1, 0,
  3740. 0, 0, 0, 1
  3741. ];
  3742. }
  3743. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3744. const te = this.elements;
  3745. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3746. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3747. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3748. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3749. return this;
  3750. }
  3751. identity() {
  3752. this.set(
  3753. 1, 0, 0, 0,
  3754. 0, 1, 0, 0,
  3755. 0, 0, 1, 0,
  3756. 0, 0, 0, 1
  3757. );
  3758. return this;
  3759. }
  3760. clone() {
  3761. return new Matrix4().fromArray( this.elements );
  3762. }
  3763. copy( m ) {
  3764. const te = this.elements;
  3765. const me = m.elements;
  3766. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3767. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3768. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3769. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3770. return this;
  3771. }
  3772. copyPosition( m ) {
  3773. const te = this.elements, me = m.elements;
  3774. te[ 12 ] = me[ 12 ];
  3775. te[ 13 ] = me[ 13 ];
  3776. te[ 14 ] = me[ 14 ];
  3777. return this;
  3778. }
  3779. setFromMatrix3( m ) {
  3780. const me = m.elements;
  3781. this.set(
  3782. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3783. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3784. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3785. 0, 0, 0, 1
  3786. );
  3787. return this;
  3788. }
  3789. extractBasis( xAxis, yAxis, zAxis ) {
  3790. xAxis.setFromMatrixColumn( this, 0 );
  3791. yAxis.setFromMatrixColumn( this, 1 );
  3792. zAxis.setFromMatrixColumn( this, 2 );
  3793. return this;
  3794. }
  3795. makeBasis( xAxis, yAxis, zAxis ) {
  3796. this.set(
  3797. xAxis.x, yAxis.x, zAxis.x, 0,
  3798. xAxis.y, yAxis.y, zAxis.y, 0,
  3799. xAxis.z, yAxis.z, zAxis.z, 0,
  3800. 0, 0, 0, 1
  3801. );
  3802. return this;
  3803. }
  3804. extractRotation( m ) {
  3805. // this method does not support reflection matrices
  3806. const te = this.elements;
  3807. const me = m.elements;
  3808. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3809. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3810. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3811. te[ 0 ] = me[ 0 ] * scaleX;
  3812. te[ 1 ] = me[ 1 ] * scaleX;
  3813. te[ 2 ] = me[ 2 ] * scaleX;
  3814. te[ 3 ] = 0;
  3815. te[ 4 ] = me[ 4 ] * scaleY;
  3816. te[ 5 ] = me[ 5 ] * scaleY;
  3817. te[ 6 ] = me[ 6 ] * scaleY;
  3818. te[ 7 ] = 0;
  3819. te[ 8 ] = me[ 8 ] * scaleZ;
  3820. te[ 9 ] = me[ 9 ] * scaleZ;
  3821. te[ 10 ] = me[ 10 ] * scaleZ;
  3822. te[ 11 ] = 0;
  3823. te[ 12 ] = 0;
  3824. te[ 13 ] = 0;
  3825. te[ 14 ] = 0;
  3826. te[ 15 ] = 1;
  3827. return this;
  3828. }
  3829. makeRotationFromEuler( euler ) {
  3830. const te = this.elements;
  3831. const x = euler.x, y = euler.y, z = euler.z;
  3832. const a = Math.cos( x ), b = Math.sin( x );
  3833. const c = Math.cos( y ), d = Math.sin( y );
  3834. const e = Math.cos( z ), f = Math.sin( z );
  3835. if ( euler.order === 'XYZ' ) {
  3836. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3837. te[ 0 ] = c * e;
  3838. te[ 4 ] = - c * f;
  3839. te[ 8 ] = d;
  3840. te[ 1 ] = af + be * d;
  3841. te[ 5 ] = ae - bf * d;
  3842. te[ 9 ] = - b * c;
  3843. te[ 2 ] = bf - ae * d;
  3844. te[ 6 ] = be + af * d;
  3845. te[ 10 ] = a * c;
  3846. } else if ( euler.order === 'YXZ' ) {
  3847. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3848. te[ 0 ] = ce + df * b;
  3849. te[ 4 ] = de * b - cf;
  3850. te[ 8 ] = a * d;
  3851. te[ 1 ] = a * f;
  3852. te[ 5 ] = a * e;
  3853. te[ 9 ] = - b;
  3854. te[ 2 ] = cf * b - de;
  3855. te[ 6 ] = df + ce * b;
  3856. te[ 10 ] = a * c;
  3857. } else if ( euler.order === 'ZXY' ) {
  3858. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3859. te[ 0 ] = ce - df * b;
  3860. te[ 4 ] = - a * f;
  3861. te[ 8 ] = de + cf * b;
  3862. te[ 1 ] = cf + de * b;
  3863. te[ 5 ] = a * e;
  3864. te[ 9 ] = df - ce * b;
  3865. te[ 2 ] = - a * d;
  3866. te[ 6 ] = b;
  3867. te[ 10 ] = a * c;
  3868. } else if ( euler.order === 'ZYX' ) {
  3869. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3870. te[ 0 ] = c * e;
  3871. te[ 4 ] = be * d - af;
  3872. te[ 8 ] = ae * d + bf;
  3873. te[ 1 ] = c * f;
  3874. te[ 5 ] = bf * d + ae;
  3875. te[ 9 ] = af * d - be;
  3876. te[ 2 ] = - d;
  3877. te[ 6 ] = b * c;
  3878. te[ 10 ] = a * c;
  3879. } else if ( euler.order === 'YZX' ) {
  3880. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3881. te[ 0 ] = c * e;
  3882. te[ 4 ] = bd - ac * f;
  3883. te[ 8 ] = bc * f + ad;
  3884. te[ 1 ] = f;
  3885. te[ 5 ] = a * e;
  3886. te[ 9 ] = - b * e;
  3887. te[ 2 ] = - d * e;
  3888. te[ 6 ] = ad * f + bc;
  3889. te[ 10 ] = ac - bd * f;
  3890. } else if ( euler.order === 'XZY' ) {
  3891. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3892. te[ 0 ] = c * e;
  3893. te[ 4 ] = - f;
  3894. te[ 8 ] = d * e;
  3895. te[ 1 ] = ac * f + bd;
  3896. te[ 5 ] = a * e;
  3897. te[ 9 ] = ad * f - bc;
  3898. te[ 2 ] = bc * f - ad;
  3899. te[ 6 ] = b * e;
  3900. te[ 10 ] = bd * f + ac;
  3901. }
  3902. // bottom row
  3903. te[ 3 ] = 0;
  3904. te[ 7 ] = 0;
  3905. te[ 11 ] = 0;
  3906. // last column
  3907. te[ 12 ] = 0;
  3908. te[ 13 ] = 0;
  3909. te[ 14 ] = 0;
  3910. te[ 15 ] = 1;
  3911. return this;
  3912. }
  3913. makeRotationFromQuaternion( q ) {
  3914. return this.compose( _zero, q, _one );
  3915. }
  3916. lookAt( eye, target, up ) {
  3917. const te = this.elements;
  3918. _z.subVectors( eye, target );
  3919. if ( _z.lengthSq() === 0 ) {
  3920. // eye and target are in the same position
  3921. _z.z = 1;
  3922. }
  3923. _z.normalize();
  3924. _x.crossVectors( up, _z );
  3925. if ( _x.lengthSq() === 0 ) {
  3926. // up and z are parallel
  3927. if ( Math.abs( up.z ) === 1 ) {
  3928. _z.x += 0.0001;
  3929. } else {
  3930. _z.z += 0.0001;
  3931. }
  3932. _z.normalize();
  3933. _x.crossVectors( up, _z );
  3934. }
  3935. _x.normalize();
  3936. _y.crossVectors( _z, _x );
  3937. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3938. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3939. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3940. return this;
  3941. }
  3942. multiply( m ) {
  3943. return this.multiplyMatrices( this, m );
  3944. }
  3945. premultiply( m ) {
  3946. return this.multiplyMatrices( m, this );
  3947. }
  3948. multiplyMatrices( a, b ) {
  3949. const ae = a.elements;
  3950. const be = b.elements;
  3951. const te = this.elements;
  3952. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3953. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3954. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3955. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3956. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3957. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3958. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3959. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3960. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3961. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3962. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3963. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3964. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3965. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3966. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3967. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3968. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3969. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3970. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3971. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3972. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3973. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3974. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3975. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3976. return this;
  3977. }
  3978. multiplyScalar( s ) {
  3979. const te = this.elements;
  3980. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3981. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3982. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3983. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3984. return this;
  3985. }
  3986. determinant() {
  3987. const te = this.elements;
  3988. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3989. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3990. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3991. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3992. //TODO: make this more efficient
  3993. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3994. return (
  3995. n41 * (
  3996. + n14 * n23 * n32
  3997. - n13 * n24 * n32
  3998. - n14 * n22 * n33
  3999. + n12 * n24 * n33
  4000. + n13 * n22 * n34
  4001. - n12 * n23 * n34
  4002. ) +
  4003. n42 * (
  4004. + n11 * n23 * n34
  4005. - n11 * n24 * n33
  4006. + n14 * n21 * n33
  4007. - n13 * n21 * n34
  4008. + n13 * n24 * n31
  4009. - n14 * n23 * n31
  4010. ) +
  4011. n43 * (
  4012. + n11 * n24 * n32
  4013. - n11 * n22 * n34
  4014. - n14 * n21 * n32
  4015. + n12 * n21 * n34
  4016. + n14 * n22 * n31
  4017. - n12 * n24 * n31
  4018. ) +
  4019. n44 * (
  4020. - n13 * n22 * n31
  4021. - n11 * n23 * n32
  4022. + n11 * n22 * n33
  4023. + n13 * n21 * n32
  4024. - n12 * n21 * n33
  4025. + n12 * n23 * n31
  4026. )
  4027. );
  4028. }
  4029. transpose() {
  4030. const te = this.elements;
  4031. let tmp;
  4032. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4033. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4034. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4035. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4036. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4037. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4038. return this;
  4039. }
  4040. setPosition( x, y, z ) {
  4041. const te = this.elements;
  4042. if ( x.isVector3 ) {
  4043. te[ 12 ] = x.x;
  4044. te[ 13 ] = x.y;
  4045. te[ 14 ] = x.z;
  4046. } else {
  4047. te[ 12 ] = x;
  4048. te[ 13 ] = y;
  4049. te[ 14 ] = z;
  4050. }
  4051. return this;
  4052. }
  4053. invert() {
  4054. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4055. const te = this.elements,
  4056. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4057. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4058. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4059. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4060. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4061. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4062. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4063. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4064. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4065. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4066. const detInv = 1 / det;
  4067. te[ 0 ] = t11 * detInv;
  4068. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4069. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4070. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4071. te[ 4 ] = t12 * detInv;
  4072. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4073. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4074. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4075. te[ 8 ] = t13 * detInv;
  4076. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4077. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4078. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4079. te[ 12 ] = t14 * detInv;
  4080. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4081. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4082. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4083. return this;
  4084. }
  4085. scale( v ) {
  4086. const te = this.elements;
  4087. const x = v.x, y = v.y, z = v.z;
  4088. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4089. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4090. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4091. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4092. return this;
  4093. }
  4094. getMaxScaleOnAxis() {
  4095. const te = this.elements;
  4096. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4097. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4098. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4099. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4100. }
  4101. makeTranslation( x, y, z ) {
  4102. this.set(
  4103. 1, 0, 0, x,
  4104. 0, 1, 0, y,
  4105. 0, 0, 1, z,
  4106. 0, 0, 0, 1
  4107. );
  4108. return this;
  4109. }
  4110. makeRotationX( theta ) {
  4111. const c = Math.cos( theta ), s = Math.sin( theta );
  4112. this.set(
  4113. 1, 0, 0, 0,
  4114. 0, c, - s, 0,
  4115. 0, s, c, 0,
  4116. 0, 0, 0, 1
  4117. );
  4118. return this;
  4119. }
  4120. makeRotationY( theta ) {
  4121. const c = Math.cos( theta ), s = Math.sin( theta );
  4122. this.set(
  4123. c, 0, s, 0,
  4124. 0, 1, 0, 0,
  4125. - s, 0, c, 0,
  4126. 0, 0, 0, 1
  4127. );
  4128. return this;
  4129. }
  4130. makeRotationZ( theta ) {
  4131. const c = Math.cos( theta ), s = Math.sin( theta );
  4132. this.set(
  4133. c, - s, 0, 0,
  4134. s, c, 0, 0,
  4135. 0, 0, 1, 0,
  4136. 0, 0, 0, 1
  4137. );
  4138. return this;
  4139. }
  4140. makeRotationAxis( axis, angle ) {
  4141. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4142. const c = Math.cos( angle );
  4143. const s = Math.sin( angle );
  4144. const t = 1 - c;
  4145. const x = axis.x, y = axis.y, z = axis.z;
  4146. const tx = t * x, ty = t * y;
  4147. this.set(
  4148. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4149. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4150. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4151. 0, 0, 0, 1
  4152. );
  4153. return this;
  4154. }
  4155. makeScale( x, y, z ) {
  4156. this.set(
  4157. x, 0, 0, 0,
  4158. 0, y, 0, 0,
  4159. 0, 0, z, 0,
  4160. 0, 0, 0, 1
  4161. );
  4162. return this;
  4163. }
  4164. makeShear( xy, xz, yx, yz, zx, zy ) {
  4165. this.set(
  4166. 1, yx, zx, 0,
  4167. xy, 1, zy, 0,
  4168. xz, yz, 1, 0,
  4169. 0, 0, 0, 1
  4170. );
  4171. return this;
  4172. }
  4173. compose( position, quaternion, scale ) {
  4174. const te = this.elements;
  4175. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4176. const x2 = x + x, y2 = y + y, z2 = z + z;
  4177. const xx = x * x2, xy = x * y2, xz = x * z2;
  4178. const yy = y * y2, yz = y * z2, zz = z * z2;
  4179. const wx = w * x2, wy = w * y2, wz = w * z2;
  4180. const sx = scale.x, sy = scale.y, sz = scale.z;
  4181. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4182. te[ 1 ] = ( xy + wz ) * sx;
  4183. te[ 2 ] = ( xz - wy ) * sx;
  4184. te[ 3 ] = 0;
  4185. te[ 4 ] = ( xy - wz ) * sy;
  4186. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4187. te[ 6 ] = ( yz + wx ) * sy;
  4188. te[ 7 ] = 0;
  4189. te[ 8 ] = ( xz + wy ) * sz;
  4190. te[ 9 ] = ( yz - wx ) * sz;
  4191. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4192. te[ 11 ] = 0;
  4193. te[ 12 ] = position.x;
  4194. te[ 13 ] = position.y;
  4195. te[ 14 ] = position.z;
  4196. te[ 15 ] = 1;
  4197. return this;
  4198. }
  4199. decompose( position, quaternion, scale ) {
  4200. const te = this.elements;
  4201. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4202. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4203. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4204. // if determine is negative, we need to invert one scale
  4205. const det = this.determinant();
  4206. if ( det < 0 ) sx = - sx;
  4207. position.x = te[ 12 ];
  4208. position.y = te[ 13 ];
  4209. position.z = te[ 14 ];
  4210. // scale the rotation part
  4211. _m1$2.copy( this );
  4212. const invSX = 1 / sx;
  4213. const invSY = 1 / sy;
  4214. const invSZ = 1 / sz;
  4215. _m1$2.elements[ 0 ] *= invSX;
  4216. _m1$2.elements[ 1 ] *= invSX;
  4217. _m1$2.elements[ 2 ] *= invSX;
  4218. _m1$2.elements[ 4 ] *= invSY;
  4219. _m1$2.elements[ 5 ] *= invSY;
  4220. _m1$2.elements[ 6 ] *= invSY;
  4221. _m1$2.elements[ 8 ] *= invSZ;
  4222. _m1$2.elements[ 9 ] *= invSZ;
  4223. _m1$2.elements[ 10 ] *= invSZ;
  4224. quaternion.setFromRotationMatrix( _m1$2 );
  4225. scale.x = sx;
  4226. scale.y = sy;
  4227. scale.z = sz;
  4228. return this;
  4229. }
  4230. makePerspective( left, right, top, bottom, near, far ) {
  4231. const te = this.elements;
  4232. const x = 2 * near / ( right - left );
  4233. const y = 2 * near / ( top - bottom );
  4234. const a = ( right + left ) / ( right - left );
  4235. const b = ( top + bottom ) / ( top - bottom );
  4236. const c = - ( far + near ) / ( far - near );
  4237. const d = - 2 * far * near / ( far - near );
  4238. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4239. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4240. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4241. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4242. return this;
  4243. }
  4244. makeOrthographic( left, right, top, bottom, near, far ) {
  4245. const te = this.elements;
  4246. const w = 1.0 / ( right - left );
  4247. const h = 1.0 / ( top - bottom );
  4248. const p = 1.0 / ( far - near );
  4249. const x = ( right + left ) * w;
  4250. const y = ( top + bottom ) * h;
  4251. const z = ( far + near ) * p;
  4252. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4253. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4254. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4255. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4256. return this;
  4257. }
  4258. equals( matrix ) {
  4259. const te = this.elements;
  4260. const me = matrix.elements;
  4261. for ( let i = 0; i < 16; i ++ ) {
  4262. if ( te[ i ] !== me[ i ] ) return false;
  4263. }
  4264. return true;
  4265. }
  4266. fromArray( array, offset = 0 ) {
  4267. for ( let i = 0; i < 16; i ++ ) {
  4268. this.elements[ i ] = array[ i + offset ];
  4269. }
  4270. return this;
  4271. }
  4272. toArray( array = [], offset = 0 ) {
  4273. const te = this.elements;
  4274. array[ offset ] = te[ 0 ];
  4275. array[ offset + 1 ] = te[ 1 ];
  4276. array[ offset + 2 ] = te[ 2 ];
  4277. array[ offset + 3 ] = te[ 3 ];
  4278. array[ offset + 4 ] = te[ 4 ];
  4279. array[ offset + 5 ] = te[ 5 ];
  4280. array[ offset + 6 ] = te[ 6 ];
  4281. array[ offset + 7 ] = te[ 7 ];
  4282. array[ offset + 8 ] = te[ 8 ];
  4283. array[ offset + 9 ] = te[ 9 ];
  4284. array[ offset + 10 ] = te[ 10 ];
  4285. array[ offset + 11 ] = te[ 11 ];
  4286. array[ offset + 12 ] = te[ 12 ];
  4287. array[ offset + 13 ] = te[ 13 ];
  4288. array[ offset + 14 ] = te[ 14 ];
  4289. array[ offset + 15 ] = te[ 15 ];
  4290. return array;
  4291. }
  4292. }
  4293. const _v1$5 = /*@__PURE__*/ new Vector3();
  4294. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4295. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4296. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4297. const _x = /*@__PURE__*/ new Vector3();
  4298. const _y = /*@__PURE__*/ new Vector3();
  4299. const _z = /*@__PURE__*/ new Vector3();
  4300. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4301. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4302. class Euler {
  4303. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4304. this.isEuler = true;
  4305. this._x = x;
  4306. this._y = y;
  4307. this._z = z;
  4308. this._order = order;
  4309. }
  4310. get x() {
  4311. return this._x;
  4312. }
  4313. set x( value ) {
  4314. this._x = value;
  4315. this._onChangeCallback();
  4316. }
  4317. get y() {
  4318. return this._y;
  4319. }
  4320. set y( value ) {
  4321. this._y = value;
  4322. this._onChangeCallback();
  4323. }
  4324. get z() {
  4325. return this._z;
  4326. }
  4327. set z( value ) {
  4328. this._z = value;
  4329. this._onChangeCallback();
  4330. }
  4331. get order() {
  4332. return this._order;
  4333. }
  4334. set order( value ) {
  4335. this._order = value;
  4336. this._onChangeCallback();
  4337. }
  4338. set( x, y, z, order = this._order ) {
  4339. this._x = x;
  4340. this._y = y;
  4341. this._z = z;
  4342. this._order = order;
  4343. this._onChangeCallback();
  4344. return this;
  4345. }
  4346. clone() {
  4347. return new this.constructor( this._x, this._y, this._z, this._order );
  4348. }
  4349. copy( euler ) {
  4350. this._x = euler._x;
  4351. this._y = euler._y;
  4352. this._z = euler._z;
  4353. this._order = euler._order;
  4354. this._onChangeCallback();
  4355. return this;
  4356. }
  4357. setFromRotationMatrix( m, order = this._order, update = true ) {
  4358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4359. const te = m.elements;
  4360. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4361. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4362. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4363. switch ( order ) {
  4364. case 'XYZ':
  4365. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4366. if ( Math.abs( m13 ) < 0.9999999 ) {
  4367. this._x = Math.atan2( - m23, m33 );
  4368. this._z = Math.atan2( - m12, m11 );
  4369. } else {
  4370. this._x = Math.atan2( m32, m22 );
  4371. this._z = 0;
  4372. }
  4373. break;
  4374. case 'YXZ':
  4375. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4376. if ( Math.abs( m23 ) < 0.9999999 ) {
  4377. this._y = Math.atan2( m13, m33 );
  4378. this._z = Math.atan2( m21, m22 );
  4379. } else {
  4380. this._y = Math.atan2( - m31, m11 );
  4381. this._z = 0;
  4382. }
  4383. break;
  4384. case 'ZXY':
  4385. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4386. if ( Math.abs( m32 ) < 0.9999999 ) {
  4387. this._y = Math.atan2( - m31, m33 );
  4388. this._z = Math.atan2( - m12, m22 );
  4389. } else {
  4390. this._y = 0;
  4391. this._z = Math.atan2( m21, m11 );
  4392. }
  4393. break;
  4394. case 'ZYX':
  4395. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4396. if ( Math.abs( m31 ) < 0.9999999 ) {
  4397. this._x = Math.atan2( m32, m33 );
  4398. this._z = Math.atan2( m21, m11 );
  4399. } else {
  4400. this._x = 0;
  4401. this._z = Math.atan2( - m12, m22 );
  4402. }
  4403. break;
  4404. case 'YZX':
  4405. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4406. if ( Math.abs( m21 ) < 0.9999999 ) {
  4407. this._x = Math.atan2( - m23, m22 );
  4408. this._y = Math.atan2( - m31, m11 );
  4409. } else {
  4410. this._x = 0;
  4411. this._y = Math.atan2( m13, m33 );
  4412. }
  4413. break;
  4414. case 'XZY':
  4415. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4416. if ( Math.abs( m12 ) < 0.9999999 ) {
  4417. this._x = Math.atan2( m32, m22 );
  4418. this._y = Math.atan2( m13, m11 );
  4419. } else {
  4420. this._x = Math.atan2( - m23, m33 );
  4421. this._y = 0;
  4422. }
  4423. break;
  4424. default:
  4425. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4426. }
  4427. this._order = order;
  4428. if ( update === true ) this._onChangeCallback();
  4429. return this;
  4430. }
  4431. setFromQuaternion( q, order, update ) {
  4432. _matrix$1.makeRotationFromQuaternion( q );
  4433. return this.setFromRotationMatrix( _matrix$1, order, update );
  4434. }
  4435. setFromVector3( v, order = this._order ) {
  4436. return this.set( v.x, v.y, v.z, order );
  4437. }
  4438. reorder( newOrder ) {
  4439. // WARNING: this discards revolution information -bhouston
  4440. _quaternion$3.setFromEuler( this );
  4441. return this.setFromQuaternion( _quaternion$3, newOrder );
  4442. }
  4443. equals( euler ) {
  4444. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4445. }
  4446. fromArray( array ) {
  4447. this._x = array[ 0 ];
  4448. this._y = array[ 1 ];
  4449. this._z = array[ 2 ];
  4450. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4451. this._onChangeCallback();
  4452. return this;
  4453. }
  4454. toArray( array = [], offset = 0 ) {
  4455. array[ offset ] = this._x;
  4456. array[ offset + 1 ] = this._y;
  4457. array[ offset + 2 ] = this._z;
  4458. array[ offset + 3 ] = this._order;
  4459. return array;
  4460. }
  4461. _onChange( callback ) {
  4462. this._onChangeCallback = callback;
  4463. return this;
  4464. }
  4465. _onChangeCallback() {}
  4466. *[ Symbol.iterator ]() {
  4467. yield this._x;
  4468. yield this._y;
  4469. yield this._z;
  4470. yield this._order;
  4471. }
  4472. }
  4473. Euler.DEFAULT_ORDER = 'XYZ';
  4474. class Layers {
  4475. constructor() {
  4476. this.mask = 1 | 0;
  4477. }
  4478. set( channel ) {
  4479. this.mask = ( 1 << channel | 0 ) >>> 0;
  4480. }
  4481. enable( channel ) {
  4482. this.mask |= 1 << channel | 0;
  4483. }
  4484. enableAll() {
  4485. this.mask = 0xffffffff | 0;
  4486. }
  4487. toggle( channel ) {
  4488. this.mask ^= 1 << channel | 0;
  4489. }
  4490. disable( channel ) {
  4491. this.mask &= ~ ( 1 << channel | 0 );
  4492. }
  4493. disableAll() {
  4494. this.mask = 0;
  4495. }
  4496. test( layers ) {
  4497. return ( this.mask & layers.mask ) !== 0;
  4498. }
  4499. isEnabled( channel ) {
  4500. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4501. }
  4502. }
  4503. let _object3DId = 0;
  4504. const _v1$4 = /*@__PURE__*/ new Vector3();
  4505. const _q1 = /*@__PURE__*/ new Quaternion();
  4506. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4507. const _target = /*@__PURE__*/ new Vector3();
  4508. const _position$3 = /*@__PURE__*/ new Vector3();
  4509. const _scale$2 = /*@__PURE__*/ new Vector3();
  4510. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4511. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4512. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4513. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4514. const _addedEvent = { type: 'added' };
  4515. const _removedEvent = { type: 'removed' };
  4516. class Object3D extends EventDispatcher {
  4517. constructor() {
  4518. super();
  4519. this.isObject3D = true;
  4520. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4521. this.uuid = generateUUID();
  4522. this.name = '';
  4523. this.type = 'Object3D';
  4524. this.parent = null;
  4525. this.children = [];
  4526. this.up = Object3D.DEFAULT_UP.clone();
  4527. const position = new Vector3();
  4528. const rotation = new Euler();
  4529. const quaternion = new Quaternion();
  4530. const scale = new Vector3( 1, 1, 1 );
  4531. function onRotationChange() {
  4532. quaternion.setFromEuler( rotation, false );
  4533. }
  4534. function onQuaternionChange() {
  4535. rotation.setFromQuaternion( quaternion, undefined, false );
  4536. }
  4537. rotation._onChange( onRotationChange );
  4538. quaternion._onChange( onQuaternionChange );
  4539. Object.defineProperties( this, {
  4540. position: {
  4541. configurable: true,
  4542. enumerable: true,
  4543. value: position
  4544. },
  4545. rotation: {
  4546. configurable: true,
  4547. enumerable: true,
  4548. value: rotation
  4549. },
  4550. quaternion: {
  4551. configurable: true,
  4552. enumerable: true,
  4553. value: quaternion
  4554. },
  4555. scale: {
  4556. configurable: true,
  4557. enumerable: true,
  4558. value: scale
  4559. },
  4560. modelViewMatrix: {
  4561. value: new Matrix4()
  4562. },
  4563. normalMatrix: {
  4564. value: new Matrix3()
  4565. }
  4566. } );
  4567. this.matrix = new Matrix4();
  4568. this.matrixWorld = new Matrix4();
  4569. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4570. this.matrixWorldNeedsUpdate = false;
  4571. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4572. this.layers = new Layers();
  4573. this.visible = true;
  4574. this.castShadow = false;
  4575. this.receiveShadow = false;
  4576. this.frustumCulled = true;
  4577. this.renderOrder = 0;
  4578. this.animations = [];
  4579. this.userData = {};
  4580. }
  4581. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4582. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4583. applyMatrix4( matrix ) {
  4584. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4585. this.matrix.premultiply( matrix );
  4586. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4587. }
  4588. applyQuaternion( q ) {
  4589. this.quaternion.premultiply( q );
  4590. return this;
  4591. }
  4592. setRotationFromAxisAngle( axis, angle ) {
  4593. // assumes axis is normalized
  4594. this.quaternion.setFromAxisAngle( axis, angle );
  4595. }
  4596. setRotationFromEuler( euler ) {
  4597. this.quaternion.setFromEuler( euler, true );
  4598. }
  4599. setRotationFromMatrix( m ) {
  4600. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4601. this.quaternion.setFromRotationMatrix( m );
  4602. }
  4603. setRotationFromQuaternion( q ) {
  4604. // assumes q is normalized
  4605. this.quaternion.copy( q );
  4606. }
  4607. rotateOnAxis( axis, angle ) {
  4608. // rotate object on axis in object space
  4609. // axis is assumed to be normalized
  4610. _q1.setFromAxisAngle( axis, angle );
  4611. this.quaternion.multiply( _q1 );
  4612. return this;
  4613. }
  4614. rotateOnWorldAxis( axis, angle ) {
  4615. // rotate object on axis in world space
  4616. // axis is assumed to be normalized
  4617. // method assumes no rotated parent
  4618. _q1.setFromAxisAngle( axis, angle );
  4619. this.quaternion.premultiply( _q1 );
  4620. return this;
  4621. }
  4622. rotateX( angle ) {
  4623. return this.rotateOnAxis( _xAxis, angle );
  4624. }
  4625. rotateY( angle ) {
  4626. return this.rotateOnAxis( _yAxis, angle );
  4627. }
  4628. rotateZ( angle ) {
  4629. return this.rotateOnAxis( _zAxis, angle );
  4630. }
  4631. translateOnAxis( axis, distance ) {
  4632. // translate object by distance along axis in object space
  4633. // axis is assumed to be normalized
  4634. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4635. this.position.add( _v1$4.multiplyScalar( distance ) );
  4636. return this;
  4637. }
  4638. translateX( distance ) {
  4639. return this.translateOnAxis( _xAxis, distance );
  4640. }
  4641. translateY( distance ) {
  4642. return this.translateOnAxis( _yAxis, distance );
  4643. }
  4644. translateZ( distance ) {
  4645. return this.translateOnAxis( _zAxis, distance );
  4646. }
  4647. localToWorld( vector ) {
  4648. this.updateWorldMatrix( true, false );
  4649. return vector.applyMatrix4( this.matrixWorld );
  4650. }
  4651. worldToLocal( vector ) {
  4652. this.updateWorldMatrix( true, false );
  4653. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4654. }
  4655. lookAt( x, y, z ) {
  4656. // This method does not support objects having non-uniformly-scaled parent(s)
  4657. if ( x.isVector3 ) {
  4658. _target.copy( x );
  4659. } else {
  4660. _target.set( x, y, z );
  4661. }
  4662. const parent = this.parent;
  4663. this.updateWorldMatrix( true, false );
  4664. _position$3.setFromMatrixPosition( this.matrixWorld );
  4665. if ( this.isCamera || this.isLight ) {
  4666. _m1$1.lookAt( _position$3, _target, this.up );
  4667. } else {
  4668. _m1$1.lookAt( _target, _position$3, this.up );
  4669. }
  4670. this.quaternion.setFromRotationMatrix( _m1$1 );
  4671. if ( parent ) {
  4672. _m1$1.extractRotation( parent.matrixWorld );
  4673. _q1.setFromRotationMatrix( _m1$1 );
  4674. this.quaternion.premultiply( _q1.invert() );
  4675. }
  4676. }
  4677. add( object ) {
  4678. if ( arguments.length > 1 ) {
  4679. for ( let i = 0; i < arguments.length; i ++ ) {
  4680. this.add( arguments[ i ] );
  4681. }
  4682. return this;
  4683. }
  4684. if ( object === this ) {
  4685. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4686. return this;
  4687. }
  4688. if ( object && object.isObject3D ) {
  4689. if ( object.parent !== null ) {
  4690. object.parent.remove( object );
  4691. }
  4692. object.parent = this;
  4693. this.children.push( object );
  4694. object.dispatchEvent( _addedEvent );
  4695. } else {
  4696. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4697. }
  4698. return this;
  4699. }
  4700. remove( object ) {
  4701. if ( arguments.length > 1 ) {
  4702. for ( let i = 0; i < arguments.length; i ++ ) {
  4703. this.remove( arguments[ i ] );
  4704. }
  4705. return this;
  4706. }
  4707. const index = this.children.indexOf( object );
  4708. if ( index !== - 1 ) {
  4709. object.parent = null;
  4710. this.children.splice( index, 1 );
  4711. object.dispatchEvent( _removedEvent );
  4712. }
  4713. return this;
  4714. }
  4715. removeFromParent() {
  4716. const parent = this.parent;
  4717. if ( parent !== null ) {
  4718. parent.remove( this );
  4719. }
  4720. return this;
  4721. }
  4722. clear() {
  4723. for ( let i = 0; i < this.children.length; i ++ ) {
  4724. const object = this.children[ i ];
  4725. object.parent = null;
  4726. object.dispatchEvent( _removedEvent );
  4727. }
  4728. this.children.length = 0;
  4729. return this;
  4730. }
  4731. attach( object ) {
  4732. // adds object as a child of this, while maintaining the object's world transform
  4733. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4734. this.updateWorldMatrix( true, false );
  4735. _m1$1.copy( this.matrixWorld ).invert();
  4736. if ( object.parent !== null ) {
  4737. object.parent.updateWorldMatrix( true, false );
  4738. _m1$1.multiply( object.parent.matrixWorld );
  4739. }
  4740. object.applyMatrix4( _m1$1 );
  4741. this.add( object );
  4742. object.updateWorldMatrix( false, true );
  4743. return this;
  4744. }
  4745. getObjectById( id ) {
  4746. return this.getObjectByProperty( 'id', id );
  4747. }
  4748. getObjectByName( name ) {
  4749. return this.getObjectByProperty( 'name', name );
  4750. }
  4751. getObjectByProperty( name, value ) {
  4752. if ( this[ name ] === value ) return this;
  4753. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4754. const child = this.children[ i ];
  4755. const object = child.getObjectByProperty( name, value );
  4756. if ( object !== undefined ) {
  4757. return object;
  4758. }
  4759. }
  4760. return undefined;
  4761. }
  4762. getObjectsByProperty( name, value ) {
  4763. let result = [];
  4764. if ( this[ name ] === value ) result.push( this );
  4765. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4766. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4767. if ( childResult.length > 0 ) {
  4768. result = result.concat( childResult );
  4769. }
  4770. }
  4771. return result;
  4772. }
  4773. getWorldPosition( target ) {
  4774. this.updateWorldMatrix( true, false );
  4775. return target.setFromMatrixPosition( this.matrixWorld );
  4776. }
  4777. getWorldQuaternion( target ) {
  4778. this.updateWorldMatrix( true, false );
  4779. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4780. return target;
  4781. }
  4782. getWorldScale( target ) {
  4783. this.updateWorldMatrix( true, false );
  4784. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4785. return target;
  4786. }
  4787. getWorldDirection( target ) {
  4788. this.updateWorldMatrix( true, false );
  4789. const e = this.matrixWorld.elements;
  4790. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4791. }
  4792. raycast( /* raycaster, intersects */ ) {}
  4793. traverse( callback ) {
  4794. callback( this );
  4795. const children = this.children;
  4796. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4797. children[ i ].traverse( callback );
  4798. }
  4799. }
  4800. traverseVisible( callback ) {
  4801. if ( this.visible === false ) return;
  4802. callback( this );
  4803. const children = this.children;
  4804. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4805. children[ i ].traverseVisible( callback );
  4806. }
  4807. }
  4808. traverseAncestors( callback ) {
  4809. const parent = this.parent;
  4810. if ( parent !== null ) {
  4811. callback( parent );
  4812. parent.traverseAncestors( callback );
  4813. }
  4814. }
  4815. updateMatrix() {
  4816. this.matrix.compose( this.position, this.quaternion, this.scale );
  4817. this.matrixWorldNeedsUpdate = true;
  4818. }
  4819. updateMatrixWorld( force ) {
  4820. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4821. if ( this.matrixWorldNeedsUpdate || force ) {
  4822. if ( this.parent === null ) {
  4823. this.matrixWorld.copy( this.matrix );
  4824. } else {
  4825. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4826. }
  4827. this.matrixWorldNeedsUpdate = false;
  4828. force = true;
  4829. }
  4830. // update children
  4831. const children = this.children;
  4832. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4833. const child = children[ i ];
  4834. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4835. child.updateMatrixWorld( force );
  4836. }
  4837. }
  4838. }
  4839. updateWorldMatrix( updateParents, updateChildren ) {
  4840. const parent = this.parent;
  4841. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4842. parent.updateWorldMatrix( true, false );
  4843. }
  4844. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4845. if ( this.parent === null ) {
  4846. this.matrixWorld.copy( this.matrix );
  4847. } else {
  4848. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4849. }
  4850. // update children
  4851. if ( updateChildren === true ) {
  4852. const children = this.children;
  4853. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4854. const child = children[ i ];
  4855. if ( child.matrixWorldAutoUpdate === true ) {
  4856. child.updateWorldMatrix( false, true );
  4857. }
  4858. }
  4859. }
  4860. }
  4861. toJSON( meta ) {
  4862. // meta is a string when called from JSON.stringify
  4863. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4864. const output = {};
  4865. // meta is a hash used to collect geometries, materials.
  4866. // not providing it implies that this is the root object
  4867. // being serialized.
  4868. if ( isRootObject ) {
  4869. // initialize meta obj
  4870. meta = {
  4871. geometries: {},
  4872. materials: {},
  4873. textures: {},
  4874. images: {},
  4875. shapes: {},
  4876. skeletons: {},
  4877. animations: {},
  4878. nodes: {}
  4879. };
  4880. output.metadata = {
  4881. version: 4.5,
  4882. type: 'Object',
  4883. generator: 'Object3D.toJSON'
  4884. };
  4885. }
  4886. // standard Object3D serialization
  4887. const object = {};
  4888. object.uuid = this.uuid;
  4889. object.type = this.type;
  4890. if ( this.name !== '' ) object.name = this.name;
  4891. if ( this.castShadow === true ) object.castShadow = true;
  4892. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4893. if ( this.visible === false ) object.visible = false;
  4894. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4895. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4896. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4897. object.layers = this.layers.mask;
  4898. object.matrix = this.matrix.toArray();
  4899. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4900. // object specific properties
  4901. if ( this.isInstancedMesh ) {
  4902. object.type = 'InstancedMesh';
  4903. object.count = this.count;
  4904. object.instanceMatrix = this.instanceMatrix.toJSON();
  4905. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4906. }
  4907. //
  4908. function serialize( library, element ) {
  4909. if ( library[ element.uuid ] === undefined ) {
  4910. library[ element.uuid ] = element.toJSON( meta );
  4911. }
  4912. return element.uuid;
  4913. }
  4914. if ( this.isScene ) {
  4915. if ( this.background ) {
  4916. if ( this.background.isColor ) {
  4917. object.background = this.background.toJSON();
  4918. } else if ( this.background.isTexture ) {
  4919. object.background = this.background.toJSON( meta ).uuid;
  4920. }
  4921. }
  4922. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4923. object.environment = this.environment.toJSON( meta ).uuid;
  4924. }
  4925. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4926. object.geometry = serialize( meta.geometries, this.geometry );
  4927. const parameters = this.geometry.parameters;
  4928. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4929. const shapes = parameters.shapes;
  4930. if ( Array.isArray( shapes ) ) {
  4931. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4932. const shape = shapes[ i ];
  4933. serialize( meta.shapes, shape );
  4934. }
  4935. } else {
  4936. serialize( meta.shapes, shapes );
  4937. }
  4938. }
  4939. }
  4940. if ( this.isSkinnedMesh ) {
  4941. object.bindMode = this.bindMode;
  4942. object.bindMatrix = this.bindMatrix.toArray();
  4943. if ( this.skeleton !== undefined ) {
  4944. serialize( meta.skeletons, this.skeleton );
  4945. object.skeleton = this.skeleton.uuid;
  4946. }
  4947. }
  4948. if ( this.material !== undefined ) {
  4949. if ( Array.isArray( this.material ) ) {
  4950. const uuids = [];
  4951. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4952. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4953. }
  4954. object.material = uuids;
  4955. } else {
  4956. object.material = serialize( meta.materials, this.material );
  4957. }
  4958. }
  4959. //
  4960. if ( this.children.length > 0 ) {
  4961. object.children = [];
  4962. for ( let i = 0; i < this.children.length; i ++ ) {
  4963. object.children.push( this.children[ i ].toJSON( meta ).object );
  4964. }
  4965. }
  4966. //
  4967. if ( this.animations.length > 0 ) {
  4968. object.animations = [];
  4969. for ( let i = 0; i < this.animations.length; i ++ ) {
  4970. const animation = this.animations[ i ];
  4971. object.animations.push( serialize( meta.animations, animation ) );
  4972. }
  4973. }
  4974. if ( isRootObject ) {
  4975. const geometries = extractFromCache( meta.geometries );
  4976. const materials = extractFromCache( meta.materials );
  4977. const textures = extractFromCache( meta.textures );
  4978. const images = extractFromCache( meta.images );
  4979. const shapes = extractFromCache( meta.shapes );
  4980. const skeletons = extractFromCache( meta.skeletons );
  4981. const animations = extractFromCache( meta.animations );
  4982. const nodes = extractFromCache( meta.nodes );
  4983. if ( geometries.length > 0 ) output.geometries = geometries;
  4984. if ( materials.length > 0 ) output.materials = materials;
  4985. if ( textures.length > 0 ) output.textures = textures;
  4986. if ( images.length > 0 ) output.images = images;
  4987. if ( shapes.length > 0 ) output.shapes = shapes;
  4988. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4989. if ( animations.length > 0 ) output.animations = animations;
  4990. if ( nodes.length > 0 ) output.nodes = nodes;
  4991. }
  4992. output.object = object;
  4993. return output;
  4994. // extract data from the cache hash
  4995. // remove metadata on each item
  4996. // and return as array
  4997. function extractFromCache( cache ) {
  4998. const values = [];
  4999. for ( const key in cache ) {
  5000. const data = cache[ key ];
  5001. delete data.metadata;
  5002. values.push( data );
  5003. }
  5004. return values;
  5005. }
  5006. }
  5007. clone( recursive ) {
  5008. return new this.constructor().copy( this, recursive );
  5009. }
  5010. copy( source, recursive = true ) {
  5011. this.name = source.name;
  5012. this.up.copy( source.up );
  5013. this.position.copy( source.position );
  5014. this.rotation.order = source.rotation.order;
  5015. this.quaternion.copy( source.quaternion );
  5016. this.scale.copy( source.scale );
  5017. this.matrix.copy( source.matrix );
  5018. this.matrixWorld.copy( source.matrixWorld );
  5019. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5020. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5021. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5022. this.layers.mask = source.layers.mask;
  5023. this.visible = source.visible;
  5024. this.castShadow = source.castShadow;
  5025. this.receiveShadow = source.receiveShadow;
  5026. this.frustumCulled = source.frustumCulled;
  5027. this.renderOrder = source.renderOrder;
  5028. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5029. if ( recursive === true ) {
  5030. for ( let i = 0; i < source.children.length; i ++ ) {
  5031. const child = source.children[ i ];
  5032. this.add( child.clone() );
  5033. }
  5034. }
  5035. return this;
  5036. }
  5037. }
  5038. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5039. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  5040. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  5041. const _v0$1 = /*@__PURE__*/ new Vector3();
  5042. const _v1$3 = /*@__PURE__*/ new Vector3();
  5043. const _v2$2 = /*@__PURE__*/ new Vector3();
  5044. const _v3$1 = /*@__PURE__*/ new Vector3();
  5045. const _vab = /*@__PURE__*/ new Vector3();
  5046. const _vac = /*@__PURE__*/ new Vector3();
  5047. const _vbc = /*@__PURE__*/ new Vector3();
  5048. const _vap = /*@__PURE__*/ new Vector3();
  5049. const _vbp = /*@__PURE__*/ new Vector3();
  5050. const _vcp = /*@__PURE__*/ new Vector3();
  5051. class Triangle {
  5052. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5053. this.a = a;
  5054. this.b = b;
  5055. this.c = c;
  5056. }
  5057. static getNormal( a, b, c, target ) {
  5058. target.subVectors( c, b );
  5059. _v0$1.subVectors( a, b );
  5060. target.cross( _v0$1 );
  5061. const targetLengthSq = target.lengthSq();
  5062. if ( targetLengthSq > 0 ) {
  5063. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5064. }
  5065. return target.set( 0, 0, 0 );
  5066. }
  5067. // static/instance method to calculate barycentric coordinates
  5068. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5069. static getBarycoord( point, a, b, c, target ) {
  5070. _v0$1.subVectors( c, a );
  5071. _v1$3.subVectors( b, a );
  5072. _v2$2.subVectors( point, a );
  5073. const dot00 = _v0$1.dot( _v0$1 );
  5074. const dot01 = _v0$1.dot( _v1$3 );
  5075. const dot02 = _v0$1.dot( _v2$2 );
  5076. const dot11 = _v1$3.dot( _v1$3 );
  5077. const dot12 = _v1$3.dot( _v2$2 );
  5078. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5079. // collinear or singular triangle
  5080. if ( denom === 0 ) {
  5081. // arbitrary location outside of triangle?
  5082. // not sure if this is the best idea, maybe should be returning undefined
  5083. return target.set( - 2, - 1, - 1 );
  5084. }
  5085. const invDenom = 1 / denom;
  5086. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5087. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5088. // barycentric coordinates must always sum to 1
  5089. return target.set( 1 - u - v, v, u );
  5090. }
  5091. static containsPoint( point, a, b, c ) {
  5092. this.getBarycoord( point, a, b, c, _v3$1 );
  5093. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5094. }
  5095. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5096. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5097. target.set( 0, 0 );
  5098. target.addScaledVector( uv1, _v3$1.x );
  5099. target.addScaledVector( uv2, _v3$1.y );
  5100. target.addScaledVector( uv3, _v3$1.z );
  5101. return target;
  5102. }
  5103. static isFrontFacing( a, b, c, direction ) {
  5104. _v0$1.subVectors( c, b );
  5105. _v1$3.subVectors( a, b );
  5106. // strictly front facing
  5107. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5108. }
  5109. set( a, b, c ) {
  5110. this.a.copy( a );
  5111. this.b.copy( b );
  5112. this.c.copy( c );
  5113. return this;
  5114. }
  5115. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5116. this.a.copy( points[ i0 ] );
  5117. this.b.copy( points[ i1 ] );
  5118. this.c.copy( points[ i2 ] );
  5119. return this;
  5120. }
  5121. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5122. this.a.fromBufferAttribute( attribute, i0 );
  5123. this.b.fromBufferAttribute( attribute, i1 );
  5124. this.c.fromBufferAttribute( attribute, i2 );
  5125. return this;
  5126. }
  5127. clone() {
  5128. return new this.constructor().copy( this );
  5129. }
  5130. copy( triangle ) {
  5131. this.a.copy( triangle.a );
  5132. this.b.copy( triangle.b );
  5133. this.c.copy( triangle.c );
  5134. return this;
  5135. }
  5136. getArea() {
  5137. _v0$1.subVectors( this.c, this.b );
  5138. _v1$3.subVectors( this.a, this.b );
  5139. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5140. }
  5141. getMidpoint( target ) {
  5142. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5143. }
  5144. getNormal( target ) {
  5145. return Triangle.getNormal( this.a, this.b, this.c, target );
  5146. }
  5147. getPlane( target ) {
  5148. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5149. }
  5150. getBarycoord( point, target ) {
  5151. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5152. }
  5153. getUV( point, uv1, uv2, uv3, target ) {
  5154. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5155. }
  5156. containsPoint( point ) {
  5157. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5158. }
  5159. isFrontFacing( direction ) {
  5160. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5161. }
  5162. intersectsBox( box ) {
  5163. return box.intersectsTriangle( this );
  5164. }
  5165. closestPointToPoint( p, target ) {
  5166. const a = this.a, b = this.b, c = this.c;
  5167. let v, w;
  5168. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5169. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5170. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5171. // basically, we're distinguishing which of the voronoi regions of the triangle
  5172. // the point lies in with the minimum amount of redundant computation.
  5173. _vab.subVectors( b, a );
  5174. _vac.subVectors( c, a );
  5175. _vap.subVectors( p, a );
  5176. const d1 = _vab.dot( _vap );
  5177. const d2 = _vac.dot( _vap );
  5178. if ( d1 <= 0 && d2 <= 0 ) {
  5179. // vertex region of A; barycentric coords (1, 0, 0)
  5180. return target.copy( a );
  5181. }
  5182. _vbp.subVectors( p, b );
  5183. const d3 = _vab.dot( _vbp );
  5184. const d4 = _vac.dot( _vbp );
  5185. if ( d3 >= 0 && d4 <= d3 ) {
  5186. // vertex region of B; barycentric coords (0, 1, 0)
  5187. return target.copy( b );
  5188. }
  5189. const vc = d1 * d4 - d3 * d2;
  5190. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5191. v = d1 / ( d1 - d3 );
  5192. // edge region of AB; barycentric coords (1-v, v, 0)
  5193. return target.copy( a ).addScaledVector( _vab, v );
  5194. }
  5195. _vcp.subVectors( p, c );
  5196. const d5 = _vab.dot( _vcp );
  5197. const d6 = _vac.dot( _vcp );
  5198. if ( d6 >= 0 && d5 <= d6 ) {
  5199. // vertex region of C; barycentric coords (0, 0, 1)
  5200. return target.copy( c );
  5201. }
  5202. const vb = d5 * d2 - d1 * d6;
  5203. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5204. w = d2 / ( d2 - d6 );
  5205. // edge region of AC; barycentric coords (1-w, 0, w)
  5206. return target.copy( a ).addScaledVector( _vac, w );
  5207. }
  5208. const va = d3 * d6 - d5 * d4;
  5209. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5210. _vbc.subVectors( c, b );
  5211. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5212. // edge region of BC; barycentric coords (0, 1-w, w)
  5213. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5214. }
  5215. // face region
  5216. const denom = 1 / ( va + vb + vc );
  5217. // u = va * denom
  5218. v = vb * denom;
  5219. w = vc * denom;
  5220. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5221. }
  5222. equals( triangle ) {
  5223. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5224. }
  5225. }
  5226. let materialId = 0;
  5227. class Material extends EventDispatcher {
  5228. constructor() {
  5229. super();
  5230. this.isMaterial = true;
  5231. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5232. this.uuid = generateUUID();
  5233. this.name = '';
  5234. this.type = 'Material';
  5235. this.blending = NormalBlending;
  5236. this.side = FrontSide;
  5237. this.vertexColors = false;
  5238. this.opacity = 1;
  5239. this.transparent = false;
  5240. this.blendSrc = SrcAlphaFactor;
  5241. this.blendDst = OneMinusSrcAlphaFactor;
  5242. this.blendEquation = AddEquation;
  5243. this.blendSrcAlpha = null;
  5244. this.blendDstAlpha = null;
  5245. this.blendEquationAlpha = null;
  5246. this.depthFunc = LessEqualDepth;
  5247. this.depthTest = true;
  5248. this.depthWrite = true;
  5249. this.stencilWriteMask = 0xff;
  5250. this.stencilFunc = AlwaysStencilFunc;
  5251. this.stencilRef = 0;
  5252. this.stencilFuncMask = 0xff;
  5253. this.stencilFail = KeepStencilOp;
  5254. this.stencilZFail = KeepStencilOp;
  5255. this.stencilZPass = KeepStencilOp;
  5256. this.stencilWrite = false;
  5257. this.clippingPlanes = null;
  5258. this.clipIntersection = false;
  5259. this.clipShadows = false;
  5260. this.shadowSide = null;
  5261. this.colorWrite = true;
  5262. this.precision = null; // override the renderer's default precision for this material
  5263. this.polygonOffset = false;
  5264. this.polygonOffsetFactor = 0;
  5265. this.polygonOffsetUnits = 0;
  5266. this.dithering = false;
  5267. this.alphaToCoverage = false;
  5268. this.premultipliedAlpha = false;
  5269. this.forceSinglePass = false;
  5270. this.visible = true;
  5271. this.toneMapped = true;
  5272. this.userData = {};
  5273. this.version = 0;
  5274. this._alphaTest = 0;
  5275. }
  5276. get alphaTest() {
  5277. return this._alphaTest;
  5278. }
  5279. set alphaTest( value ) {
  5280. if ( this._alphaTest > 0 !== value > 0 ) {
  5281. this.version ++;
  5282. }
  5283. this._alphaTest = value;
  5284. }
  5285. onBuild( /* shaderobject, renderer */ ) {}
  5286. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5287. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5288. customProgramCacheKey() {
  5289. return this.onBeforeCompile.toString();
  5290. }
  5291. setValues( values ) {
  5292. if ( values === undefined ) return;
  5293. for ( const key in values ) {
  5294. const newValue = values[ key ];
  5295. if ( newValue === undefined ) {
  5296. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5297. continue;
  5298. }
  5299. const currentValue = this[ key ];
  5300. if ( currentValue === undefined ) {
  5301. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5302. continue;
  5303. }
  5304. if ( currentValue && currentValue.isColor ) {
  5305. currentValue.set( newValue );
  5306. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5307. currentValue.copy( newValue );
  5308. } else {
  5309. this[ key ] = newValue;
  5310. }
  5311. }
  5312. }
  5313. toJSON( meta ) {
  5314. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5315. if ( isRootObject ) {
  5316. meta = {
  5317. textures: {},
  5318. images: {}
  5319. };
  5320. }
  5321. const data = {
  5322. metadata: {
  5323. version: 4.5,
  5324. type: 'Material',
  5325. generator: 'Material.toJSON'
  5326. }
  5327. };
  5328. // standard Material serialization
  5329. data.uuid = this.uuid;
  5330. data.type = this.type;
  5331. if ( this.name !== '' ) data.name = this.name;
  5332. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5333. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5334. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5335. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5336. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5337. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5338. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5339. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5340. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5341. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5342. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5343. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5344. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5345. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5346. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5347. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5348. }
  5349. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5350. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5351. }
  5352. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5353. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5354. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5355. }
  5356. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5357. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5358. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5359. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5360. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5361. }
  5362. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5363. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5364. }
  5365. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5366. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5367. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5368. if ( this.lightMap && this.lightMap.isTexture ) {
  5369. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5370. data.lightMapIntensity = this.lightMapIntensity;
  5371. }
  5372. if ( this.aoMap && this.aoMap.isTexture ) {
  5373. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5374. data.aoMapIntensity = this.aoMapIntensity;
  5375. }
  5376. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5377. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5378. data.bumpScale = this.bumpScale;
  5379. }
  5380. if ( this.normalMap && this.normalMap.isTexture ) {
  5381. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5382. data.normalMapType = this.normalMapType;
  5383. data.normalScale = this.normalScale.toArray();
  5384. }
  5385. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5386. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5387. data.displacementScale = this.displacementScale;
  5388. data.displacementBias = this.displacementBias;
  5389. }
  5390. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5391. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5392. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5393. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5394. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5395. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5396. if ( this.envMap && this.envMap.isTexture ) {
  5397. data.envMap = this.envMap.toJSON( meta ).uuid;
  5398. if ( this.combine !== undefined ) data.combine = this.combine;
  5399. }
  5400. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5401. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5402. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5403. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5404. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5405. }
  5406. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5407. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5408. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5409. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5410. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5411. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5412. if ( this.size !== undefined ) data.size = this.size;
  5413. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5414. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5415. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5416. if ( this.side !== FrontSide ) data.side = this.side;
  5417. if ( this.vertexColors ) data.vertexColors = true;
  5418. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5419. if ( this.transparent === true ) data.transparent = this.transparent;
  5420. data.depthFunc = this.depthFunc;
  5421. data.depthTest = this.depthTest;
  5422. data.depthWrite = this.depthWrite;
  5423. data.colorWrite = this.colorWrite;
  5424. data.stencilWrite = this.stencilWrite;
  5425. data.stencilWriteMask = this.stencilWriteMask;
  5426. data.stencilFunc = this.stencilFunc;
  5427. data.stencilRef = this.stencilRef;
  5428. data.stencilFuncMask = this.stencilFuncMask;
  5429. data.stencilFail = this.stencilFail;
  5430. data.stencilZFail = this.stencilZFail;
  5431. data.stencilZPass = this.stencilZPass;
  5432. // rotation (SpriteMaterial)
  5433. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5434. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5435. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5436. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5437. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5438. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5439. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5440. if ( this.scale !== undefined ) data.scale = this.scale;
  5441. if ( this.dithering === true ) data.dithering = true;
  5442. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5443. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5444. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5445. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5446. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5447. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5448. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5449. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5450. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5451. if ( this.visible === false ) data.visible = false;
  5452. if ( this.toneMapped === false ) data.toneMapped = false;
  5453. if ( this.fog === false ) data.fog = false;
  5454. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5455. // TODO: Copied from Object3D.toJSON
  5456. function extractFromCache( cache ) {
  5457. const values = [];
  5458. for ( const key in cache ) {
  5459. const data = cache[ key ];
  5460. delete data.metadata;
  5461. values.push( data );
  5462. }
  5463. return values;
  5464. }
  5465. if ( isRootObject ) {
  5466. const textures = extractFromCache( meta.textures );
  5467. const images = extractFromCache( meta.images );
  5468. if ( textures.length > 0 ) data.textures = textures;
  5469. if ( images.length > 0 ) data.images = images;
  5470. }
  5471. return data;
  5472. }
  5473. clone() {
  5474. return new this.constructor().copy( this );
  5475. }
  5476. copy( source ) {
  5477. this.name = source.name;
  5478. this.blending = source.blending;
  5479. this.side = source.side;
  5480. this.vertexColors = source.vertexColors;
  5481. this.opacity = source.opacity;
  5482. this.transparent = source.transparent;
  5483. this.blendSrc = source.blendSrc;
  5484. this.blendDst = source.blendDst;
  5485. this.blendEquation = source.blendEquation;
  5486. this.blendSrcAlpha = source.blendSrcAlpha;
  5487. this.blendDstAlpha = source.blendDstAlpha;
  5488. this.blendEquationAlpha = source.blendEquationAlpha;
  5489. this.depthFunc = source.depthFunc;
  5490. this.depthTest = source.depthTest;
  5491. this.depthWrite = source.depthWrite;
  5492. this.stencilWriteMask = source.stencilWriteMask;
  5493. this.stencilFunc = source.stencilFunc;
  5494. this.stencilRef = source.stencilRef;
  5495. this.stencilFuncMask = source.stencilFuncMask;
  5496. this.stencilFail = source.stencilFail;
  5497. this.stencilZFail = source.stencilZFail;
  5498. this.stencilZPass = source.stencilZPass;
  5499. this.stencilWrite = source.stencilWrite;
  5500. const srcPlanes = source.clippingPlanes;
  5501. let dstPlanes = null;
  5502. if ( srcPlanes !== null ) {
  5503. const n = srcPlanes.length;
  5504. dstPlanes = new Array( n );
  5505. for ( let i = 0; i !== n; ++ i ) {
  5506. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5507. }
  5508. }
  5509. this.clippingPlanes = dstPlanes;
  5510. this.clipIntersection = source.clipIntersection;
  5511. this.clipShadows = source.clipShadows;
  5512. this.shadowSide = source.shadowSide;
  5513. this.colorWrite = source.colorWrite;
  5514. this.precision = source.precision;
  5515. this.polygonOffset = source.polygonOffset;
  5516. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5517. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5518. this.dithering = source.dithering;
  5519. this.alphaTest = source.alphaTest;
  5520. this.alphaToCoverage = source.alphaToCoverage;
  5521. this.premultipliedAlpha = source.premultipliedAlpha;
  5522. this.forceSinglePass = source.forceSinglePass;
  5523. this.visible = source.visible;
  5524. this.toneMapped = source.toneMapped;
  5525. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5526. return this;
  5527. }
  5528. dispose() {
  5529. this.dispatchEvent( { type: 'dispose' } );
  5530. }
  5531. set needsUpdate( value ) {
  5532. if ( value === true ) this.version ++;
  5533. }
  5534. }
  5535. class MeshBasicMaterial extends Material {
  5536. constructor( parameters ) {
  5537. super();
  5538. this.isMeshBasicMaterial = true;
  5539. this.type = 'MeshBasicMaterial';
  5540. this.color = new Color( 0xffffff ); // emissive
  5541. this.map = null;
  5542. this.lightMap = null;
  5543. this.lightMapIntensity = 1.0;
  5544. this.aoMap = null;
  5545. this.aoMapIntensity = 1.0;
  5546. this.specularMap = null;
  5547. this.alphaMap = null;
  5548. this.envMap = null;
  5549. this.combine = MultiplyOperation;
  5550. this.reflectivity = 1;
  5551. this.refractionRatio = 0.98;
  5552. this.wireframe = false;
  5553. this.wireframeLinewidth = 1;
  5554. this.wireframeLinecap = 'round';
  5555. this.wireframeLinejoin = 'round';
  5556. this.fog = true;
  5557. this.setValues( parameters );
  5558. }
  5559. copy( source ) {
  5560. super.copy( source );
  5561. this.color.copy( source.color );
  5562. this.map = source.map;
  5563. this.lightMap = source.lightMap;
  5564. this.lightMapIntensity = source.lightMapIntensity;
  5565. this.aoMap = source.aoMap;
  5566. this.aoMapIntensity = source.aoMapIntensity;
  5567. this.specularMap = source.specularMap;
  5568. this.alphaMap = source.alphaMap;
  5569. this.envMap = source.envMap;
  5570. this.combine = source.combine;
  5571. this.reflectivity = source.reflectivity;
  5572. this.refractionRatio = source.refractionRatio;
  5573. this.wireframe = source.wireframe;
  5574. this.wireframeLinewidth = source.wireframeLinewidth;
  5575. this.wireframeLinecap = source.wireframeLinecap;
  5576. this.wireframeLinejoin = source.wireframeLinejoin;
  5577. this.fog = source.fog;
  5578. return this;
  5579. }
  5580. }
  5581. const _vector$9 = /*@__PURE__*/ new Vector3();
  5582. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5583. class BufferAttribute {
  5584. constructor( array, itemSize, normalized = false ) {
  5585. if ( Array.isArray( array ) ) {
  5586. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5587. }
  5588. this.isBufferAttribute = true;
  5589. this.name = '';
  5590. this.array = array;
  5591. this.itemSize = itemSize;
  5592. this.count = array !== undefined ? array.length / itemSize : 0;
  5593. this.normalized = normalized;
  5594. this.usage = StaticDrawUsage;
  5595. this.updateRange = { offset: 0, count: - 1 };
  5596. this.version = 0;
  5597. }
  5598. onUploadCallback() {}
  5599. set needsUpdate( value ) {
  5600. if ( value === true ) this.version ++;
  5601. }
  5602. setUsage( value ) {
  5603. this.usage = value;
  5604. return this;
  5605. }
  5606. copy( source ) {
  5607. this.name = source.name;
  5608. this.array = new source.array.constructor( source.array );
  5609. this.itemSize = source.itemSize;
  5610. this.count = source.count;
  5611. this.normalized = source.normalized;
  5612. this.usage = source.usage;
  5613. return this;
  5614. }
  5615. copyAt( index1, attribute, index2 ) {
  5616. index1 *= this.itemSize;
  5617. index2 *= attribute.itemSize;
  5618. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5619. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5620. }
  5621. return this;
  5622. }
  5623. copyArray( array ) {
  5624. this.array.set( array );
  5625. return this;
  5626. }
  5627. applyMatrix3( m ) {
  5628. if ( this.itemSize === 2 ) {
  5629. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5630. _vector2$1.fromBufferAttribute( this, i );
  5631. _vector2$1.applyMatrix3( m );
  5632. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5633. }
  5634. } else if ( this.itemSize === 3 ) {
  5635. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5636. _vector$9.fromBufferAttribute( this, i );
  5637. _vector$9.applyMatrix3( m );
  5638. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5639. }
  5640. }
  5641. return this;
  5642. }
  5643. applyMatrix4( m ) {
  5644. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5645. _vector$9.fromBufferAttribute( this, i );
  5646. _vector$9.applyMatrix4( m );
  5647. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5648. }
  5649. return this;
  5650. }
  5651. applyNormalMatrix( m ) {
  5652. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5653. _vector$9.fromBufferAttribute( this, i );
  5654. _vector$9.applyNormalMatrix( m );
  5655. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5656. }
  5657. return this;
  5658. }
  5659. transformDirection( m ) {
  5660. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5661. _vector$9.fromBufferAttribute( this, i );
  5662. _vector$9.transformDirection( m );
  5663. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5664. }
  5665. return this;
  5666. }
  5667. set( value, offset = 0 ) {
  5668. // Matching BufferAttribute constructor, do not normalize the array.
  5669. this.array.set( value, offset );
  5670. return this;
  5671. }
  5672. getX( index ) {
  5673. let x = this.array[ index * this.itemSize ];
  5674. if ( this.normalized ) x = denormalize( x, this.array );
  5675. return x;
  5676. }
  5677. setX( index, x ) {
  5678. if ( this.normalized ) x = normalize( x, this.array );
  5679. this.array[ index * this.itemSize ] = x;
  5680. return this;
  5681. }
  5682. getY( index ) {
  5683. let y = this.array[ index * this.itemSize + 1 ];
  5684. if ( this.normalized ) y = denormalize( y, this.array );
  5685. return y;
  5686. }
  5687. setY( index, y ) {
  5688. if ( this.normalized ) y = normalize( y, this.array );
  5689. this.array[ index * this.itemSize + 1 ] = y;
  5690. return this;
  5691. }
  5692. getZ( index ) {
  5693. let z = this.array[ index * this.itemSize + 2 ];
  5694. if ( this.normalized ) z = denormalize( z, this.array );
  5695. return z;
  5696. }
  5697. setZ( index, z ) {
  5698. if ( this.normalized ) z = normalize( z, this.array );
  5699. this.array[ index * this.itemSize + 2 ] = z;
  5700. return this;
  5701. }
  5702. getW( index ) {
  5703. let w = this.array[ index * this.itemSize + 3 ];
  5704. if ( this.normalized ) w = denormalize( w, this.array );
  5705. return w;
  5706. }
  5707. setW( index, w ) {
  5708. if ( this.normalized ) w = normalize( w, this.array );
  5709. this.array[ index * this.itemSize + 3 ] = w;
  5710. return this;
  5711. }
  5712. setXY( index, x, y ) {
  5713. index *= this.itemSize;
  5714. if ( this.normalized ) {
  5715. x = normalize( x, this.array );
  5716. y = normalize( y, this.array );
  5717. }
  5718. this.array[ index + 0 ] = x;
  5719. this.array[ index + 1 ] = y;
  5720. return this;
  5721. }
  5722. setXYZ( index, x, y, z ) {
  5723. index *= this.itemSize;
  5724. if ( this.normalized ) {
  5725. x = normalize( x, this.array );
  5726. y = normalize( y, this.array );
  5727. z = normalize( z, this.array );
  5728. }
  5729. this.array[ index + 0 ] = x;
  5730. this.array[ index + 1 ] = y;
  5731. this.array[ index + 2 ] = z;
  5732. return this;
  5733. }
  5734. setXYZW( index, x, y, z, w ) {
  5735. index *= this.itemSize;
  5736. if ( this.normalized ) {
  5737. x = normalize( x, this.array );
  5738. y = normalize( y, this.array );
  5739. z = normalize( z, this.array );
  5740. w = normalize( w, this.array );
  5741. }
  5742. this.array[ index + 0 ] = x;
  5743. this.array[ index + 1 ] = y;
  5744. this.array[ index + 2 ] = z;
  5745. this.array[ index + 3 ] = w;
  5746. return this;
  5747. }
  5748. onUpload( callback ) {
  5749. this.onUploadCallback = callback;
  5750. return this;
  5751. }
  5752. clone() {
  5753. return new this.constructor( this.array, this.itemSize ).copy( this );
  5754. }
  5755. toJSON() {
  5756. const data = {
  5757. itemSize: this.itemSize,
  5758. type: this.array.constructor.name,
  5759. array: Array.from( this.array ),
  5760. normalized: this.normalized
  5761. };
  5762. if ( this.name !== '' ) data.name = this.name;
  5763. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5764. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5765. return data;
  5766. }
  5767. // @deprecated
  5768. copyColorsArray() {
  5769. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5770. }
  5771. copyVector2sArray() {
  5772. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5773. }
  5774. copyVector3sArray() {
  5775. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5776. }
  5777. copyVector4sArray() {
  5778. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5779. }
  5780. }
  5781. //
  5782. class Int8BufferAttribute extends BufferAttribute {
  5783. constructor( array, itemSize, normalized ) {
  5784. super( new Int8Array( array ), itemSize, normalized );
  5785. }
  5786. }
  5787. class Uint8BufferAttribute extends BufferAttribute {
  5788. constructor( array, itemSize, normalized ) {
  5789. super( new Uint8Array( array ), itemSize, normalized );
  5790. }
  5791. }
  5792. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5793. constructor( array, itemSize, normalized ) {
  5794. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5795. }
  5796. }
  5797. class Int16BufferAttribute extends BufferAttribute {
  5798. constructor( array, itemSize, normalized ) {
  5799. super( new Int16Array( array ), itemSize, normalized );
  5800. }
  5801. }
  5802. class Uint16BufferAttribute extends BufferAttribute {
  5803. constructor( array, itemSize, normalized ) {
  5804. super( new Uint16Array( array ), itemSize, normalized );
  5805. }
  5806. }
  5807. class Int32BufferAttribute extends BufferAttribute {
  5808. constructor( array, itemSize, normalized ) {
  5809. super( new Int32Array( array ), itemSize, normalized );
  5810. }
  5811. }
  5812. class Uint32BufferAttribute extends BufferAttribute {
  5813. constructor( array, itemSize, normalized ) {
  5814. super( new Uint32Array( array ), itemSize, normalized );
  5815. }
  5816. }
  5817. class Float16BufferAttribute extends BufferAttribute {
  5818. constructor( array, itemSize, normalized ) {
  5819. super( new Uint16Array( array ), itemSize, normalized );
  5820. this.isFloat16BufferAttribute = true;
  5821. }
  5822. }
  5823. class Float32BufferAttribute extends BufferAttribute {
  5824. constructor( array, itemSize, normalized ) {
  5825. super( new Float32Array( array ), itemSize, normalized );
  5826. }
  5827. }
  5828. class Float64BufferAttribute extends BufferAttribute {
  5829. constructor( array, itemSize, normalized ) {
  5830. super( new Float64Array( array ), itemSize, normalized );
  5831. }
  5832. }
  5833. let _id$1 = 0;
  5834. const _m1 = /*@__PURE__*/ new Matrix4();
  5835. const _obj = /*@__PURE__*/ new Object3D();
  5836. const _offset = /*@__PURE__*/ new Vector3();
  5837. const _box$1 = /*@__PURE__*/ new Box3();
  5838. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5839. const _vector$8 = /*@__PURE__*/ new Vector3();
  5840. class BufferGeometry extends EventDispatcher {
  5841. constructor() {
  5842. super();
  5843. this.isBufferGeometry = true;
  5844. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5845. this.uuid = generateUUID();
  5846. this.name = '';
  5847. this.type = 'BufferGeometry';
  5848. this.index = null;
  5849. this.attributes = {};
  5850. this.morphAttributes = {};
  5851. this.morphTargetsRelative = false;
  5852. this.groups = [];
  5853. this.boundingBox = null;
  5854. this.boundingSphere = null;
  5855. this.drawRange = { start: 0, count: Infinity };
  5856. this.userData = {};
  5857. }
  5858. getIndex() {
  5859. return this.index;
  5860. }
  5861. setIndex( index ) {
  5862. if ( Array.isArray( index ) ) {
  5863. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5864. } else {
  5865. this.index = index;
  5866. }
  5867. return this;
  5868. }
  5869. getAttribute( name ) {
  5870. return this.attributes[ name ];
  5871. }
  5872. setAttribute( name, attribute ) {
  5873. this.attributes[ name ] = attribute;
  5874. return this;
  5875. }
  5876. deleteAttribute( name ) {
  5877. delete this.attributes[ name ];
  5878. return this;
  5879. }
  5880. hasAttribute( name ) {
  5881. return this.attributes[ name ] !== undefined;
  5882. }
  5883. addGroup( start, count, materialIndex = 0 ) {
  5884. this.groups.push( {
  5885. start: start,
  5886. count: count,
  5887. materialIndex: materialIndex
  5888. } );
  5889. }
  5890. clearGroups() {
  5891. this.groups = [];
  5892. }
  5893. setDrawRange( start, count ) {
  5894. this.drawRange.start = start;
  5895. this.drawRange.count = count;
  5896. }
  5897. applyMatrix4( matrix ) {
  5898. const position = this.attributes.position;
  5899. if ( position !== undefined ) {
  5900. position.applyMatrix4( matrix );
  5901. position.needsUpdate = true;
  5902. }
  5903. const normal = this.attributes.normal;
  5904. if ( normal !== undefined ) {
  5905. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5906. normal.applyNormalMatrix( normalMatrix );
  5907. normal.needsUpdate = true;
  5908. }
  5909. const tangent = this.attributes.tangent;
  5910. if ( tangent !== undefined ) {
  5911. tangent.transformDirection( matrix );
  5912. tangent.needsUpdate = true;
  5913. }
  5914. if ( this.boundingBox !== null ) {
  5915. this.computeBoundingBox();
  5916. }
  5917. if ( this.boundingSphere !== null ) {
  5918. this.computeBoundingSphere();
  5919. }
  5920. return this;
  5921. }
  5922. applyQuaternion( q ) {
  5923. _m1.makeRotationFromQuaternion( q );
  5924. this.applyMatrix4( _m1 );
  5925. return this;
  5926. }
  5927. rotateX( angle ) {
  5928. // rotate geometry around world x-axis
  5929. _m1.makeRotationX( angle );
  5930. this.applyMatrix4( _m1 );
  5931. return this;
  5932. }
  5933. rotateY( angle ) {
  5934. // rotate geometry around world y-axis
  5935. _m1.makeRotationY( angle );
  5936. this.applyMatrix4( _m1 );
  5937. return this;
  5938. }
  5939. rotateZ( angle ) {
  5940. // rotate geometry around world z-axis
  5941. _m1.makeRotationZ( angle );
  5942. this.applyMatrix4( _m1 );
  5943. return this;
  5944. }
  5945. translate( x, y, z ) {
  5946. // translate geometry
  5947. _m1.makeTranslation( x, y, z );
  5948. this.applyMatrix4( _m1 );
  5949. return this;
  5950. }
  5951. scale( x, y, z ) {
  5952. // scale geometry
  5953. _m1.makeScale( x, y, z );
  5954. this.applyMatrix4( _m1 );
  5955. return this;
  5956. }
  5957. lookAt( vector ) {
  5958. _obj.lookAt( vector );
  5959. _obj.updateMatrix();
  5960. this.applyMatrix4( _obj.matrix );
  5961. return this;
  5962. }
  5963. center() {
  5964. this.computeBoundingBox();
  5965. this.boundingBox.getCenter( _offset ).negate();
  5966. this.translate( _offset.x, _offset.y, _offset.z );
  5967. return this;
  5968. }
  5969. setFromPoints( points ) {
  5970. const position = [];
  5971. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5972. const point = points[ i ];
  5973. position.push( point.x, point.y, point.z || 0 );
  5974. }
  5975. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5976. return this;
  5977. }
  5978. computeBoundingBox() {
  5979. if ( this.boundingBox === null ) {
  5980. this.boundingBox = new Box3();
  5981. }
  5982. const position = this.attributes.position;
  5983. const morphAttributesPosition = this.morphAttributes.position;
  5984. if ( position && position.isGLBufferAttribute ) {
  5985. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5986. this.boundingBox.set(
  5987. new Vector3( - Infinity, - Infinity, - Infinity ),
  5988. new Vector3( + Infinity, + Infinity, + Infinity )
  5989. );
  5990. return;
  5991. }
  5992. if ( position !== undefined ) {
  5993. this.boundingBox.setFromBufferAttribute( position );
  5994. // process morph attributes if present
  5995. if ( morphAttributesPosition ) {
  5996. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5997. const morphAttribute = morphAttributesPosition[ i ];
  5998. _box$1.setFromBufferAttribute( morphAttribute );
  5999. if ( this.morphTargetsRelative ) {
  6000. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  6001. this.boundingBox.expandByPoint( _vector$8 );
  6002. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6003. this.boundingBox.expandByPoint( _vector$8 );
  6004. } else {
  6005. this.boundingBox.expandByPoint( _box$1.min );
  6006. this.boundingBox.expandByPoint( _box$1.max );
  6007. }
  6008. }
  6009. }
  6010. } else {
  6011. this.boundingBox.makeEmpty();
  6012. }
  6013. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6014. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6015. }
  6016. }
  6017. computeBoundingSphere() {
  6018. if ( this.boundingSphere === null ) {
  6019. this.boundingSphere = new Sphere();
  6020. }
  6021. const position = this.attributes.position;
  6022. const morphAttributesPosition = this.morphAttributes.position;
  6023. if ( position && position.isGLBufferAttribute ) {
  6024. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6025. this.boundingSphere.set( new Vector3(), Infinity );
  6026. return;
  6027. }
  6028. if ( position ) {
  6029. // first, find the center of the bounding sphere
  6030. const center = this.boundingSphere.center;
  6031. _box$1.setFromBufferAttribute( position );
  6032. // process morph attributes if present
  6033. if ( morphAttributesPosition ) {
  6034. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6035. const morphAttribute = morphAttributesPosition[ i ];
  6036. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6037. if ( this.morphTargetsRelative ) {
  6038. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6039. _box$1.expandByPoint( _vector$8 );
  6040. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6041. _box$1.expandByPoint( _vector$8 );
  6042. } else {
  6043. _box$1.expandByPoint( _boxMorphTargets.min );
  6044. _box$1.expandByPoint( _boxMorphTargets.max );
  6045. }
  6046. }
  6047. }
  6048. _box$1.getCenter( center );
  6049. // second, try to find a boundingSphere with a radius smaller than the
  6050. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6051. let maxRadiusSq = 0;
  6052. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6053. _vector$8.fromBufferAttribute( position, i );
  6054. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6055. }
  6056. // process morph attributes if present
  6057. if ( morphAttributesPosition ) {
  6058. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6059. const morphAttribute = morphAttributesPosition[ i ];
  6060. const morphTargetsRelative = this.morphTargetsRelative;
  6061. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6062. _vector$8.fromBufferAttribute( morphAttribute, j );
  6063. if ( morphTargetsRelative ) {
  6064. _offset.fromBufferAttribute( position, j );
  6065. _vector$8.add( _offset );
  6066. }
  6067. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6068. }
  6069. }
  6070. }
  6071. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6072. if ( isNaN( this.boundingSphere.radius ) ) {
  6073. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6074. }
  6075. }
  6076. }
  6077. computeTangents() {
  6078. const index = this.index;
  6079. const attributes = this.attributes;
  6080. // based on http://www.terathon.com/code/tangent.html
  6081. // (per vertex tangents)
  6082. if ( index === null ||
  6083. attributes.position === undefined ||
  6084. attributes.normal === undefined ||
  6085. attributes.uv === undefined ) {
  6086. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6087. return;
  6088. }
  6089. const indices = index.array;
  6090. const positions = attributes.position.array;
  6091. const normals = attributes.normal.array;
  6092. const uvs = attributes.uv.array;
  6093. const nVertices = positions.length / 3;
  6094. if ( this.hasAttribute( 'tangent' ) === false ) {
  6095. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6096. }
  6097. const tangents = this.getAttribute( 'tangent' ).array;
  6098. const tan1 = [], tan2 = [];
  6099. for ( let i = 0; i < nVertices; i ++ ) {
  6100. tan1[ i ] = new Vector3();
  6101. tan2[ i ] = new Vector3();
  6102. }
  6103. const vA = new Vector3(),
  6104. vB = new Vector3(),
  6105. vC = new Vector3(),
  6106. uvA = new Vector2(),
  6107. uvB = new Vector2(),
  6108. uvC = new Vector2(),
  6109. sdir = new Vector3(),
  6110. tdir = new Vector3();
  6111. function handleTriangle( a, b, c ) {
  6112. vA.fromArray( positions, a * 3 );
  6113. vB.fromArray( positions, b * 3 );
  6114. vC.fromArray( positions, c * 3 );
  6115. uvA.fromArray( uvs, a * 2 );
  6116. uvB.fromArray( uvs, b * 2 );
  6117. uvC.fromArray( uvs, c * 2 );
  6118. vB.sub( vA );
  6119. vC.sub( vA );
  6120. uvB.sub( uvA );
  6121. uvC.sub( uvA );
  6122. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6123. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6124. if ( ! isFinite( r ) ) return;
  6125. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6126. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6127. tan1[ a ].add( sdir );
  6128. tan1[ b ].add( sdir );
  6129. tan1[ c ].add( sdir );
  6130. tan2[ a ].add( tdir );
  6131. tan2[ b ].add( tdir );
  6132. tan2[ c ].add( tdir );
  6133. }
  6134. let groups = this.groups;
  6135. if ( groups.length === 0 ) {
  6136. groups = [ {
  6137. start: 0,
  6138. count: indices.length
  6139. } ];
  6140. }
  6141. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6142. const group = groups[ i ];
  6143. const start = group.start;
  6144. const count = group.count;
  6145. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6146. handleTriangle(
  6147. indices[ j + 0 ],
  6148. indices[ j + 1 ],
  6149. indices[ j + 2 ]
  6150. );
  6151. }
  6152. }
  6153. const tmp = new Vector3(), tmp2 = new Vector3();
  6154. const n = new Vector3(), n2 = new Vector3();
  6155. function handleVertex( v ) {
  6156. n.fromArray( normals, v * 3 );
  6157. n2.copy( n );
  6158. const t = tan1[ v ];
  6159. // Gram-Schmidt orthogonalize
  6160. tmp.copy( t );
  6161. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6162. // Calculate handedness
  6163. tmp2.crossVectors( n2, t );
  6164. const test = tmp2.dot( tan2[ v ] );
  6165. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6166. tangents[ v * 4 ] = tmp.x;
  6167. tangents[ v * 4 + 1 ] = tmp.y;
  6168. tangents[ v * 4 + 2 ] = tmp.z;
  6169. tangents[ v * 4 + 3 ] = w;
  6170. }
  6171. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6172. const group = groups[ i ];
  6173. const start = group.start;
  6174. const count = group.count;
  6175. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6176. handleVertex( indices[ j + 0 ] );
  6177. handleVertex( indices[ j + 1 ] );
  6178. handleVertex( indices[ j + 2 ] );
  6179. }
  6180. }
  6181. }
  6182. computeVertexNormals() {
  6183. const index = this.index;
  6184. const positionAttribute = this.getAttribute( 'position' );
  6185. if ( positionAttribute !== undefined ) {
  6186. let normalAttribute = this.getAttribute( 'normal' );
  6187. if ( normalAttribute === undefined ) {
  6188. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6189. this.setAttribute( 'normal', normalAttribute );
  6190. } else {
  6191. // reset existing normals to zero
  6192. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6193. normalAttribute.setXYZ( i, 0, 0, 0 );
  6194. }
  6195. }
  6196. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6197. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6198. const cb = new Vector3(), ab = new Vector3();
  6199. // indexed elements
  6200. if ( index ) {
  6201. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6202. const vA = index.getX( i + 0 );
  6203. const vB = index.getX( i + 1 );
  6204. const vC = index.getX( i + 2 );
  6205. pA.fromBufferAttribute( positionAttribute, vA );
  6206. pB.fromBufferAttribute( positionAttribute, vB );
  6207. pC.fromBufferAttribute( positionAttribute, vC );
  6208. cb.subVectors( pC, pB );
  6209. ab.subVectors( pA, pB );
  6210. cb.cross( ab );
  6211. nA.fromBufferAttribute( normalAttribute, vA );
  6212. nB.fromBufferAttribute( normalAttribute, vB );
  6213. nC.fromBufferAttribute( normalAttribute, vC );
  6214. nA.add( cb );
  6215. nB.add( cb );
  6216. nC.add( cb );
  6217. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6218. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6219. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6220. }
  6221. } else {
  6222. // non-indexed elements (unconnected triangle soup)
  6223. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6224. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6225. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6226. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6227. cb.subVectors( pC, pB );
  6228. ab.subVectors( pA, pB );
  6229. cb.cross( ab );
  6230. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6231. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6232. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6233. }
  6234. }
  6235. this.normalizeNormals();
  6236. normalAttribute.needsUpdate = true;
  6237. }
  6238. }
  6239. // @deprecated since r144
  6240. merge() {
  6241. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6242. return this;
  6243. }
  6244. normalizeNormals() {
  6245. const normals = this.attributes.normal;
  6246. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6247. _vector$8.fromBufferAttribute( normals, i );
  6248. _vector$8.normalize();
  6249. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6250. }
  6251. }
  6252. toNonIndexed() {
  6253. function convertBufferAttribute( attribute, indices ) {
  6254. const array = attribute.array;
  6255. const itemSize = attribute.itemSize;
  6256. const normalized = attribute.normalized;
  6257. const array2 = new array.constructor( indices.length * itemSize );
  6258. let index = 0, index2 = 0;
  6259. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6260. if ( attribute.isInterleavedBufferAttribute ) {
  6261. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6262. } else {
  6263. index = indices[ i ] * itemSize;
  6264. }
  6265. for ( let j = 0; j < itemSize; j ++ ) {
  6266. array2[ index2 ++ ] = array[ index ++ ];
  6267. }
  6268. }
  6269. return new BufferAttribute( array2, itemSize, normalized );
  6270. }
  6271. //
  6272. if ( this.index === null ) {
  6273. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6274. return this;
  6275. }
  6276. const geometry2 = new BufferGeometry();
  6277. const indices = this.index.array;
  6278. const attributes = this.attributes;
  6279. // attributes
  6280. for ( const name in attributes ) {
  6281. const attribute = attributes[ name ];
  6282. const newAttribute = convertBufferAttribute( attribute, indices );
  6283. geometry2.setAttribute( name, newAttribute );
  6284. }
  6285. // morph attributes
  6286. const morphAttributes = this.morphAttributes;
  6287. for ( const name in morphAttributes ) {
  6288. const morphArray = [];
  6289. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6290. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6291. const attribute = morphAttribute[ i ];
  6292. const newAttribute = convertBufferAttribute( attribute, indices );
  6293. morphArray.push( newAttribute );
  6294. }
  6295. geometry2.morphAttributes[ name ] = morphArray;
  6296. }
  6297. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6298. // groups
  6299. const groups = this.groups;
  6300. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6301. const group = groups[ i ];
  6302. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6303. }
  6304. return geometry2;
  6305. }
  6306. toJSON() {
  6307. const data = {
  6308. metadata: {
  6309. version: 4.5,
  6310. type: 'BufferGeometry',
  6311. generator: 'BufferGeometry.toJSON'
  6312. }
  6313. };
  6314. // standard BufferGeometry serialization
  6315. data.uuid = this.uuid;
  6316. data.type = this.type;
  6317. if ( this.name !== '' ) data.name = this.name;
  6318. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6319. if ( this.parameters !== undefined ) {
  6320. const parameters = this.parameters;
  6321. for ( const key in parameters ) {
  6322. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6323. }
  6324. return data;
  6325. }
  6326. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6327. data.data = { attributes: {} };
  6328. const index = this.index;
  6329. if ( index !== null ) {
  6330. data.data.index = {
  6331. type: index.array.constructor.name,
  6332. array: Array.prototype.slice.call( index.array )
  6333. };
  6334. }
  6335. const attributes = this.attributes;
  6336. for ( const key in attributes ) {
  6337. const attribute = attributes[ key ];
  6338. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6339. }
  6340. const morphAttributes = {};
  6341. let hasMorphAttributes = false;
  6342. for ( const key in this.morphAttributes ) {
  6343. const attributeArray = this.morphAttributes[ key ];
  6344. const array = [];
  6345. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6346. const attribute = attributeArray[ i ];
  6347. array.push( attribute.toJSON( data.data ) );
  6348. }
  6349. if ( array.length > 0 ) {
  6350. morphAttributes[ key ] = array;
  6351. hasMorphAttributes = true;
  6352. }
  6353. }
  6354. if ( hasMorphAttributes ) {
  6355. data.data.morphAttributes = morphAttributes;
  6356. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6357. }
  6358. const groups = this.groups;
  6359. if ( groups.length > 0 ) {
  6360. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6361. }
  6362. const boundingSphere = this.boundingSphere;
  6363. if ( boundingSphere !== null ) {
  6364. data.data.boundingSphere = {
  6365. center: boundingSphere.center.toArray(),
  6366. radius: boundingSphere.radius
  6367. };
  6368. }
  6369. return data;
  6370. }
  6371. clone() {
  6372. return new this.constructor().copy( this );
  6373. }
  6374. copy( source ) {
  6375. // reset
  6376. this.index = null;
  6377. this.attributes = {};
  6378. this.morphAttributes = {};
  6379. this.groups = [];
  6380. this.boundingBox = null;
  6381. this.boundingSphere = null;
  6382. // used for storing cloned, shared data
  6383. const data = {};
  6384. // name
  6385. this.name = source.name;
  6386. // index
  6387. const index = source.index;
  6388. if ( index !== null ) {
  6389. this.setIndex( index.clone( data ) );
  6390. }
  6391. // attributes
  6392. const attributes = source.attributes;
  6393. for ( const name in attributes ) {
  6394. const attribute = attributes[ name ];
  6395. this.setAttribute( name, attribute.clone( data ) );
  6396. }
  6397. // morph attributes
  6398. const morphAttributes = source.morphAttributes;
  6399. for ( const name in morphAttributes ) {
  6400. const array = [];
  6401. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6402. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6403. array.push( morphAttribute[ i ].clone( data ) );
  6404. }
  6405. this.morphAttributes[ name ] = array;
  6406. }
  6407. this.morphTargetsRelative = source.morphTargetsRelative;
  6408. // groups
  6409. const groups = source.groups;
  6410. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6411. const group = groups[ i ];
  6412. this.addGroup( group.start, group.count, group.materialIndex );
  6413. }
  6414. // bounding box
  6415. const boundingBox = source.boundingBox;
  6416. if ( boundingBox !== null ) {
  6417. this.boundingBox = boundingBox.clone();
  6418. }
  6419. // bounding sphere
  6420. const boundingSphere = source.boundingSphere;
  6421. if ( boundingSphere !== null ) {
  6422. this.boundingSphere = boundingSphere.clone();
  6423. }
  6424. // draw range
  6425. this.drawRange.start = source.drawRange.start;
  6426. this.drawRange.count = source.drawRange.count;
  6427. // user data
  6428. this.userData = source.userData;
  6429. // geometry generator parameters
  6430. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6431. return this;
  6432. }
  6433. dispose() {
  6434. this.dispatchEvent( { type: 'dispose' } );
  6435. }
  6436. }
  6437. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6438. const _ray$2 = /*@__PURE__*/ new Ray();
  6439. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6440. const _vA$1 = /*@__PURE__*/ new Vector3();
  6441. const _vB$1 = /*@__PURE__*/ new Vector3();
  6442. const _vC$1 = /*@__PURE__*/ new Vector3();
  6443. const _tempA = /*@__PURE__*/ new Vector3();
  6444. const _morphA = /*@__PURE__*/ new Vector3();
  6445. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6446. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6447. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6448. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6449. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6450. class Mesh extends Object3D {
  6451. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6452. super();
  6453. this.isMesh = true;
  6454. this.type = 'Mesh';
  6455. this.geometry = geometry;
  6456. this.material = material;
  6457. this.updateMorphTargets();
  6458. }
  6459. copy( source, recursive ) {
  6460. super.copy( source, recursive );
  6461. if ( source.morphTargetInfluences !== undefined ) {
  6462. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6463. }
  6464. if ( source.morphTargetDictionary !== undefined ) {
  6465. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6466. }
  6467. this.material = source.material;
  6468. this.geometry = source.geometry;
  6469. return this;
  6470. }
  6471. updateMorphTargets() {
  6472. const geometry = this.geometry;
  6473. const morphAttributes = geometry.morphAttributes;
  6474. const keys = Object.keys( morphAttributes );
  6475. if ( keys.length > 0 ) {
  6476. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6477. if ( morphAttribute !== undefined ) {
  6478. this.morphTargetInfluences = [];
  6479. this.morphTargetDictionary = {};
  6480. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6481. const name = morphAttribute[ m ].name || String( m );
  6482. this.morphTargetInfluences.push( 0 );
  6483. this.morphTargetDictionary[ name ] = m;
  6484. }
  6485. }
  6486. }
  6487. }
  6488. getVertexPosition( index, target ) {
  6489. const geometry = this.geometry;
  6490. const position = geometry.attributes.position;
  6491. const morphPosition = geometry.morphAttributes.position;
  6492. const morphTargetsRelative = geometry.morphTargetsRelative;
  6493. target.fromBufferAttribute( position, index );
  6494. const morphInfluences = this.morphTargetInfluences;
  6495. if ( morphPosition && morphInfluences ) {
  6496. _morphA.set( 0, 0, 0 );
  6497. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6498. const influence = morphInfluences[ i ];
  6499. const morphAttribute = morphPosition[ i ];
  6500. if ( influence === 0 ) continue;
  6501. _tempA.fromBufferAttribute( morphAttribute, index );
  6502. if ( morphTargetsRelative ) {
  6503. _morphA.addScaledVector( _tempA, influence );
  6504. } else {
  6505. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6506. }
  6507. }
  6508. target.add( _morphA );
  6509. }
  6510. if ( this.isSkinnedMesh ) {
  6511. this.boneTransform( index, target );
  6512. }
  6513. return target;
  6514. }
  6515. raycast( raycaster, intersects ) {
  6516. const geometry = this.geometry;
  6517. const material = this.material;
  6518. const matrixWorld = this.matrixWorld;
  6519. if ( material === undefined ) return;
  6520. // Checking boundingSphere distance to ray
  6521. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6522. _sphere$3.copy( geometry.boundingSphere );
  6523. _sphere$3.applyMatrix4( matrixWorld );
  6524. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6525. //
  6526. _inverseMatrix$2.copy( matrixWorld ).invert();
  6527. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6528. // Check boundingBox before continuing
  6529. if ( geometry.boundingBox !== null ) {
  6530. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6531. }
  6532. let intersection;
  6533. const index = geometry.index;
  6534. const position = geometry.attributes.position;
  6535. const uv = geometry.attributes.uv;
  6536. const uv2 = geometry.attributes.uv2;
  6537. const groups = geometry.groups;
  6538. const drawRange = geometry.drawRange;
  6539. if ( index !== null ) {
  6540. // indexed buffer geometry
  6541. if ( Array.isArray( material ) ) {
  6542. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6543. const group = groups[ i ];
  6544. const groupMaterial = material[ group.materialIndex ];
  6545. const start = Math.max( group.start, drawRange.start );
  6546. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6547. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6548. const a = index.getX( j );
  6549. const b = index.getX( j + 1 );
  6550. const c = index.getX( j + 2 );
  6551. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6552. if ( intersection ) {
  6553. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6554. intersection.face.materialIndex = group.materialIndex;
  6555. intersects.push( intersection );
  6556. }
  6557. }
  6558. }
  6559. } else {
  6560. const start = Math.max( 0, drawRange.start );
  6561. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6562. for ( let i = start, il = end; i < il; i += 3 ) {
  6563. const a = index.getX( i );
  6564. const b = index.getX( i + 1 );
  6565. const c = index.getX( i + 2 );
  6566. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6567. if ( intersection ) {
  6568. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6569. intersects.push( intersection );
  6570. }
  6571. }
  6572. }
  6573. } else if ( position !== undefined ) {
  6574. // non-indexed buffer geometry
  6575. if ( Array.isArray( material ) ) {
  6576. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6577. const group = groups[ i ];
  6578. const groupMaterial = material[ group.materialIndex ];
  6579. const start = Math.max( group.start, drawRange.start );
  6580. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6581. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6582. const a = j;
  6583. const b = j + 1;
  6584. const c = j + 2;
  6585. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6586. if ( intersection ) {
  6587. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6588. intersection.face.materialIndex = group.materialIndex;
  6589. intersects.push( intersection );
  6590. }
  6591. }
  6592. }
  6593. } else {
  6594. const start = Math.max( 0, drawRange.start );
  6595. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6596. for ( let i = start, il = end; i < il; i += 3 ) {
  6597. const a = i;
  6598. const b = i + 1;
  6599. const c = i + 2;
  6600. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6601. if ( intersection ) {
  6602. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6603. intersects.push( intersection );
  6604. }
  6605. }
  6606. }
  6607. }
  6608. }
  6609. }
  6610. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6611. let intersect;
  6612. if ( material.side === BackSide ) {
  6613. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6614. } else {
  6615. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6616. }
  6617. if ( intersect === null ) return null;
  6618. _intersectionPointWorld.copy( point );
  6619. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6620. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6621. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6622. return {
  6623. distance: distance,
  6624. point: _intersectionPointWorld.clone(),
  6625. object: object
  6626. };
  6627. }
  6628. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6629. object.getVertexPosition( a, _vA$1 );
  6630. object.getVertexPosition( b, _vB$1 );
  6631. object.getVertexPosition( c, _vC$1 );
  6632. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6633. if ( intersection ) {
  6634. if ( uv ) {
  6635. _uvA$1.fromBufferAttribute( uv, a );
  6636. _uvB$1.fromBufferAttribute( uv, b );
  6637. _uvC$1.fromBufferAttribute( uv, c );
  6638. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6639. }
  6640. if ( uv2 ) {
  6641. _uvA$1.fromBufferAttribute( uv2, a );
  6642. _uvB$1.fromBufferAttribute( uv2, b );
  6643. _uvC$1.fromBufferAttribute( uv2, c );
  6644. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6645. }
  6646. const face = {
  6647. a: a,
  6648. b: b,
  6649. c: c,
  6650. normal: new Vector3(),
  6651. materialIndex: 0
  6652. };
  6653. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6654. intersection.face = face;
  6655. }
  6656. return intersection;
  6657. }
  6658. class BoxGeometry extends BufferGeometry {
  6659. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6660. super();
  6661. this.type = 'BoxGeometry';
  6662. this.parameters = {
  6663. width: width,
  6664. height: height,
  6665. depth: depth,
  6666. widthSegments: widthSegments,
  6667. heightSegments: heightSegments,
  6668. depthSegments: depthSegments
  6669. };
  6670. const scope = this;
  6671. // segments
  6672. widthSegments = Math.floor( widthSegments );
  6673. heightSegments = Math.floor( heightSegments );
  6674. depthSegments = Math.floor( depthSegments );
  6675. // buffers
  6676. const indices = [];
  6677. const vertices = [];
  6678. const normals = [];
  6679. const uvs = [];
  6680. // helper variables
  6681. let numberOfVertices = 0;
  6682. let groupStart = 0;
  6683. // build each side of the box geometry
  6684. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6685. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6686. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6687. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6688. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6689. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6690. // build geometry
  6691. this.setIndex( indices );
  6692. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6693. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6694. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6695. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6696. const segmentWidth = width / gridX;
  6697. const segmentHeight = height / gridY;
  6698. const widthHalf = width / 2;
  6699. const heightHalf = height / 2;
  6700. const depthHalf = depth / 2;
  6701. const gridX1 = gridX + 1;
  6702. const gridY1 = gridY + 1;
  6703. let vertexCounter = 0;
  6704. let groupCount = 0;
  6705. const vector = new Vector3();
  6706. // generate vertices, normals and uvs
  6707. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6708. const y = iy * segmentHeight - heightHalf;
  6709. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6710. const x = ix * segmentWidth - widthHalf;
  6711. // set values to correct vector component
  6712. vector[ u ] = x * udir;
  6713. vector[ v ] = y * vdir;
  6714. vector[ w ] = depthHalf;
  6715. // now apply vector to vertex buffer
  6716. vertices.push( vector.x, vector.y, vector.z );
  6717. // set values to correct vector component
  6718. vector[ u ] = 0;
  6719. vector[ v ] = 0;
  6720. vector[ w ] = depth > 0 ? 1 : - 1;
  6721. // now apply vector to normal buffer
  6722. normals.push( vector.x, vector.y, vector.z );
  6723. // uvs
  6724. uvs.push( ix / gridX );
  6725. uvs.push( 1 - ( iy / gridY ) );
  6726. // counters
  6727. vertexCounter += 1;
  6728. }
  6729. }
  6730. // indices
  6731. // 1. you need three indices to draw a single face
  6732. // 2. a single segment consists of two faces
  6733. // 3. so we need to generate six (2*3) indices per segment
  6734. for ( let iy = 0; iy < gridY; iy ++ ) {
  6735. for ( let ix = 0; ix < gridX; ix ++ ) {
  6736. const a = numberOfVertices + ix + gridX1 * iy;
  6737. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6738. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6739. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6740. // faces
  6741. indices.push( a, b, d );
  6742. indices.push( b, c, d );
  6743. // increase counter
  6744. groupCount += 6;
  6745. }
  6746. }
  6747. // add a group to the geometry. this will ensure multi material support
  6748. scope.addGroup( groupStart, groupCount, materialIndex );
  6749. // calculate new start value for groups
  6750. groupStart += groupCount;
  6751. // update total number of vertices
  6752. numberOfVertices += vertexCounter;
  6753. }
  6754. }
  6755. static fromJSON( data ) {
  6756. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6757. }
  6758. }
  6759. /**
  6760. * Uniform Utilities
  6761. */
  6762. function cloneUniforms( src ) {
  6763. const dst = {};
  6764. for ( const u in src ) {
  6765. dst[ u ] = {};
  6766. for ( const p in src[ u ] ) {
  6767. const property = src[ u ][ p ];
  6768. if ( property && ( property.isColor ||
  6769. property.isMatrix3 || property.isMatrix4 ||
  6770. property.isVector2 || property.isVector3 || property.isVector4 ||
  6771. property.isTexture || property.isQuaternion ) ) {
  6772. dst[ u ][ p ] = property.clone();
  6773. } else if ( Array.isArray( property ) ) {
  6774. dst[ u ][ p ] = property.slice();
  6775. } else {
  6776. dst[ u ][ p ] = property;
  6777. }
  6778. }
  6779. }
  6780. return dst;
  6781. }
  6782. function mergeUniforms( uniforms ) {
  6783. const merged = {};
  6784. for ( let u = 0; u < uniforms.length; u ++ ) {
  6785. const tmp = cloneUniforms( uniforms[ u ] );
  6786. for ( const p in tmp ) {
  6787. merged[ p ] = tmp[ p ];
  6788. }
  6789. }
  6790. return merged;
  6791. }
  6792. function cloneUniformsGroups( src ) {
  6793. const dst = [];
  6794. for ( let u = 0; u < src.length; u ++ ) {
  6795. dst.push( src[ u ].clone() );
  6796. }
  6797. return dst;
  6798. }
  6799. function getUnlitUniformColorSpace( renderer ) {
  6800. if ( renderer.getRenderTarget() === null ) {
  6801. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  6802. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  6803. }
  6804. return LinearSRGBColorSpace;
  6805. }
  6806. // Legacy
  6807. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6808. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6809. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6810. class ShaderMaterial extends Material {
  6811. constructor( parameters ) {
  6812. super();
  6813. this.isShaderMaterial = true;
  6814. this.type = 'ShaderMaterial';
  6815. this.defines = {};
  6816. this.uniforms = {};
  6817. this.uniformsGroups = [];
  6818. this.vertexShader = default_vertex;
  6819. this.fragmentShader = default_fragment;
  6820. this.linewidth = 1;
  6821. this.wireframe = false;
  6822. this.wireframeLinewidth = 1;
  6823. this.fog = false; // set to use scene fog
  6824. this.lights = false; // set to use scene lights
  6825. this.clipping = false; // set to use user-defined clipping planes
  6826. this.extensions = {
  6827. derivatives: false, // set to use derivatives
  6828. fragDepth: false, // set to use fragment depth values
  6829. drawBuffers: false, // set to use draw buffers
  6830. shaderTextureLOD: false // set to use shader texture LOD
  6831. };
  6832. // When rendered geometry doesn't include these attributes but the material does,
  6833. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6834. this.defaultAttributeValues = {
  6835. 'color': [ 1, 1, 1 ],
  6836. 'uv': [ 0, 0 ],
  6837. 'uv2': [ 0, 0 ]
  6838. };
  6839. this.index0AttributeName = undefined;
  6840. this.uniformsNeedUpdate = false;
  6841. this.glslVersion = null;
  6842. if ( parameters !== undefined ) {
  6843. this.setValues( parameters );
  6844. }
  6845. }
  6846. copy( source ) {
  6847. super.copy( source );
  6848. this.fragmentShader = source.fragmentShader;
  6849. this.vertexShader = source.vertexShader;
  6850. this.uniforms = cloneUniforms( source.uniforms );
  6851. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6852. this.defines = Object.assign( {}, source.defines );
  6853. this.wireframe = source.wireframe;
  6854. this.wireframeLinewidth = source.wireframeLinewidth;
  6855. this.fog = source.fog;
  6856. this.lights = source.lights;
  6857. this.clipping = source.clipping;
  6858. this.extensions = Object.assign( {}, source.extensions );
  6859. this.glslVersion = source.glslVersion;
  6860. return this;
  6861. }
  6862. toJSON( meta ) {
  6863. const data = super.toJSON( meta );
  6864. data.glslVersion = this.glslVersion;
  6865. data.uniforms = {};
  6866. for ( const name in this.uniforms ) {
  6867. const uniform = this.uniforms[ name ];
  6868. const value = uniform.value;
  6869. if ( value && value.isTexture ) {
  6870. data.uniforms[ name ] = {
  6871. type: 't',
  6872. value: value.toJSON( meta ).uuid
  6873. };
  6874. } else if ( value && value.isColor ) {
  6875. data.uniforms[ name ] = {
  6876. type: 'c',
  6877. value: value.getHex()
  6878. };
  6879. } else if ( value && value.isVector2 ) {
  6880. data.uniforms[ name ] = {
  6881. type: 'v2',
  6882. value: value.toArray()
  6883. };
  6884. } else if ( value && value.isVector3 ) {
  6885. data.uniforms[ name ] = {
  6886. type: 'v3',
  6887. value: value.toArray()
  6888. };
  6889. } else if ( value && value.isVector4 ) {
  6890. data.uniforms[ name ] = {
  6891. type: 'v4',
  6892. value: value.toArray()
  6893. };
  6894. } else if ( value && value.isMatrix3 ) {
  6895. data.uniforms[ name ] = {
  6896. type: 'm3',
  6897. value: value.toArray()
  6898. };
  6899. } else if ( value && value.isMatrix4 ) {
  6900. data.uniforms[ name ] = {
  6901. type: 'm4',
  6902. value: value.toArray()
  6903. };
  6904. } else {
  6905. data.uniforms[ name ] = {
  6906. value: value
  6907. };
  6908. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6909. }
  6910. }
  6911. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6912. data.vertexShader = this.vertexShader;
  6913. data.fragmentShader = this.fragmentShader;
  6914. const extensions = {};
  6915. for ( const key in this.extensions ) {
  6916. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6917. }
  6918. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6919. return data;
  6920. }
  6921. }
  6922. class Camera extends Object3D {
  6923. constructor() {
  6924. super();
  6925. this.isCamera = true;
  6926. this.type = 'Camera';
  6927. this.matrixWorldInverse = new Matrix4();
  6928. this.projectionMatrix = new Matrix4();
  6929. this.projectionMatrixInverse = new Matrix4();
  6930. }
  6931. copy( source, recursive ) {
  6932. super.copy( source, recursive );
  6933. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6934. this.projectionMatrix.copy( source.projectionMatrix );
  6935. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6936. return this;
  6937. }
  6938. getWorldDirection( target ) {
  6939. this.updateWorldMatrix( true, false );
  6940. const e = this.matrixWorld.elements;
  6941. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6942. }
  6943. updateMatrixWorld( force ) {
  6944. super.updateMatrixWorld( force );
  6945. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6946. }
  6947. updateWorldMatrix( updateParents, updateChildren ) {
  6948. super.updateWorldMatrix( updateParents, updateChildren );
  6949. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6950. }
  6951. clone() {
  6952. return new this.constructor().copy( this );
  6953. }
  6954. }
  6955. class PerspectiveCamera extends Camera {
  6956. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6957. super();
  6958. this.isPerspectiveCamera = true;
  6959. this.type = 'PerspectiveCamera';
  6960. this.fov = fov;
  6961. this.zoom = 1;
  6962. this.near = near;
  6963. this.far = far;
  6964. this.focus = 10;
  6965. this.aspect = aspect;
  6966. this.view = null;
  6967. this.filmGauge = 35; // width of the film (default in millimeters)
  6968. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6969. this.updateProjectionMatrix();
  6970. }
  6971. copy( source, recursive ) {
  6972. super.copy( source, recursive );
  6973. this.fov = source.fov;
  6974. this.zoom = source.zoom;
  6975. this.near = source.near;
  6976. this.far = source.far;
  6977. this.focus = source.focus;
  6978. this.aspect = source.aspect;
  6979. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6980. this.filmGauge = source.filmGauge;
  6981. this.filmOffset = source.filmOffset;
  6982. return this;
  6983. }
  6984. /**
  6985. * Sets the FOV by focal length in respect to the current .filmGauge.
  6986. *
  6987. * The default film gauge is 35, so that the focal length can be specified for
  6988. * a 35mm (full frame) camera.
  6989. *
  6990. * Values for focal length and film gauge must have the same unit.
  6991. */
  6992. setFocalLength( focalLength ) {
  6993. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6994. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6995. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6996. this.updateProjectionMatrix();
  6997. }
  6998. /**
  6999. * Calculates the focal length from the current .fov and .filmGauge.
  7000. */
  7001. getFocalLength() {
  7002. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7003. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7004. }
  7005. getEffectiveFOV() {
  7006. return RAD2DEG * 2 * Math.atan(
  7007. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7008. }
  7009. getFilmWidth() {
  7010. // film not completely covered in portrait format (aspect < 1)
  7011. return this.filmGauge * Math.min( this.aspect, 1 );
  7012. }
  7013. getFilmHeight() {
  7014. // film not completely covered in landscape format (aspect > 1)
  7015. return this.filmGauge / Math.max( this.aspect, 1 );
  7016. }
  7017. /**
  7018. * Sets an offset in a larger frustum. This is useful for multi-window or
  7019. * multi-monitor/multi-machine setups.
  7020. *
  7021. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7022. * the monitors are in grid like this
  7023. *
  7024. * +---+---+---+
  7025. * | A | B | C |
  7026. * +---+---+---+
  7027. * | D | E | F |
  7028. * +---+---+---+
  7029. *
  7030. * then for each monitor you would call it like this
  7031. *
  7032. * const w = 1920;
  7033. * const h = 1080;
  7034. * const fullWidth = w * 3;
  7035. * const fullHeight = h * 2;
  7036. *
  7037. * --A--
  7038. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7039. * --B--
  7040. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7041. * --C--
  7042. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7043. * --D--
  7044. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7045. * --E--
  7046. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7047. * --F--
  7048. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7049. *
  7050. * Note there is no reason monitors have to be the same size or in a grid.
  7051. */
  7052. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7053. this.aspect = fullWidth / fullHeight;
  7054. if ( this.view === null ) {
  7055. this.view = {
  7056. enabled: true,
  7057. fullWidth: 1,
  7058. fullHeight: 1,
  7059. offsetX: 0,
  7060. offsetY: 0,
  7061. width: 1,
  7062. height: 1
  7063. };
  7064. }
  7065. this.view.enabled = true;
  7066. this.view.fullWidth = fullWidth;
  7067. this.view.fullHeight = fullHeight;
  7068. this.view.offsetX = x;
  7069. this.view.offsetY = y;
  7070. this.view.width = width;
  7071. this.view.height = height;
  7072. this.updateProjectionMatrix();
  7073. }
  7074. clearViewOffset() {
  7075. if ( this.view !== null ) {
  7076. this.view.enabled = false;
  7077. }
  7078. this.updateProjectionMatrix();
  7079. }
  7080. updateProjectionMatrix() {
  7081. const near = this.near;
  7082. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7083. let height = 2 * top;
  7084. let width = this.aspect * height;
  7085. let left = - 0.5 * width;
  7086. const view = this.view;
  7087. if ( this.view !== null && this.view.enabled ) {
  7088. const fullWidth = view.fullWidth,
  7089. fullHeight = view.fullHeight;
  7090. left += view.offsetX * width / fullWidth;
  7091. top -= view.offsetY * height / fullHeight;
  7092. width *= view.width / fullWidth;
  7093. height *= view.height / fullHeight;
  7094. }
  7095. const skew = this.filmOffset;
  7096. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7097. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7098. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7099. }
  7100. toJSON( meta ) {
  7101. const data = super.toJSON( meta );
  7102. data.object.fov = this.fov;
  7103. data.object.zoom = this.zoom;
  7104. data.object.near = this.near;
  7105. data.object.far = this.far;
  7106. data.object.focus = this.focus;
  7107. data.object.aspect = this.aspect;
  7108. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7109. data.object.filmGauge = this.filmGauge;
  7110. data.object.filmOffset = this.filmOffset;
  7111. return data;
  7112. }
  7113. }
  7114. const fov = - 90; // negative fov is not an error
  7115. const aspect = 1;
  7116. class CubeCamera extends Object3D {
  7117. constructor( near, far, renderTarget ) {
  7118. super();
  7119. this.type = 'CubeCamera';
  7120. this.renderTarget = renderTarget;
  7121. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7122. cameraPX.layers = this.layers;
  7123. cameraPX.up.set( 0, 1, 0 );
  7124. cameraPX.lookAt( 1, 0, 0 );
  7125. this.add( cameraPX );
  7126. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7127. cameraNX.layers = this.layers;
  7128. cameraNX.up.set( 0, 1, 0 );
  7129. cameraNX.lookAt( - 1, 0, 0 );
  7130. this.add( cameraNX );
  7131. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7132. cameraPY.layers = this.layers;
  7133. cameraPY.up.set( 0, 0, - 1 );
  7134. cameraPY.lookAt( 0, 1, 0 );
  7135. this.add( cameraPY );
  7136. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7137. cameraNY.layers = this.layers;
  7138. cameraNY.up.set( 0, 0, 1 );
  7139. cameraNY.lookAt( 0, - 1, 0 );
  7140. this.add( cameraNY );
  7141. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7142. cameraPZ.layers = this.layers;
  7143. cameraPZ.up.set( 0, 1, 0 );
  7144. cameraPZ.lookAt( 0, 0, 1 );
  7145. this.add( cameraPZ );
  7146. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7147. cameraNZ.layers = this.layers;
  7148. cameraNZ.up.set( 0, 1, 0 );
  7149. cameraNZ.lookAt( 0, 0, - 1 );
  7150. this.add( cameraNZ );
  7151. }
  7152. update( renderer, scene ) {
  7153. if ( this.parent === null ) this.updateMatrixWorld();
  7154. const renderTarget = this.renderTarget;
  7155. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7156. const currentRenderTarget = renderer.getRenderTarget();
  7157. const currentToneMapping = renderer.toneMapping;
  7158. const currentXrEnabled = renderer.xr.enabled;
  7159. renderer.toneMapping = NoToneMapping;
  7160. renderer.xr.enabled = false;
  7161. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7162. renderTarget.texture.generateMipmaps = false;
  7163. renderer.setRenderTarget( renderTarget, 0 );
  7164. renderer.render( scene, cameraPX );
  7165. renderer.setRenderTarget( renderTarget, 1 );
  7166. renderer.render( scene, cameraNX );
  7167. renderer.setRenderTarget( renderTarget, 2 );
  7168. renderer.render( scene, cameraPY );
  7169. renderer.setRenderTarget( renderTarget, 3 );
  7170. renderer.render( scene, cameraNY );
  7171. renderer.setRenderTarget( renderTarget, 4 );
  7172. renderer.render( scene, cameraPZ );
  7173. renderTarget.texture.generateMipmaps = generateMipmaps;
  7174. renderer.setRenderTarget( renderTarget, 5 );
  7175. renderer.render( scene, cameraNZ );
  7176. renderer.setRenderTarget( currentRenderTarget );
  7177. renderer.toneMapping = currentToneMapping;
  7178. renderer.xr.enabled = currentXrEnabled;
  7179. renderTarget.texture.needsPMREMUpdate = true;
  7180. }
  7181. }
  7182. class CubeTexture extends Texture {
  7183. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7184. images = images !== undefined ? images : [];
  7185. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7186. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7187. this.isCubeTexture = true;
  7188. this.flipY = false;
  7189. }
  7190. get images() {
  7191. return this.image;
  7192. }
  7193. set images( value ) {
  7194. this.image = value;
  7195. }
  7196. }
  7197. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7198. constructor( size = 1, options = {} ) {
  7199. super( size, size, options );
  7200. this.isWebGLCubeRenderTarget = true;
  7201. const image = { width: size, height: size, depth: 1 };
  7202. const images = [ image, image, image, image, image, image ];
  7203. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7204. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7205. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7206. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7207. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7208. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7209. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7210. this.texture.isRenderTargetTexture = true;
  7211. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7212. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7213. }
  7214. fromEquirectangularTexture( renderer, texture ) {
  7215. this.texture.type = texture.type;
  7216. this.texture.encoding = texture.encoding;
  7217. this.texture.generateMipmaps = texture.generateMipmaps;
  7218. this.texture.minFilter = texture.minFilter;
  7219. this.texture.magFilter = texture.magFilter;
  7220. const shader = {
  7221. uniforms: {
  7222. tEquirect: { value: null },
  7223. },
  7224. vertexShader: /* glsl */`
  7225. varying vec3 vWorldDirection;
  7226. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7227. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7228. }
  7229. void main() {
  7230. vWorldDirection = transformDirection( position, modelMatrix );
  7231. #include <begin_vertex>
  7232. #include <project_vertex>
  7233. }
  7234. `,
  7235. fragmentShader: /* glsl */`
  7236. uniform sampler2D tEquirect;
  7237. varying vec3 vWorldDirection;
  7238. #include <common>
  7239. void main() {
  7240. vec3 direction = normalize( vWorldDirection );
  7241. vec2 sampleUV = equirectUv( direction );
  7242. gl_FragColor = texture2D( tEquirect, sampleUV );
  7243. }
  7244. `
  7245. };
  7246. const geometry = new BoxGeometry( 5, 5, 5 );
  7247. const material = new ShaderMaterial( {
  7248. name: 'CubemapFromEquirect',
  7249. uniforms: cloneUniforms( shader.uniforms ),
  7250. vertexShader: shader.vertexShader,
  7251. fragmentShader: shader.fragmentShader,
  7252. side: BackSide,
  7253. blending: NoBlending
  7254. } );
  7255. material.uniforms.tEquirect.value = texture;
  7256. const mesh = new Mesh( geometry, material );
  7257. const currentMinFilter = texture.minFilter;
  7258. // Avoid blurred poles
  7259. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7260. const camera = new CubeCamera( 1, 10, this );
  7261. camera.update( renderer, mesh );
  7262. texture.minFilter = currentMinFilter;
  7263. mesh.geometry.dispose();
  7264. mesh.material.dispose();
  7265. return this;
  7266. }
  7267. clear( renderer, color, depth, stencil ) {
  7268. const currentRenderTarget = renderer.getRenderTarget();
  7269. for ( let i = 0; i < 6; i ++ ) {
  7270. renderer.setRenderTarget( this, i );
  7271. renderer.clear( color, depth, stencil );
  7272. }
  7273. renderer.setRenderTarget( currentRenderTarget );
  7274. }
  7275. }
  7276. const _vector1 = /*@__PURE__*/ new Vector3();
  7277. const _vector2 = /*@__PURE__*/ new Vector3();
  7278. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7279. class Plane {
  7280. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7281. this.isPlane = true;
  7282. // normal is assumed to be normalized
  7283. this.normal = normal;
  7284. this.constant = constant;
  7285. }
  7286. set( normal, constant ) {
  7287. this.normal.copy( normal );
  7288. this.constant = constant;
  7289. return this;
  7290. }
  7291. setComponents( x, y, z, w ) {
  7292. this.normal.set( x, y, z );
  7293. this.constant = w;
  7294. return this;
  7295. }
  7296. setFromNormalAndCoplanarPoint( normal, point ) {
  7297. this.normal.copy( normal );
  7298. this.constant = - point.dot( this.normal );
  7299. return this;
  7300. }
  7301. setFromCoplanarPoints( a, b, c ) {
  7302. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7303. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7304. this.setFromNormalAndCoplanarPoint( normal, a );
  7305. return this;
  7306. }
  7307. copy( plane ) {
  7308. this.normal.copy( plane.normal );
  7309. this.constant = plane.constant;
  7310. return this;
  7311. }
  7312. normalize() {
  7313. // Note: will lead to a divide by zero if the plane is invalid.
  7314. const inverseNormalLength = 1.0 / this.normal.length();
  7315. this.normal.multiplyScalar( inverseNormalLength );
  7316. this.constant *= inverseNormalLength;
  7317. return this;
  7318. }
  7319. negate() {
  7320. this.constant *= - 1;
  7321. this.normal.negate();
  7322. return this;
  7323. }
  7324. distanceToPoint( point ) {
  7325. return this.normal.dot( point ) + this.constant;
  7326. }
  7327. distanceToSphere( sphere ) {
  7328. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7329. }
  7330. projectPoint( point, target ) {
  7331. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7332. }
  7333. intersectLine( line, target ) {
  7334. const direction = line.delta( _vector1 );
  7335. const denominator = this.normal.dot( direction );
  7336. if ( denominator === 0 ) {
  7337. // line is coplanar, return origin
  7338. if ( this.distanceToPoint( line.start ) === 0 ) {
  7339. return target.copy( line.start );
  7340. }
  7341. // Unsure if this is the correct method to handle this case.
  7342. return null;
  7343. }
  7344. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7345. if ( t < 0 || t > 1 ) {
  7346. return null;
  7347. }
  7348. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7349. }
  7350. intersectsLine( line ) {
  7351. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7352. const startSign = this.distanceToPoint( line.start );
  7353. const endSign = this.distanceToPoint( line.end );
  7354. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7355. }
  7356. intersectsBox( box ) {
  7357. return box.intersectsPlane( this );
  7358. }
  7359. intersectsSphere( sphere ) {
  7360. return sphere.intersectsPlane( this );
  7361. }
  7362. coplanarPoint( target ) {
  7363. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7364. }
  7365. applyMatrix4( matrix, optionalNormalMatrix ) {
  7366. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7367. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7368. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7369. this.constant = - referencePoint.dot( normal );
  7370. return this;
  7371. }
  7372. translate( offset ) {
  7373. this.constant -= offset.dot( this.normal );
  7374. return this;
  7375. }
  7376. equals( plane ) {
  7377. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7378. }
  7379. clone() {
  7380. return new this.constructor().copy( this );
  7381. }
  7382. }
  7383. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7384. const _vector$7 = /*@__PURE__*/ new Vector3();
  7385. class Frustum {
  7386. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7387. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7388. }
  7389. set( p0, p1, p2, p3, p4, p5 ) {
  7390. const planes = this.planes;
  7391. planes[ 0 ].copy( p0 );
  7392. planes[ 1 ].copy( p1 );
  7393. planes[ 2 ].copy( p2 );
  7394. planes[ 3 ].copy( p3 );
  7395. planes[ 4 ].copy( p4 );
  7396. planes[ 5 ].copy( p5 );
  7397. return this;
  7398. }
  7399. copy( frustum ) {
  7400. const planes = this.planes;
  7401. for ( let i = 0; i < 6; i ++ ) {
  7402. planes[ i ].copy( frustum.planes[ i ] );
  7403. }
  7404. return this;
  7405. }
  7406. setFromProjectionMatrix( m ) {
  7407. const planes = this.planes;
  7408. const me = m.elements;
  7409. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7410. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7411. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7412. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7413. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7414. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7415. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7416. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7417. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7418. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7419. return this;
  7420. }
  7421. intersectsObject( object ) {
  7422. const geometry = object.geometry;
  7423. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7424. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7425. return this.intersectsSphere( _sphere$2 );
  7426. }
  7427. intersectsSprite( sprite ) {
  7428. _sphere$2.center.set( 0, 0, 0 );
  7429. _sphere$2.radius = 0.7071067811865476;
  7430. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7431. return this.intersectsSphere( _sphere$2 );
  7432. }
  7433. intersectsSphere( sphere ) {
  7434. const planes = this.planes;
  7435. const center = sphere.center;
  7436. const negRadius = - sphere.radius;
  7437. for ( let i = 0; i < 6; i ++ ) {
  7438. const distance = planes[ i ].distanceToPoint( center );
  7439. if ( distance < negRadius ) {
  7440. return false;
  7441. }
  7442. }
  7443. return true;
  7444. }
  7445. intersectsBox( box ) {
  7446. const planes = this.planes;
  7447. for ( let i = 0; i < 6; i ++ ) {
  7448. const plane = planes[ i ];
  7449. // corner at max distance
  7450. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7451. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7452. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7453. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7454. return false;
  7455. }
  7456. }
  7457. return true;
  7458. }
  7459. containsPoint( point ) {
  7460. const planes = this.planes;
  7461. for ( let i = 0; i < 6; i ++ ) {
  7462. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7463. return false;
  7464. }
  7465. }
  7466. return true;
  7467. }
  7468. clone() {
  7469. return new this.constructor().copy( this );
  7470. }
  7471. }
  7472. function WebGLAnimation() {
  7473. let context = null;
  7474. let isAnimating = false;
  7475. let animationLoop = null;
  7476. let requestId = null;
  7477. function onAnimationFrame( time, frame ) {
  7478. animationLoop( time, frame );
  7479. requestId = context.requestAnimationFrame( onAnimationFrame );
  7480. }
  7481. return {
  7482. start: function () {
  7483. if ( isAnimating === true ) return;
  7484. if ( animationLoop === null ) return;
  7485. requestId = context.requestAnimationFrame( onAnimationFrame );
  7486. isAnimating = true;
  7487. },
  7488. stop: function () {
  7489. context.cancelAnimationFrame( requestId );
  7490. isAnimating = false;
  7491. },
  7492. setAnimationLoop: function ( callback ) {
  7493. animationLoop = callback;
  7494. },
  7495. setContext: function ( value ) {
  7496. context = value;
  7497. }
  7498. };
  7499. }
  7500. function WebGLAttributes( gl, capabilities ) {
  7501. const isWebGL2 = capabilities.isWebGL2;
  7502. const buffers = new WeakMap();
  7503. function createBuffer( attribute, bufferType ) {
  7504. const array = attribute.array;
  7505. const usage = attribute.usage;
  7506. const buffer = gl.createBuffer();
  7507. gl.bindBuffer( bufferType, buffer );
  7508. gl.bufferData( bufferType, array, usage );
  7509. attribute.onUploadCallback();
  7510. let type;
  7511. if ( array instanceof Float32Array ) {
  7512. type = gl.FLOAT;
  7513. } else if ( array instanceof Uint16Array ) {
  7514. if ( attribute.isFloat16BufferAttribute ) {
  7515. if ( isWebGL2 ) {
  7516. type = gl.HALF_FLOAT;
  7517. } else {
  7518. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7519. }
  7520. } else {
  7521. type = gl.UNSIGNED_SHORT;
  7522. }
  7523. } else if ( array instanceof Int16Array ) {
  7524. type = gl.SHORT;
  7525. } else if ( array instanceof Uint32Array ) {
  7526. type = gl.UNSIGNED_INT;
  7527. } else if ( array instanceof Int32Array ) {
  7528. type = gl.INT;
  7529. } else if ( array instanceof Int8Array ) {
  7530. type = gl.BYTE;
  7531. } else if ( array instanceof Uint8Array ) {
  7532. type = gl.UNSIGNED_BYTE;
  7533. } else if ( array instanceof Uint8ClampedArray ) {
  7534. type = gl.UNSIGNED_BYTE;
  7535. } else {
  7536. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7537. }
  7538. return {
  7539. buffer: buffer,
  7540. type: type,
  7541. bytesPerElement: array.BYTES_PER_ELEMENT,
  7542. version: attribute.version
  7543. };
  7544. }
  7545. function updateBuffer( buffer, attribute, bufferType ) {
  7546. const array = attribute.array;
  7547. const updateRange = attribute.updateRange;
  7548. gl.bindBuffer( bufferType, buffer );
  7549. if ( updateRange.count === - 1 ) {
  7550. // Not using update ranges
  7551. gl.bufferSubData( bufferType, 0, array );
  7552. } else {
  7553. if ( isWebGL2 ) {
  7554. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7555. array, updateRange.offset, updateRange.count );
  7556. } else {
  7557. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7558. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7559. }
  7560. updateRange.count = - 1; // reset range
  7561. }
  7562. attribute.onUploadCallback();
  7563. }
  7564. //
  7565. function get( attribute ) {
  7566. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7567. return buffers.get( attribute );
  7568. }
  7569. function remove( attribute ) {
  7570. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7571. const data = buffers.get( attribute );
  7572. if ( data ) {
  7573. gl.deleteBuffer( data.buffer );
  7574. buffers.delete( attribute );
  7575. }
  7576. }
  7577. function update( attribute, bufferType ) {
  7578. if ( attribute.isGLBufferAttribute ) {
  7579. const cached = buffers.get( attribute );
  7580. if ( ! cached || cached.version < attribute.version ) {
  7581. buffers.set( attribute, {
  7582. buffer: attribute.buffer,
  7583. type: attribute.type,
  7584. bytesPerElement: attribute.elementSize,
  7585. version: attribute.version
  7586. } );
  7587. }
  7588. return;
  7589. }
  7590. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7591. const data = buffers.get( attribute );
  7592. if ( data === undefined ) {
  7593. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7594. } else if ( data.version < attribute.version ) {
  7595. updateBuffer( data.buffer, attribute, bufferType );
  7596. data.version = attribute.version;
  7597. }
  7598. }
  7599. return {
  7600. get: get,
  7601. remove: remove,
  7602. update: update
  7603. };
  7604. }
  7605. class PlaneGeometry extends BufferGeometry {
  7606. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7607. super();
  7608. this.type = 'PlaneGeometry';
  7609. this.parameters = {
  7610. width: width,
  7611. height: height,
  7612. widthSegments: widthSegments,
  7613. heightSegments: heightSegments
  7614. };
  7615. const width_half = width / 2;
  7616. const height_half = height / 2;
  7617. const gridX = Math.floor( widthSegments );
  7618. const gridY = Math.floor( heightSegments );
  7619. const gridX1 = gridX + 1;
  7620. const gridY1 = gridY + 1;
  7621. const segment_width = width / gridX;
  7622. const segment_height = height / gridY;
  7623. //
  7624. const indices = [];
  7625. const vertices = [];
  7626. const normals = [];
  7627. const uvs = [];
  7628. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7629. const y = iy * segment_height - height_half;
  7630. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7631. const x = ix * segment_width - width_half;
  7632. vertices.push( x, - y, 0 );
  7633. normals.push( 0, 0, 1 );
  7634. uvs.push( ix / gridX );
  7635. uvs.push( 1 - ( iy / gridY ) );
  7636. }
  7637. }
  7638. for ( let iy = 0; iy < gridY; iy ++ ) {
  7639. for ( let ix = 0; ix < gridX; ix ++ ) {
  7640. const a = ix + gridX1 * iy;
  7641. const b = ix + gridX1 * ( iy + 1 );
  7642. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7643. const d = ( ix + 1 ) + gridX1 * iy;
  7644. indices.push( a, b, d );
  7645. indices.push( b, c, d );
  7646. }
  7647. }
  7648. this.setIndex( indices );
  7649. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7650. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7651. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7652. }
  7653. static fromJSON( data ) {
  7654. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7655. }
  7656. }
  7657. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7658. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7659. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7660. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7661. 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";
  7662. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7663. var begin_vertex = "vec3 transformed = vec3( position );";
  7664. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7665. 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";
  7666. 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";
  7667. 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";
  7668. 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";
  7669. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7670. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7671. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7672. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7673. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7674. 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";
  7675. 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";
  7676. 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}";
  7677. 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";
  7678. 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";
  7679. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7680. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7681. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7682. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7683. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7684. 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}";
  7685. 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";
  7686. 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";
  7687. 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";
  7688. 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";
  7689. 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";
  7690. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7691. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7692. 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";
  7693. 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";
  7694. 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}";
  7695. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7696. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7697. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7698. 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";
  7699. 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";
  7700. 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";
  7701. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7702. 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";
  7703. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7704. 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";
  7705. 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";
  7706. 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}";
  7707. 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";
  7708. 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";
  7709. 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";
  7710. 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";
  7711. 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";
  7712. 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";
  7713. 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";
  7714. 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";
  7715. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7716. 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";
  7717. 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";
  7718. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7719. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7720. 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";
  7721. 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";
  7722. 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";
  7723. 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";
  7724. 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;";
  7725. 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";
  7726. 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";
  7727. 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";
  7728. 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";
  7729. 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";
  7730. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7731. 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";
  7732. 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";
  7733. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7734. 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 );";
  7735. 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}";
  7736. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7737. 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;";
  7738. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7739. 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";
  7740. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7741. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7742. 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";
  7743. 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";
  7744. 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";
  7745. 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}";
  7746. 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";
  7747. 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";
  7748. 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";
  7749. 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";
  7750. 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";
  7751. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7752. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7753. 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; }";
  7754. 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";
  7755. 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";
  7756. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7757. 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";
  7758. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7759. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7760. 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";
  7761. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7762. 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";
  7763. 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}";
  7764. 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}";
  7765. 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}";
  7766. 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}";
  7767. 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}";
  7768. 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}";
  7769. 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}";
  7770. 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}";
  7771. 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}";
  7772. 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}";
  7773. 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}";
  7774. 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}";
  7775. 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}";
  7776. 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}";
  7777. 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}";
  7778. 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}";
  7779. 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}";
  7780. 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}";
  7781. 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}";
  7782. 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}";
  7783. 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}";
  7784. 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}";
  7785. 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}";
  7786. 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}";
  7787. 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}";
  7788. 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}";
  7789. 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}";
  7790. 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}";
  7791. 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}";
  7792. 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}";
  7793. 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}";
  7794. 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}";
  7795. 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}";
  7796. 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}";
  7797. const ShaderChunk = {
  7798. alphamap_fragment: alphamap_fragment,
  7799. alphamap_pars_fragment: alphamap_pars_fragment,
  7800. alphatest_fragment: alphatest_fragment,
  7801. alphatest_pars_fragment: alphatest_pars_fragment,
  7802. aomap_fragment: aomap_fragment,
  7803. aomap_pars_fragment: aomap_pars_fragment,
  7804. begin_vertex: begin_vertex,
  7805. beginnormal_vertex: beginnormal_vertex,
  7806. bsdfs: bsdfs,
  7807. iridescence_fragment: iridescence_fragment,
  7808. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7809. clipping_planes_fragment: clipping_planes_fragment,
  7810. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7811. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7812. clipping_planes_vertex: clipping_planes_vertex,
  7813. color_fragment: color_fragment,
  7814. color_pars_fragment: color_pars_fragment,
  7815. color_pars_vertex: color_pars_vertex,
  7816. color_vertex: color_vertex,
  7817. common: common,
  7818. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7819. defaultnormal_vertex: defaultnormal_vertex,
  7820. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7821. displacementmap_vertex: displacementmap_vertex,
  7822. emissivemap_fragment: emissivemap_fragment,
  7823. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7824. encodings_fragment: encodings_fragment,
  7825. encodings_pars_fragment: encodings_pars_fragment,
  7826. envmap_fragment: envmap_fragment,
  7827. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7828. envmap_pars_fragment: envmap_pars_fragment,
  7829. envmap_pars_vertex: envmap_pars_vertex,
  7830. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7831. envmap_vertex: envmap_vertex,
  7832. fog_vertex: fog_vertex,
  7833. fog_pars_vertex: fog_pars_vertex,
  7834. fog_fragment: fog_fragment,
  7835. fog_pars_fragment: fog_pars_fragment,
  7836. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7837. lightmap_fragment: lightmap_fragment,
  7838. lightmap_pars_fragment: lightmap_pars_fragment,
  7839. lights_lambert_fragment: lights_lambert_fragment,
  7840. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7841. lights_pars_begin: lights_pars_begin,
  7842. lights_toon_fragment: lights_toon_fragment,
  7843. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7844. lights_phong_fragment: lights_phong_fragment,
  7845. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7846. lights_physical_fragment: lights_physical_fragment,
  7847. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7848. lights_fragment_begin: lights_fragment_begin,
  7849. lights_fragment_maps: lights_fragment_maps,
  7850. lights_fragment_end: lights_fragment_end,
  7851. logdepthbuf_fragment: logdepthbuf_fragment,
  7852. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7853. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7854. logdepthbuf_vertex: logdepthbuf_vertex,
  7855. map_fragment: map_fragment,
  7856. map_pars_fragment: map_pars_fragment,
  7857. map_particle_fragment: map_particle_fragment,
  7858. map_particle_pars_fragment: map_particle_pars_fragment,
  7859. metalnessmap_fragment: metalnessmap_fragment,
  7860. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7861. morphcolor_vertex: morphcolor_vertex,
  7862. morphnormal_vertex: morphnormal_vertex,
  7863. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7864. morphtarget_vertex: morphtarget_vertex,
  7865. normal_fragment_begin: normal_fragment_begin,
  7866. normal_fragment_maps: normal_fragment_maps,
  7867. normal_pars_fragment: normal_pars_fragment,
  7868. normal_pars_vertex: normal_pars_vertex,
  7869. normal_vertex: normal_vertex,
  7870. normalmap_pars_fragment: normalmap_pars_fragment,
  7871. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7872. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7873. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7874. iridescence_pars_fragment: iridescence_pars_fragment,
  7875. output_fragment: output_fragment,
  7876. packing: packing,
  7877. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7878. project_vertex: project_vertex,
  7879. dithering_fragment: dithering_fragment,
  7880. dithering_pars_fragment: dithering_pars_fragment,
  7881. roughnessmap_fragment: roughnessmap_fragment,
  7882. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7883. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7884. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7885. shadowmap_vertex: shadowmap_vertex,
  7886. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7887. skinbase_vertex: skinbase_vertex,
  7888. skinning_pars_vertex: skinning_pars_vertex,
  7889. skinning_vertex: skinning_vertex,
  7890. skinnormal_vertex: skinnormal_vertex,
  7891. specularmap_fragment: specularmap_fragment,
  7892. specularmap_pars_fragment: specularmap_pars_fragment,
  7893. tonemapping_fragment: tonemapping_fragment,
  7894. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7895. transmission_fragment: transmission_fragment,
  7896. transmission_pars_fragment: transmission_pars_fragment,
  7897. uv_pars_fragment: uv_pars_fragment,
  7898. uv_pars_vertex: uv_pars_vertex,
  7899. uv_vertex: uv_vertex,
  7900. uv2_pars_fragment: uv2_pars_fragment,
  7901. uv2_pars_vertex: uv2_pars_vertex,
  7902. uv2_vertex: uv2_vertex,
  7903. worldpos_vertex: worldpos_vertex,
  7904. background_vert: vertex$h,
  7905. background_frag: fragment$h,
  7906. backgroundCube_vert: vertex$g,
  7907. backgroundCube_frag: fragment$g,
  7908. cube_vert: vertex$f,
  7909. cube_frag: fragment$f,
  7910. depth_vert: vertex$e,
  7911. depth_frag: fragment$e,
  7912. distanceRGBA_vert: vertex$d,
  7913. distanceRGBA_frag: fragment$d,
  7914. equirect_vert: vertex$c,
  7915. equirect_frag: fragment$c,
  7916. linedashed_vert: vertex$b,
  7917. linedashed_frag: fragment$b,
  7918. meshbasic_vert: vertex$a,
  7919. meshbasic_frag: fragment$a,
  7920. meshlambert_vert: vertex$9,
  7921. meshlambert_frag: fragment$9,
  7922. meshmatcap_vert: vertex$8,
  7923. meshmatcap_frag: fragment$8,
  7924. meshnormal_vert: vertex$7,
  7925. meshnormal_frag: fragment$7,
  7926. meshphong_vert: vertex$6,
  7927. meshphong_frag: fragment$6,
  7928. meshphysical_vert: vertex$5,
  7929. meshphysical_frag: fragment$5,
  7930. meshtoon_vert: vertex$4,
  7931. meshtoon_frag: fragment$4,
  7932. points_vert: vertex$3,
  7933. points_frag: fragment$3,
  7934. shadow_vert: vertex$2,
  7935. shadow_frag: fragment$2,
  7936. sprite_vert: vertex$1,
  7937. sprite_frag: fragment$1
  7938. };
  7939. /**
  7940. * Uniforms library for shared webgl shaders
  7941. */
  7942. const UniformsLib = {
  7943. common: {
  7944. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7945. opacity: { value: 1.0 },
  7946. map: { value: null },
  7947. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7948. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7949. alphaMap: { value: null },
  7950. alphaTest: { value: 0 }
  7951. },
  7952. specularmap: {
  7953. specularMap: { value: null },
  7954. },
  7955. envmap: {
  7956. envMap: { value: null },
  7957. flipEnvMap: { value: - 1 },
  7958. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7959. ior: { value: 1.5 }, // physical
  7960. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  7961. },
  7962. aomap: {
  7963. aoMap: { value: null },
  7964. aoMapIntensity: { value: 1 }
  7965. },
  7966. lightmap: {
  7967. lightMap: { value: null },
  7968. lightMapIntensity: { value: 1 }
  7969. },
  7970. emissivemap: {
  7971. emissiveMap: { value: null }
  7972. },
  7973. bumpmap: {
  7974. bumpMap: { value: null },
  7975. bumpScale: { value: 1 }
  7976. },
  7977. normalmap: {
  7978. normalMap: { value: null },
  7979. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  7980. },
  7981. displacementmap: {
  7982. displacementMap: { value: null },
  7983. displacementScale: { value: 1 },
  7984. displacementBias: { value: 0 }
  7985. },
  7986. roughnessmap: {
  7987. roughnessMap: { value: null }
  7988. },
  7989. metalnessmap: {
  7990. metalnessMap: { value: null }
  7991. },
  7992. gradientmap: {
  7993. gradientMap: { value: null }
  7994. },
  7995. fog: {
  7996. fogDensity: { value: 0.00025 },
  7997. fogNear: { value: 1 },
  7998. fogFar: { value: 2000 },
  7999. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8000. },
  8001. lights: {
  8002. ambientLightColor: { value: [] },
  8003. lightProbe: { value: [] },
  8004. directionalLights: { value: [], properties: {
  8005. direction: {},
  8006. color: {}
  8007. } },
  8008. directionalLightShadows: { value: [], properties: {
  8009. shadowBias: {},
  8010. shadowNormalBias: {},
  8011. shadowRadius: {},
  8012. shadowMapSize: {}
  8013. } },
  8014. directionalShadowMap: { value: [] },
  8015. directionalShadowMatrix: { value: [] },
  8016. spotLights: { value: [], properties: {
  8017. color: {},
  8018. position: {},
  8019. direction: {},
  8020. distance: {},
  8021. coneCos: {},
  8022. penumbraCos: {},
  8023. decay: {}
  8024. } },
  8025. spotLightShadows: { value: [], properties: {
  8026. shadowBias: {},
  8027. shadowNormalBias: {},
  8028. shadowRadius: {},
  8029. shadowMapSize: {}
  8030. } },
  8031. spotLightMap: { value: [] },
  8032. spotShadowMap: { value: [] },
  8033. spotLightMatrix: { value: [] },
  8034. pointLights: { value: [], properties: {
  8035. color: {},
  8036. position: {},
  8037. decay: {},
  8038. distance: {}
  8039. } },
  8040. pointLightShadows: { value: [], properties: {
  8041. shadowBias: {},
  8042. shadowNormalBias: {},
  8043. shadowRadius: {},
  8044. shadowMapSize: {},
  8045. shadowCameraNear: {},
  8046. shadowCameraFar: {}
  8047. } },
  8048. pointShadowMap: { value: [] },
  8049. pointShadowMatrix: { value: [] },
  8050. hemisphereLights: { value: [], properties: {
  8051. direction: {},
  8052. skyColor: {},
  8053. groundColor: {}
  8054. } },
  8055. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8056. rectAreaLights: { value: [], properties: {
  8057. color: {},
  8058. position: {},
  8059. width: {},
  8060. height: {}
  8061. } },
  8062. ltc_1: { value: null },
  8063. ltc_2: { value: null }
  8064. },
  8065. points: {
  8066. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8067. opacity: { value: 1.0 },
  8068. size: { value: 1.0 },
  8069. scale: { value: 1.0 },
  8070. map: { value: null },
  8071. alphaMap: { value: null },
  8072. alphaTest: { value: 0 },
  8073. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8074. },
  8075. sprite: {
  8076. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8077. opacity: { value: 1.0 },
  8078. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8079. rotation: { value: 0.0 },
  8080. map: { value: null },
  8081. alphaMap: { value: null },
  8082. alphaTest: { value: 0 },
  8083. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8084. }
  8085. };
  8086. const ShaderLib = {
  8087. basic: {
  8088. uniforms: /*@__PURE__*/ mergeUniforms( [
  8089. UniformsLib.common,
  8090. UniformsLib.specularmap,
  8091. UniformsLib.envmap,
  8092. UniformsLib.aomap,
  8093. UniformsLib.lightmap,
  8094. UniformsLib.fog
  8095. ] ),
  8096. vertexShader: ShaderChunk.meshbasic_vert,
  8097. fragmentShader: ShaderChunk.meshbasic_frag
  8098. },
  8099. lambert: {
  8100. uniforms: /*@__PURE__*/ mergeUniforms( [
  8101. UniformsLib.common,
  8102. UniformsLib.specularmap,
  8103. UniformsLib.envmap,
  8104. UniformsLib.aomap,
  8105. UniformsLib.lightmap,
  8106. UniformsLib.emissivemap,
  8107. UniformsLib.bumpmap,
  8108. UniformsLib.normalmap,
  8109. UniformsLib.displacementmap,
  8110. UniformsLib.fog,
  8111. UniformsLib.lights,
  8112. {
  8113. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8114. }
  8115. ] ),
  8116. vertexShader: ShaderChunk.meshlambert_vert,
  8117. fragmentShader: ShaderChunk.meshlambert_frag
  8118. },
  8119. phong: {
  8120. uniforms: /*@__PURE__*/ mergeUniforms( [
  8121. UniformsLib.common,
  8122. UniformsLib.specularmap,
  8123. UniformsLib.envmap,
  8124. UniformsLib.aomap,
  8125. UniformsLib.lightmap,
  8126. UniformsLib.emissivemap,
  8127. UniformsLib.bumpmap,
  8128. UniformsLib.normalmap,
  8129. UniformsLib.displacementmap,
  8130. UniformsLib.fog,
  8131. UniformsLib.lights,
  8132. {
  8133. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8134. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8135. shininess: { value: 30 }
  8136. }
  8137. ] ),
  8138. vertexShader: ShaderChunk.meshphong_vert,
  8139. fragmentShader: ShaderChunk.meshphong_frag
  8140. },
  8141. standard: {
  8142. uniforms: /*@__PURE__*/ mergeUniforms( [
  8143. UniformsLib.common,
  8144. UniformsLib.envmap,
  8145. UniformsLib.aomap,
  8146. UniformsLib.lightmap,
  8147. UniformsLib.emissivemap,
  8148. UniformsLib.bumpmap,
  8149. UniformsLib.normalmap,
  8150. UniformsLib.displacementmap,
  8151. UniformsLib.roughnessmap,
  8152. UniformsLib.metalnessmap,
  8153. UniformsLib.fog,
  8154. UniformsLib.lights,
  8155. {
  8156. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8157. roughness: { value: 1.0 },
  8158. metalness: { value: 0.0 },
  8159. envMapIntensity: { value: 1 } // temporary
  8160. }
  8161. ] ),
  8162. vertexShader: ShaderChunk.meshphysical_vert,
  8163. fragmentShader: ShaderChunk.meshphysical_frag
  8164. },
  8165. toon: {
  8166. uniforms: /*@__PURE__*/ mergeUniforms( [
  8167. UniformsLib.common,
  8168. UniformsLib.aomap,
  8169. UniformsLib.lightmap,
  8170. UniformsLib.emissivemap,
  8171. UniformsLib.bumpmap,
  8172. UniformsLib.normalmap,
  8173. UniformsLib.displacementmap,
  8174. UniformsLib.gradientmap,
  8175. UniformsLib.fog,
  8176. UniformsLib.lights,
  8177. {
  8178. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8179. }
  8180. ] ),
  8181. vertexShader: ShaderChunk.meshtoon_vert,
  8182. fragmentShader: ShaderChunk.meshtoon_frag
  8183. },
  8184. matcap: {
  8185. uniforms: /*@__PURE__*/ mergeUniforms( [
  8186. UniformsLib.common,
  8187. UniformsLib.bumpmap,
  8188. UniformsLib.normalmap,
  8189. UniformsLib.displacementmap,
  8190. UniformsLib.fog,
  8191. {
  8192. matcap: { value: null }
  8193. }
  8194. ] ),
  8195. vertexShader: ShaderChunk.meshmatcap_vert,
  8196. fragmentShader: ShaderChunk.meshmatcap_frag
  8197. },
  8198. points: {
  8199. uniforms: /*@__PURE__*/ mergeUniforms( [
  8200. UniformsLib.points,
  8201. UniformsLib.fog
  8202. ] ),
  8203. vertexShader: ShaderChunk.points_vert,
  8204. fragmentShader: ShaderChunk.points_frag
  8205. },
  8206. dashed: {
  8207. uniforms: /*@__PURE__*/ mergeUniforms( [
  8208. UniformsLib.common,
  8209. UniformsLib.fog,
  8210. {
  8211. scale: { value: 1 },
  8212. dashSize: { value: 1 },
  8213. totalSize: { value: 2 }
  8214. }
  8215. ] ),
  8216. vertexShader: ShaderChunk.linedashed_vert,
  8217. fragmentShader: ShaderChunk.linedashed_frag
  8218. },
  8219. depth: {
  8220. uniforms: /*@__PURE__*/ mergeUniforms( [
  8221. UniformsLib.common,
  8222. UniformsLib.displacementmap
  8223. ] ),
  8224. vertexShader: ShaderChunk.depth_vert,
  8225. fragmentShader: ShaderChunk.depth_frag
  8226. },
  8227. normal: {
  8228. uniforms: /*@__PURE__*/ mergeUniforms( [
  8229. UniformsLib.common,
  8230. UniformsLib.bumpmap,
  8231. UniformsLib.normalmap,
  8232. UniformsLib.displacementmap,
  8233. {
  8234. opacity: { value: 1.0 }
  8235. }
  8236. ] ),
  8237. vertexShader: ShaderChunk.meshnormal_vert,
  8238. fragmentShader: ShaderChunk.meshnormal_frag
  8239. },
  8240. sprite: {
  8241. uniforms: /*@__PURE__*/ mergeUniforms( [
  8242. UniformsLib.sprite,
  8243. UniformsLib.fog
  8244. ] ),
  8245. vertexShader: ShaderChunk.sprite_vert,
  8246. fragmentShader: ShaderChunk.sprite_frag
  8247. },
  8248. background: {
  8249. uniforms: {
  8250. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8251. t2D: { value: null },
  8252. backgroundIntensity: { value: 1 }
  8253. },
  8254. vertexShader: ShaderChunk.background_vert,
  8255. fragmentShader: ShaderChunk.background_frag
  8256. },
  8257. backgroundCube: {
  8258. uniforms: {
  8259. envMap: { value: null },
  8260. flipEnvMap: { value: - 1 },
  8261. backgroundBlurriness: { value: 0 },
  8262. backgroundIntensity: { value: 1 }
  8263. },
  8264. vertexShader: ShaderChunk.backgroundCube_vert,
  8265. fragmentShader: ShaderChunk.backgroundCube_frag
  8266. },
  8267. cube: {
  8268. uniforms: {
  8269. tCube: { value: null },
  8270. tFlip: { value: - 1 },
  8271. opacity: { value: 1.0 }
  8272. },
  8273. vertexShader: ShaderChunk.cube_vert,
  8274. fragmentShader: ShaderChunk.cube_frag
  8275. },
  8276. equirect: {
  8277. uniforms: {
  8278. tEquirect: { value: null },
  8279. },
  8280. vertexShader: ShaderChunk.equirect_vert,
  8281. fragmentShader: ShaderChunk.equirect_frag
  8282. },
  8283. distanceRGBA: {
  8284. uniforms: /*@__PURE__*/ mergeUniforms( [
  8285. UniformsLib.common,
  8286. UniformsLib.displacementmap,
  8287. {
  8288. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8289. nearDistance: { value: 1 },
  8290. farDistance: { value: 1000 }
  8291. }
  8292. ] ),
  8293. vertexShader: ShaderChunk.distanceRGBA_vert,
  8294. fragmentShader: ShaderChunk.distanceRGBA_frag
  8295. },
  8296. shadow: {
  8297. uniforms: /*@__PURE__*/ mergeUniforms( [
  8298. UniformsLib.lights,
  8299. UniformsLib.fog,
  8300. {
  8301. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8302. opacity: { value: 1.0 }
  8303. },
  8304. ] ),
  8305. vertexShader: ShaderChunk.shadow_vert,
  8306. fragmentShader: ShaderChunk.shadow_frag
  8307. }
  8308. };
  8309. ShaderLib.physical = {
  8310. uniforms: /*@__PURE__*/ mergeUniforms( [
  8311. ShaderLib.standard.uniforms,
  8312. {
  8313. clearcoat: { value: 0 },
  8314. clearcoatMap: { value: null },
  8315. clearcoatRoughness: { value: 0 },
  8316. clearcoatRoughnessMap: { value: null },
  8317. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8318. clearcoatNormalMap: { value: null },
  8319. iridescence: { value: 0 },
  8320. iridescenceMap: { value: null },
  8321. iridescenceIOR: { value: 1.3 },
  8322. iridescenceThicknessMinimum: { value: 100 },
  8323. iridescenceThicknessMaximum: { value: 400 },
  8324. iridescenceThicknessMap: { value: null },
  8325. sheen: { value: 0 },
  8326. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8327. sheenColorMap: { value: null },
  8328. sheenRoughness: { value: 1 },
  8329. sheenRoughnessMap: { value: null },
  8330. transmission: { value: 0 },
  8331. transmissionMap: { value: null },
  8332. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8333. transmissionSamplerMap: { value: null },
  8334. thickness: { value: 0 },
  8335. thicknessMap: { value: null },
  8336. attenuationDistance: { value: 0 },
  8337. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8338. specularIntensity: { value: 1 },
  8339. specularIntensityMap: { value: null },
  8340. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8341. specularColorMap: { value: null },
  8342. }
  8343. ] ),
  8344. vertexShader: ShaderChunk.meshphysical_vert,
  8345. fragmentShader: ShaderChunk.meshphysical_frag
  8346. };
  8347. const _rgb = { r: 0, b: 0, g: 0 };
  8348. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8349. const clearColor = new Color( 0x000000 );
  8350. let clearAlpha = alpha === true ? 0 : 1;
  8351. let planeMesh;
  8352. let boxMesh;
  8353. let currentBackground = null;
  8354. let currentBackgroundVersion = 0;
  8355. let currentTonemapping = null;
  8356. function render( renderList, scene ) {
  8357. let forceClear = false;
  8358. let background = scene.isScene === true ? scene.background : null;
  8359. if ( background && background.isTexture ) {
  8360. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8361. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8362. }
  8363. // Ignore background in AR
  8364. // TODO: Reconsider this.
  8365. const xr = renderer.xr;
  8366. const session = xr.getSession && xr.getSession();
  8367. if ( session && session.environmentBlendMode === 'additive' ) {
  8368. background = null;
  8369. }
  8370. if ( background === null ) {
  8371. setClear( clearColor, clearAlpha );
  8372. } else if ( background && background.isColor ) {
  8373. setClear( background, 1 );
  8374. forceClear = true;
  8375. }
  8376. if ( renderer.autoClear || forceClear ) {
  8377. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8378. }
  8379. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8380. if ( boxMesh === undefined ) {
  8381. boxMesh = new Mesh(
  8382. new BoxGeometry( 1, 1, 1 ),
  8383. new ShaderMaterial( {
  8384. name: 'BackgroundCubeMaterial',
  8385. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8386. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8387. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8388. side: BackSide,
  8389. depthTest: false,
  8390. depthWrite: false,
  8391. fog: false
  8392. } )
  8393. );
  8394. boxMesh.geometry.deleteAttribute( 'normal' );
  8395. boxMesh.geometry.deleteAttribute( 'uv' );
  8396. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8397. this.matrixWorld.copyPosition( camera.matrixWorld );
  8398. };
  8399. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8400. Object.defineProperty( boxMesh.material, 'envMap', {
  8401. get: function () {
  8402. return this.uniforms.envMap.value;
  8403. }
  8404. } );
  8405. objects.update( boxMesh );
  8406. }
  8407. boxMesh.material.uniforms.envMap.value = background;
  8408. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8409. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8410. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8411. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8412. if ( currentBackground !== background ||
  8413. currentBackgroundVersion !== background.version ||
  8414. currentTonemapping !== renderer.toneMapping ) {
  8415. boxMesh.material.needsUpdate = true;
  8416. currentBackground = background;
  8417. currentBackgroundVersion = background.version;
  8418. currentTonemapping = renderer.toneMapping;
  8419. }
  8420. boxMesh.layers.enableAll();
  8421. // push to the pre-sorted opaque render list
  8422. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8423. } else if ( background && background.isTexture ) {
  8424. if ( planeMesh === undefined ) {
  8425. planeMesh = new Mesh(
  8426. new PlaneGeometry( 2, 2 ),
  8427. new ShaderMaterial( {
  8428. name: 'BackgroundMaterial',
  8429. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8430. vertexShader: ShaderLib.background.vertexShader,
  8431. fragmentShader: ShaderLib.background.fragmentShader,
  8432. side: FrontSide,
  8433. depthTest: false,
  8434. depthWrite: false,
  8435. fog: false
  8436. } )
  8437. );
  8438. planeMesh.geometry.deleteAttribute( 'normal' );
  8439. // add "map" material property so the renderer can evaluate it like for built-in materials
  8440. Object.defineProperty( planeMesh.material, 'map', {
  8441. get: function () {
  8442. return this.uniforms.t2D.value;
  8443. }
  8444. } );
  8445. objects.update( planeMesh );
  8446. }
  8447. planeMesh.material.uniforms.t2D.value = background;
  8448. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8449. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8450. if ( background.matrixAutoUpdate === true ) {
  8451. background.updateMatrix();
  8452. }
  8453. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8454. if ( currentBackground !== background ||
  8455. currentBackgroundVersion !== background.version ||
  8456. currentTonemapping !== renderer.toneMapping ) {
  8457. planeMesh.material.needsUpdate = true;
  8458. currentBackground = background;
  8459. currentBackgroundVersion = background.version;
  8460. currentTonemapping = renderer.toneMapping;
  8461. }
  8462. planeMesh.layers.enableAll();
  8463. // push to the pre-sorted opaque render list
  8464. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8465. }
  8466. }
  8467. function setClear( color, alpha ) {
  8468. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8469. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8470. }
  8471. return {
  8472. getClearColor: function () {
  8473. return clearColor;
  8474. },
  8475. setClearColor: function ( color, alpha = 1 ) {
  8476. clearColor.set( color );
  8477. clearAlpha = alpha;
  8478. setClear( clearColor, clearAlpha );
  8479. },
  8480. getClearAlpha: function () {
  8481. return clearAlpha;
  8482. },
  8483. setClearAlpha: function ( alpha ) {
  8484. clearAlpha = alpha;
  8485. setClear( clearColor, clearAlpha );
  8486. },
  8487. render: render
  8488. };
  8489. }
  8490. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8491. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8492. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8493. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8494. const bindingStates = {};
  8495. const defaultState = createBindingState( null );
  8496. let currentState = defaultState;
  8497. let forceUpdate = false;
  8498. function setup( object, material, program, geometry, index ) {
  8499. let updateBuffers = false;
  8500. if ( vaoAvailable ) {
  8501. const state = getBindingState( geometry, program, material );
  8502. if ( currentState !== state ) {
  8503. currentState = state;
  8504. bindVertexArrayObject( currentState.object );
  8505. }
  8506. updateBuffers = needsUpdate( object, geometry, program, index );
  8507. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8508. } else {
  8509. const wireframe = ( material.wireframe === true );
  8510. if ( currentState.geometry !== geometry.id ||
  8511. currentState.program !== program.id ||
  8512. currentState.wireframe !== wireframe ) {
  8513. currentState.geometry = geometry.id;
  8514. currentState.program = program.id;
  8515. currentState.wireframe = wireframe;
  8516. updateBuffers = true;
  8517. }
  8518. }
  8519. if ( index !== null ) {
  8520. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8521. }
  8522. if ( updateBuffers || forceUpdate ) {
  8523. forceUpdate = false;
  8524. setupVertexAttributes( object, material, program, geometry );
  8525. if ( index !== null ) {
  8526. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8527. }
  8528. }
  8529. }
  8530. function createVertexArrayObject() {
  8531. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8532. return extension.createVertexArrayOES();
  8533. }
  8534. function bindVertexArrayObject( vao ) {
  8535. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8536. return extension.bindVertexArrayOES( vao );
  8537. }
  8538. function deleteVertexArrayObject( vao ) {
  8539. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8540. return extension.deleteVertexArrayOES( vao );
  8541. }
  8542. function getBindingState( geometry, program, material ) {
  8543. const wireframe = ( material.wireframe === true );
  8544. let programMap = bindingStates[ geometry.id ];
  8545. if ( programMap === undefined ) {
  8546. programMap = {};
  8547. bindingStates[ geometry.id ] = programMap;
  8548. }
  8549. let stateMap = programMap[ program.id ];
  8550. if ( stateMap === undefined ) {
  8551. stateMap = {};
  8552. programMap[ program.id ] = stateMap;
  8553. }
  8554. let state = stateMap[ wireframe ];
  8555. if ( state === undefined ) {
  8556. state = createBindingState( createVertexArrayObject() );
  8557. stateMap[ wireframe ] = state;
  8558. }
  8559. return state;
  8560. }
  8561. function createBindingState( vao ) {
  8562. const newAttributes = [];
  8563. const enabledAttributes = [];
  8564. const attributeDivisors = [];
  8565. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8566. newAttributes[ i ] = 0;
  8567. enabledAttributes[ i ] = 0;
  8568. attributeDivisors[ i ] = 0;
  8569. }
  8570. return {
  8571. // for backward compatibility on non-VAO support browser
  8572. geometry: null,
  8573. program: null,
  8574. wireframe: false,
  8575. newAttributes: newAttributes,
  8576. enabledAttributes: enabledAttributes,
  8577. attributeDivisors: attributeDivisors,
  8578. object: vao,
  8579. attributes: {},
  8580. index: null
  8581. };
  8582. }
  8583. function needsUpdate( object, geometry, program, index ) {
  8584. const cachedAttributes = currentState.attributes;
  8585. const geometryAttributes = geometry.attributes;
  8586. let attributesNum = 0;
  8587. const programAttributes = program.getAttributes();
  8588. for ( const name in programAttributes ) {
  8589. const programAttribute = programAttributes[ name ];
  8590. if ( programAttribute.location >= 0 ) {
  8591. const cachedAttribute = cachedAttributes[ name ];
  8592. let geometryAttribute = geometryAttributes[ name ];
  8593. if ( geometryAttribute === undefined ) {
  8594. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8595. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8596. }
  8597. if ( cachedAttribute === undefined ) return true;
  8598. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8599. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8600. attributesNum ++;
  8601. }
  8602. }
  8603. if ( currentState.attributesNum !== attributesNum ) return true;
  8604. if ( currentState.index !== index ) return true;
  8605. return false;
  8606. }
  8607. function saveCache( object, geometry, program, index ) {
  8608. const cache = {};
  8609. const attributes = geometry.attributes;
  8610. let attributesNum = 0;
  8611. const programAttributes = program.getAttributes();
  8612. for ( const name in programAttributes ) {
  8613. const programAttribute = programAttributes[ name ];
  8614. if ( programAttribute.location >= 0 ) {
  8615. let attribute = attributes[ name ];
  8616. if ( attribute === undefined ) {
  8617. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8618. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8619. }
  8620. const data = {};
  8621. data.attribute = attribute;
  8622. if ( attribute && attribute.data ) {
  8623. data.data = attribute.data;
  8624. }
  8625. cache[ name ] = data;
  8626. attributesNum ++;
  8627. }
  8628. }
  8629. currentState.attributes = cache;
  8630. currentState.attributesNum = attributesNum;
  8631. currentState.index = index;
  8632. }
  8633. function initAttributes() {
  8634. const newAttributes = currentState.newAttributes;
  8635. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8636. newAttributes[ i ] = 0;
  8637. }
  8638. }
  8639. function enableAttribute( attribute ) {
  8640. enableAttributeAndDivisor( attribute, 0 );
  8641. }
  8642. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8643. const newAttributes = currentState.newAttributes;
  8644. const enabledAttributes = currentState.enabledAttributes;
  8645. const attributeDivisors = currentState.attributeDivisors;
  8646. newAttributes[ attribute ] = 1;
  8647. if ( enabledAttributes[ attribute ] === 0 ) {
  8648. gl.enableVertexAttribArray( attribute );
  8649. enabledAttributes[ attribute ] = 1;
  8650. }
  8651. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8652. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8653. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8654. attributeDivisors[ attribute ] = meshPerAttribute;
  8655. }
  8656. }
  8657. function disableUnusedAttributes() {
  8658. const newAttributes = currentState.newAttributes;
  8659. const enabledAttributes = currentState.enabledAttributes;
  8660. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8661. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8662. gl.disableVertexAttribArray( i );
  8663. enabledAttributes[ i ] = 0;
  8664. }
  8665. }
  8666. }
  8667. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8668. if ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT ) ) {
  8669. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8670. } else {
  8671. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8672. }
  8673. }
  8674. function setupVertexAttributes( object, material, program, geometry ) {
  8675. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8676. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8677. }
  8678. initAttributes();
  8679. const geometryAttributes = geometry.attributes;
  8680. const programAttributes = program.getAttributes();
  8681. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8682. for ( const name in programAttributes ) {
  8683. const programAttribute = programAttributes[ name ];
  8684. if ( programAttribute.location >= 0 ) {
  8685. let geometryAttribute = geometryAttributes[ name ];
  8686. if ( geometryAttribute === undefined ) {
  8687. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8688. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8689. }
  8690. if ( geometryAttribute !== undefined ) {
  8691. const normalized = geometryAttribute.normalized;
  8692. const size = geometryAttribute.itemSize;
  8693. const attribute = attributes.get( geometryAttribute );
  8694. // TODO Attribute may not be available on context restore
  8695. if ( attribute === undefined ) continue;
  8696. const buffer = attribute.buffer;
  8697. const type = attribute.type;
  8698. const bytesPerElement = attribute.bytesPerElement;
  8699. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8700. const data = geometryAttribute.data;
  8701. const stride = data.stride;
  8702. const offset = geometryAttribute.offset;
  8703. if ( data.isInstancedInterleavedBuffer ) {
  8704. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8705. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8706. }
  8707. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8708. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8709. }
  8710. } else {
  8711. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8712. enableAttribute( programAttribute.location + i );
  8713. }
  8714. }
  8715. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8716. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8717. vertexAttribPointer(
  8718. programAttribute.location + i,
  8719. size / programAttribute.locationSize,
  8720. type,
  8721. normalized,
  8722. stride * bytesPerElement,
  8723. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8724. );
  8725. }
  8726. } else {
  8727. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8728. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8729. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8730. }
  8731. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8732. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8733. }
  8734. } else {
  8735. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8736. enableAttribute( programAttribute.location + i );
  8737. }
  8738. }
  8739. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  8740. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8741. vertexAttribPointer(
  8742. programAttribute.location + i,
  8743. size / programAttribute.locationSize,
  8744. type,
  8745. normalized,
  8746. size * bytesPerElement,
  8747. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8748. );
  8749. }
  8750. }
  8751. } else if ( materialDefaultAttributeValues !== undefined ) {
  8752. const value = materialDefaultAttributeValues[ name ];
  8753. if ( value !== undefined ) {
  8754. switch ( value.length ) {
  8755. case 2:
  8756. gl.vertexAttrib2fv( programAttribute.location, value );
  8757. break;
  8758. case 3:
  8759. gl.vertexAttrib3fv( programAttribute.location, value );
  8760. break;
  8761. case 4:
  8762. gl.vertexAttrib4fv( programAttribute.location, value );
  8763. break;
  8764. default:
  8765. gl.vertexAttrib1fv( programAttribute.location, value );
  8766. }
  8767. }
  8768. }
  8769. }
  8770. }
  8771. disableUnusedAttributes();
  8772. }
  8773. function dispose() {
  8774. reset();
  8775. for ( const geometryId in bindingStates ) {
  8776. const programMap = bindingStates[ geometryId ];
  8777. for ( const programId in programMap ) {
  8778. const stateMap = programMap[ programId ];
  8779. for ( const wireframe in stateMap ) {
  8780. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8781. delete stateMap[ wireframe ];
  8782. }
  8783. delete programMap[ programId ];
  8784. }
  8785. delete bindingStates[ geometryId ];
  8786. }
  8787. }
  8788. function releaseStatesOfGeometry( geometry ) {
  8789. if ( bindingStates[ geometry.id ] === undefined ) return;
  8790. const programMap = bindingStates[ geometry.id ];
  8791. for ( const programId in programMap ) {
  8792. const stateMap = programMap[ programId ];
  8793. for ( const wireframe in stateMap ) {
  8794. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8795. delete stateMap[ wireframe ];
  8796. }
  8797. delete programMap[ programId ];
  8798. }
  8799. delete bindingStates[ geometry.id ];
  8800. }
  8801. function releaseStatesOfProgram( program ) {
  8802. for ( const geometryId in bindingStates ) {
  8803. const programMap = bindingStates[ geometryId ];
  8804. if ( programMap[ program.id ] === undefined ) continue;
  8805. const stateMap = programMap[ program.id ];
  8806. for ( const wireframe in stateMap ) {
  8807. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8808. delete stateMap[ wireframe ];
  8809. }
  8810. delete programMap[ program.id ];
  8811. }
  8812. }
  8813. function reset() {
  8814. resetDefaultState();
  8815. forceUpdate = true;
  8816. if ( currentState === defaultState ) return;
  8817. currentState = defaultState;
  8818. bindVertexArrayObject( currentState.object );
  8819. }
  8820. // for backward-compatibility
  8821. function resetDefaultState() {
  8822. defaultState.geometry = null;
  8823. defaultState.program = null;
  8824. defaultState.wireframe = false;
  8825. }
  8826. return {
  8827. setup: setup,
  8828. reset: reset,
  8829. resetDefaultState: resetDefaultState,
  8830. dispose: dispose,
  8831. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8832. releaseStatesOfProgram: releaseStatesOfProgram,
  8833. initAttributes: initAttributes,
  8834. enableAttribute: enableAttribute,
  8835. disableUnusedAttributes: disableUnusedAttributes
  8836. };
  8837. }
  8838. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8839. const isWebGL2 = capabilities.isWebGL2;
  8840. let mode;
  8841. function setMode( value ) {
  8842. mode = value;
  8843. }
  8844. function render( start, count ) {
  8845. gl.drawArrays( mode, start, count );
  8846. info.update( count, mode, 1 );
  8847. }
  8848. function renderInstances( start, count, primcount ) {
  8849. if ( primcount === 0 ) return;
  8850. let extension, methodName;
  8851. if ( isWebGL2 ) {
  8852. extension = gl;
  8853. methodName = 'drawArraysInstanced';
  8854. } else {
  8855. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8856. methodName = 'drawArraysInstancedANGLE';
  8857. if ( extension === null ) {
  8858. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8859. return;
  8860. }
  8861. }
  8862. extension[ methodName ]( mode, start, count, primcount );
  8863. info.update( count, mode, primcount );
  8864. }
  8865. //
  8866. this.setMode = setMode;
  8867. this.render = render;
  8868. this.renderInstances = renderInstances;
  8869. }
  8870. function WebGLCapabilities( gl, extensions, parameters ) {
  8871. let maxAnisotropy;
  8872. function getMaxAnisotropy() {
  8873. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8874. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8875. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8876. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8877. } else {
  8878. maxAnisotropy = 0;
  8879. }
  8880. return maxAnisotropy;
  8881. }
  8882. function getMaxPrecision( precision ) {
  8883. if ( precision === 'highp' ) {
  8884. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  8885. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  8886. return 'highp';
  8887. }
  8888. precision = 'mediump';
  8889. }
  8890. if ( precision === 'mediump' ) {
  8891. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  8892. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  8893. return 'mediump';
  8894. }
  8895. }
  8896. return 'lowp';
  8897. }
  8898. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  8899. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8900. const maxPrecision = getMaxPrecision( precision );
  8901. if ( maxPrecision !== precision ) {
  8902. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8903. precision = maxPrecision;
  8904. }
  8905. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8906. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8907. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  8908. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  8909. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  8910. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  8911. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8912. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  8913. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  8914. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  8915. const vertexTextures = maxVertexTextures > 0;
  8916. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8917. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8918. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  8919. return {
  8920. isWebGL2: isWebGL2,
  8921. drawBuffers: drawBuffers,
  8922. getMaxAnisotropy: getMaxAnisotropy,
  8923. getMaxPrecision: getMaxPrecision,
  8924. precision: precision,
  8925. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8926. maxTextures: maxTextures,
  8927. maxVertexTextures: maxVertexTextures,
  8928. maxTextureSize: maxTextureSize,
  8929. maxCubemapSize: maxCubemapSize,
  8930. maxAttributes: maxAttributes,
  8931. maxVertexUniforms: maxVertexUniforms,
  8932. maxVaryings: maxVaryings,
  8933. maxFragmentUniforms: maxFragmentUniforms,
  8934. vertexTextures: vertexTextures,
  8935. floatFragmentTextures: floatFragmentTextures,
  8936. floatVertexTextures: floatVertexTextures,
  8937. maxSamples: maxSamples
  8938. };
  8939. }
  8940. function WebGLClipping( properties ) {
  8941. const scope = this;
  8942. let globalState = null,
  8943. numGlobalPlanes = 0,
  8944. localClippingEnabled = false,
  8945. renderingShadows = false;
  8946. const plane = new Plane(),
  8947. viewNormalMatrix = new Matrix3(),
  8948. uniform = { value: null, needsUpdate: false };
  8949. this.uniform = uniform;
  8950. this.numPlanes = 0;
  8951. this.numIntersection = 0;
  8952. this.init = function ( planes, enableLocalClipping ) {
  8953. const enabled =
  8954. planes.length !== 0 ||
  8955. enableLocalClipping ||
  8956. // enable state of previous frame - the clipping code has to
  8957. // run another frame in order to reset the state:
  8958. numGlobalPlanes !== 0 ||
  8959. localClippingEnabled;
  8960. localClippingEnabled = enableLocalClipping;
  8961. numGlobalPlanes = planes.length;
  8962. return enabled;
  8963. };
  8964. this.beginShadows = function () {
  8965. renderingShadows = true;
  8966. projectPlanes( null );
  8967. };
  8968. this.endShadows = function () {
  8969. renderingShadows = false;
  8970. };
  8971. this.setGlobalState = function ( planes, camera ) {
  8972. globalState = projectPlanes( planes, camera, 0 );
  8973. };
  8974. this.setState = function ( material, camera, useCache ) {
  8975. const planes = material.clippingPlanes,
  8976. clipIntersection = material.clipIntersection,
  8977. clipShadows = material.clipShadows;
  8978. const materialProperties = properties.get( material );
  8979. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8980. // there's no local clipping
  8981. if ( renderingShadows ) {
  8982. // there's no global clipping
  8983. projectPlanes( null );
  8984. } else {
  8985. resetGlobalState();
  8986. }
  8987. } else {
  8988. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8989. lGlobal = nGlobal * 4;
  8990. let dstArray = materialProperties.clippingState || null;
  8991. uniform.value = dstArray; // ensure unique state
  8992. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8993. for ( let i = 0; i !== lGlobal; ++ i ) {
  8994. dstArray[ i ] = globalState[ i ];
  8995. }
  8996. materialProperties.clippingState = dstArray;
  8997. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8998. this.numPlanes += nGlobal;
  8999. }
  9000. };
  9001. function resetGlobalState() {
  9002. if ( uniform.value !== globalState ) {
  9003. uniform.value = globalState;
  9004. uniform.needsUpdate = numGlobalPlanes > 0;
  9005. }
  9006. scope.numPlanes = numGlobalPlanes;
  9007. scope.numIntersection = 0;
  9008. }
  9009. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9010. const nPlanes = planes !== null ? planes.length : 0;
  9011. let dstArray = null;
  9012. if ( nPlanes !== 0 ) {
  9013. dstArray = uniform.value;
  9014. if ( skipTransform !== true || dstArray === null ) {
  9015. const flatSize = dstOffset + nPlanes * 4,
  9016. viewMatrix = camera.matrixWorldInverse;
  9017. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9018. if ( dstArray === null || dstArray.length < flatSize ) {
  9019. dstArray = new Float32Array( flatSize );
  9020. }
  9021. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9022. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9023. plane.normal.toArray( dstArray, i4 );
  9024. dstArray[ i4 + 3 ] = plane.constant;
  9025. }
  9026. }
  9027. uniform.value = dstArray;
  9028. uniform.needsUpdate = true;
  9029. }
  9030. scope.numPlanes = nPlanes;
  9031. scope.numIntersection = 0;
  9032. return dstArray;
  9033. }
  9034. }
  9035. function WebGLCubeMaps( renderer ) {
  9036. let cubemaps = new WeakMap();
  9037. function mapTextureMapping( texture, mapping ) {
  9038. if ( mapping === EquirectangularReflectionMapping ) {
  9039. texture.mapping = CubeReflectionMapping;
  9040. } else if ( mapping === EquirectangularRefractionMapping ) {
  9041. texture.mapping = CubeRefractionMapping;
  9042. }
  9043. return texture;
  9044. }
  9045. function get( texture ) {
  9046. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9047. const mapping = texture.mapping;
  9048. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9049. if ( cubemaps.has( texture ) ) {
  9050. const cubemap = cubemaps.get( texture ).texture;
  9051. return mapTextureMapping( cubemap, texture.mapping );
  9052. } else {
  9053. const image = texture.image;
  9054. if ( image && image.height > 0 ) {
  9055. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9056. renderTarget.fromEquirectangularTexture( renderer, texture );
  9057. cubemaps.set( texture, renderTarget );
  9058. texture.addEventListener( 'dispose', onTextureDispose );
  9059. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9060. } else {
  9061. // image not yet ready. try the conversion next frame
  9062. return null;
  9063. }
  9064. }
  9065. }
  9066. }
  9067. return texture;
  9068. }
  9069. function onTextureDispose( event ) {
  9070. const texture = event.target;
  9071. texture.removeEventListener( 'dispose', onTextureDispose );
  9072. const cubemap = cubemaps.get( texture );
  9073. if ( cubemap !== undefined ) {
  9074. cubemaps.delete( texture );
  9075. cubemap.dispose();
  9076. }
  9077. }
  9078. function dispose() {
  9079. cubemaps = new WeakMap();
  9080. }
  9081. return {
  9082. get: get,
  9083. dispose: dispose
  9084. };
  9085. }
  9086. class OrthographicCamera extends Camera {
  9087. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9088. super();
  9089. this.isOrthographicCamera = true;
  9090. this.type = 'OrthographicCamera';
  9091. this.zoom = 1;
  9092. this.view = null;
  9093. this.left = left;
  9094. this.right = right;
  9095. this.top = top;
  9096. this.bottom = bottom;
  9097. this.near = near;
  9098. this.far = far;
  9099. this.updateProjectionMatrix();
  9100. }
  9101. copy( source, recursive ) {
  9102. super.copy( source, recursive );
  9103. this.left = source.left;
  9104. this.right = source.right;
  9105. this.top = source.top;
  9106. this.bottom = source.bottom;
  9107. this.near = source.near;
  9108. this.far = source.far;
  9109. this.zoom = source.zoom;
  9110. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9111. return this;
  9112. }
  9113. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9114. if ( this.view === null ) {
  9115. this.view = {
  9116. enabled: true,
  9117. fullWidth: 1,
  9118. fullHeight: 1,
  9119. offsetX: 0,
  9120. offsetY: 0,
  9121. width: 1,
  9122. height: 1
  9123. };
  9124. }
  9125. this.view.enabled = true;
  9126. this.view.fullWidth = fullWidth;
  9127. this.view.fullHeight = fullHeight;
  9128. this.view.offsetX = x;
  9129. this.view.offsetY = y;
  9130. this.view.width = width;
  9131. this.view.height = height;
  9132. this.updateProjectionMatrix();
  9133. }
  9134. clearViewOffset() {
  9135. if ( this.view !== null ) {
  9136. this.view.enabled = false;
  9137. }
  9138. this.updateProjectionMatrix();
  9139. }
  9140. updateProjectionMatrix() {
  9141. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9142. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9143. const cx = ( this.right + this.left ) / 2;
  9144. const cy = ( this.top + this.bottom ) / 2;
  9145. let left = cx - dx;
  9146. let right = cx + dx;
  9147. let top = cy + dy;
  9148. let bottom = cy - dy;
  9149. if ( this.view !== null && this.view.enabled ) {
  9150. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9151. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9152. left += scaleW * this.view.offsetX;
  9153. right = left + scaleW * this.view.width;
  9154. top -= scaleH * this.view.offsetY;
  9155. bottom = top - scaleH * this.view.height;
  9156. }
  9157. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9158. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9159. }
  9160. toJSON( meta ) {
  9161. const data = super.toJSON( meta );
  9162. data.object.zoom = this.zoom;
  9163. data.object.left = this.left;
  9164. data.object.right = this.right;
  9165. data.object.top = this.top;
  9166. data.object.bottom = this.bottom;
  9167. data.object.near = this.near;
  9168. data.object.far = this.far;
  9169. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9170. return data;
  9171. }
  9172. }
  9173. const LOD_MIN = 4;
  9174. // The standard deviations (radians) associated with the extra mips. These are
  9175. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9176. // geometric shadowing function. These sigma values squared must match the
  9177. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9178. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9179. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9180. // samples and exit early, but not recompile the shader.
  9181. const MAX_SAMPLES = 20;
  9182. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9183. const _clearColor = /*@__PURE__*/ new Color();
  9184. let _oldTarget = null;
  9185. // Golden Ratio
  9186. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9187. const INV_PHI = 1 / PHI;
  9188. // Vertices of a dodecahedron (except the opposites, which represent the
  9189. // same axis), used as axis directions evenly spread on a sphere.
  9190. const _axisDirections = [
  9191. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9192. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9193. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9194. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9195. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9196. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9197. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9198. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9199. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9200. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9201. /**
  9202. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9203. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9204. * blur to be quickly accessed based on material roughness. It is packed into a
  9205. * special CubeUV format that allows us to perform custom interpolation so that
  9206. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9207. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9208. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9209. * higher roughness levels. In this way we maintain resolution to smoothly
  9210. * interpolate diffuse lighting while limiting sampling computation.
  9211. *
  9212. * Paper: Fast, Accurate Image-Based Lighting
  9213. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9214. */
  9215. class PMREMGenerator {
  9216. constructor( renderer ) {
  9217. this._renderer = renderer;
  9218. this._pingPongRenderTarget = null;
  9219. this._lodMax = 0;
  9220. this._cubeSize = 0;
  9221. this._lodPlanes = [];
  9222. this._sizeLods = [];
  9223. this._sigmas = [];
  9224. this._blurMaterial = null;
  9225. this._cubemapMaterial = null;
  9226. this._equirectMaterial = null;
  9227. this._compileMaterial( this._blurMaterial );
  9228. }
  9229. /**
  9230. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9231. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9232. * in radians to be applied to the scene before PMREM generation. Optional near
  9233. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9234. * is placed at the origin).
  9235. */
  9236. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9237. _oldTarget = this._renderer.getRenderTarget();
  9238. this._setSize( 256 );
  9239. const cubeUVRenderTarget = this._allocateTargets();
  9240. cubeUVRenderTarget.depthBuffer = true;
  9241. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9242. if ( sigma > 0 ) {
  9243. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9244. }
  9245. this._applyPMREM( cubeUVRenderTarget );
  9246. this._cleanup( cubeUVRenderTarget );
  9247. return cubeUVRenderTarget;
  9248. }
  9249. /**
  9250. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9251. * or HDR. The ideal input image size is 1k (1024 x 512),
  9252. * as this matches best with the 256 x 256 cubemap output.
  9253. */
  9254. fromEquirectangular( equirectangular, renderTarget = null ) {
  9255. return this._fromTexture( equirectangular, renderTarget );
  9256. }
  9257. /**
  9258. * Generates a PMREM from an cubemap texture, which can be either LDR
  9259. * or HDR. The ideal input cube size is 256 x 256,
  9260. * as this matches best with the 256 x 256 cubemap output.
  9261. */
  9262. fromCubemap( cubemap, renderTarget = null ) {
  9263. return this._fromTexture( cubemap, renderTarget );
  9264. }
  9265. /**
  9266. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9267. * your texture's network fetch for increased concurrency.
  9268. */
  9269. compileCubemapShader() {
  9270. if ( this._cubemapMaterial === null ) {
  9271. this._cubemapMaterial = _getCubemapMaterial();
  9272. this._compileMaterial( this._cubemapMaterial );
  9273. }
  9274. }
  9275. /**
  9276. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9277. * your texture's network fetch for increased concurrency.
  9278. */
  9279. compileEquirectangularShader() {
  9280. if ( this._equirectMaterial === null ) {
  9281. this._equirectMaterial = _getEquirectMaterial();
  9282. this._compileMaterial( this._equirectMaterial );
  9283. }
  9284. }
  9285. /**
  9286. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9287. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9288. * one of them will cause any others to also become unusable.
  9289. */
  9290. dispose() {
  9291. this._dispose();
  9292. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9293. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9294. }
  9295. // private interface
  9296. _setSize( cubeSize ) {
  9297. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9298. this._cubeSize = Math.pow( 2, this._lodMax );
  9299. }
  9300. _dispose() {
  9301. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9302. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9303. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9304. this._lodPlanes[ i ].dispose();
  9305. }
  9306. }
  9307. _cleanup( outputTarget ) {
  9308. this._renderer.setRenderTarget( _oldTarget );
  9309. outputTarget.scissorTest = false;
  9310. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9311. }
  9312. _fromTexture( texture, renderTarget ) {
  9313. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9314. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9315. } else { // Equirectangular
  9316. this._setSize( texture.image.width / 4 );
  9317. }
  9318. _oldTarget = this._renderer.getRenderTarget();
  9319. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9320. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9321. this._applyPMREM( cubeUVRenderTarget );
  9322. this._cleanup( cubeUVRenderTarget );
  9323. return cubeUVRenderTarget;
  9324. }
  9325. _allocateTargets() {
  9326. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9327. const height = 4 * this._cubeSize;
  9328. const params = {
  9329. magFilter: LinearFilter,
  9330. minFilter: LinearFilter,
  9331. generateMipmaps: false,
  9332. type: HalfFloatType,
  9333. format: RGBAFormat,
  9334. encoding: LinearEncoding,
  9335. depthBuffer: false
  9336. };
  9337. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9338. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9339. if ( this._pingPongRenderTarget !== null ) {
  9340. this._dispose();
  9341. }
  9342. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9343. const { _lodMax } = this;
  9344. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9345. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9346. }
  9347. return cubeUVRenderTarget;
  9348. }
  9349. _compileMaterial( material ) {
  9350. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9351. this._renderer.compile( tmpMesh, _flatCamera );
  9352. }
  9353. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9354. const fov = 90;
  9355. const aspect = 1;
  9356. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9357. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9358. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9359. const renderer = this._renderer;
  9360. const originalAutoClear = renderer.autoClear;
  9361. const toneMapping = renderer.toneMapping;
  9362. renderer.getClearColor( _clearColor );
  9363. renderer.toneMapping = NoToneMapping;
  9364. renderer.autoClear = false;
  9365. const backgroundMaterial = new MeshBasicMaterial( {
  9366. name: 'PMREM.Background',
  9367. side: BackSide,
  9368. depthWrite: false,
  9369. depthTest: false,
  9370. } );
  9371. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9372. let useSolidColor = false;
  9373. const background = scene.background;
  9374. if ( background ) {
  9375. if ( background.isColor ) {
  9376. backgroundMaterial.color.copy( background );
  9377. scene.background = null;
  9378. useSolidColor = true;
  9379. }
  9380. } else {
  9381. backgroundMaterial.color.copy( _clearColor );
  9382. useSolidColor = true;
  9383. }
  9384. for ( let i = 0; i < 6; i ++ ) {
  9385. const col = i % 3;
  9386. if ( col === 0 ) {
  9387. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9388. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9389. } else if ( col === 1 ) {
  9390. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9391. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9392. } else {
  9393. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9394. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9395. }
  9396. const size = this._cubeSize;
  9397. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9398. renderer.setRenderTarget( cubeUVRenderTarget );
  9399. if ( useSolidColor ) {
  9400. renderer.render( backgroundBox, cubeCamera );
  9401. }
  9402. renderer.render( scene, cubeCamera );
  9403. }
  9404. backgroundBox.geometry.dispose();
  9405. backgroundBox.material.dispose();
  9406. renderer.toneMapping = toneMapping;
  9407. renderer.autoClear = originalAutoClear;
  9408. scene.background = background;
  9409. }
  9410. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9411. const renderer = this._renderer;
  9412. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9413. if ( isCubeTexture ) {
  9414. if ( this._cubemapMaterial === null ) {
  9415. this._cubemapMaterial = _getCubemapMaterial();
  9416. }
  9417. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9418. } else {
  9419. if ( this._equirectMaterial === null ) {
  9420. this._equirectMaterial = _getEquirectMaterial();
  9421. }
  9422. }
  9423. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9424. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9425. const uniforms = material.uniforms;
  9426. uniforms[ 'envMap' ].value = texture;
  9427. const size = this._cubeSize;
  9428. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9429. renderer.setRenderTarget( cubeUVRenderTarget );
  9430. renderer.render( mesh, _flatCamera );
  9431. }
  9432. _applyPMREM( cubeUVRenderTarget ) {
  9433. const renderer = this._renderer;
  9434. const autoClear = renderer.autoClear;
  9435. renderer.autoClear = false;
  9436. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9437. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9438. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9439. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9440. }
  9441. renderer.autoClear = autoClear;
  9442. }
  9443. /**
  9444. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9445. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9446. * the blur latitudinally (around the poles), and then longitudinally (towards
  9447. * the poles) to approximate the orthogonally-separable blur. It is least
  9448. * accurate at the poles, but still does a decent job.
  9449. */
  9450. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9451. const pingPongRenderTarget = this._pingPongRenderTarget;
  9452. this._halfBlur(
  9453. cubeUVRenderTarget,
  9454. pingPongRenderTarget,
  9455. lodIn,
  9456. lodOut,
  9457. sigma,
  9458. 'latitudinal',
  9459. poleAxis );
  9460. this._halfBlur(
  9461. pingPongRenderTarget,
  9462. cubeUVRenderTarget,
  9463. lodOut,
  9464. lodOut,
  9465. sigma,
  9466. 'longitudinal',
  9467. poleAxis );
  9468. }
  9469. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9470. const renderer = this._renderer;
  9471. const blurMaterial = this._blurMaterial;
  9472. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9473. console.error(
  9474. 'blur direction must be either latitudinal or longitudinal!' );
  9475. }
  9476. // Number of standard deviations at which to cut off the discrete approximation.
  9477. const STANDARD_DEVIATIONS = 3;
  9478. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9479. const blurUniforms = blurMaterial.uniforms;
  9480. const pixels = this._sizeLods[ lodIn ] - 1;
  9481. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9482. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9483. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9484. if ( samples > MAX_SAMPLES ) {
  9485. console.warn( `sigmaRadians, ${
  9486. sigmaRadians}, is too large and will clip, as it requested ${
  9487. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9488. }
  9489. const weights = [];
  9490. let sum = 0;
  9491. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9492. const x = i / sigmaPixels;
  9493. const weight = Math.exp( - x * x / 2 );
  9494. weights.push( weight );
  9495. if ( i === 0 ) {
  9496. sum += weight;
  9497. } else if ( i < samples ) {
  9498. sum += 2 * weight;
  9499. }
  9500. }
  9501. for ( let i = 0; i < weights.length; i ++ ) {
  9502. weights[ i ] = weights[ i ] / sum;
  9503. }
  9504. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9505. blurUniforms[ 'samples' ].value = samples;
  9506. blurUniforms[ 'weights' ].value = weights;
  9507. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9508. if ( poleAxis ) {
  9509. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9510. }
  9511. const { _lodMax } = this;
  9512. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9513. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9514. const outputSize = this._sizeLods[ lodOut ];
  9515. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9516. const y = 4 * ( this._cubeSize - outputSize );
  9517. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9518. renderer.setRenderTarget( targetOut );
  9519. renderer.render( blurMesh, _flatCamera );
  9520. }
  9521. }
  9522. function _createPlanes( lodMax ) {
  9523. const lodPlanes = [];
  9524. const sizeLods = [];
  9525. const sigmas = [];
  9526. let lod = lodMax;
  9527. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9528. for ( let i = 0; i < totalLods; i ++ ) {
  9529. const sizeLod = Math.pow( 2, lod );
  9530. sizeLods.push( sizeLod );
  9531. let sigma = 1.0 / sizeLod;
  9532. if ( i > lodMax - LOD_MIN ) {
  9533. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9534. } else if ( i === 0 ) {
  9535. sigma = 0;
  9536. }
  9537. sigmas.push( sigma );
  9538. const texelSize = 1.0 / ( sizeLod - 2 );
  9539. const min = - texelSize;
  9540. const max = 1 + texelSize;
  9541. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9542. const cubeFaces = 6;
  9543. const vertices = 6;
  9544. const positionSize = 3;
  9545. const uvSize = 2;
  9546. const faceIndexSize = 1;
  9547. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9548. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9549. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9550. for ( let face = 0; face < cubeFaces; face ++ ) {
  9551. const x = ( face % 3 ) * 2 / 3 - 1;
  9552. const y = face > 2 ? 0 : - 1;
  9553. const coordinates = [
  9554. x, y, 0,
  9555. x + 2 / 3, y, 0,
  9556. x + 2 / 3, y + 1, 0,
  9557. x, y, 0,
  9558. x + 2 / 3, y + 1, 0,
  9559. x, y + 1, 0
  9560. ];
  9561. position.set( coordinates, positionSize * vertices * face );
  9562. uv.set( uv1, uvSize * vertices * face );
  9563. const fill = [ face, face, face, face, face, face ];
  9564. faceIndex.set( fill, faceIndexSize * vertices * face );
  9565. }
  9566. const planes = new BufferGeometry();
  9567. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9568. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9569. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9570. lodPlanes.push( planes );
  9571. if ( lod > LOD_MIN ) {
  9572. lod --;
  9573. }
  9574. }
  9575. return { lodPlanes, sizeLods, sigmas };
  9576. }
  9577. function _createRenderTarget( width, height, params ) {
  9578. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9579. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9580. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9581. cubeUVRenderTarget.scissorTest = true;
  9582. return cubeUVRenderTarget;
  9583. }
  9584. function _setViewport( target, x, y, width, height ) {
  9585. target.viewport.set( x, y, width, height );
  9586. target.scissor.set( x, y, width, height );
  9587. }
  9588. function _getBlurShader( lodMax, width, height ) {
  9589. const weights = new Float32Array( MAX_SAMPLES );
  9590. const poleAxis = new Vector3( 0, 1, 0 );
  9591. const shaderMaterial = new ShaderMaterial( {
  9592. name: 'SphericalGaussianBlur',
  9593. defines: {
  9594. 'n': MAX_SAMPLES,
  9595. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9596. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9597. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9598. },
  9599. uniforms: {
  9600. 'envMap': { value: null },
  9601. 'samples': { value: 1 },
  9602. 'weights': { value: weights },
  9603. 'latitudinal': { value: false },
  9604. 'dTheta': { value: 0 },
  9605. 'mipInt': { value: 0 },
  9606. 'poleAxis': { value: poleAxis }
  9607. },
  9608. vertexShader: _getCommonVertexShader(),
  9609. fragmentShader: /* glsl */`
  9610. precision mediump float;
  9611. precision mediump int;
  9612. varying vec3 vOutputDirection;
  9613. uniform sampler2D envMap;
  9614. uniform int samples;
  9615. uniform float weights[ n ];
  9616. uniform bool latitudinal;
  9617. uniform float dTheta;
  9618. uniform float mipInt;
  9619. uniform vec3 poleAxis;
  9620. #define ENVMAP_TYPE_CUBE_UV
  9621. #include <cube_uv_reflection_fragment>
  9622. vec3 getSample( float theta, vec3 axis ) {
  9623. float cosTheta = cos( theta );
  9624. // Rodrigues' axis-angle rotation
  9625. vec3 sampleDirection = vOutputDirection * cosTheta
  9626. + cross( axis, vOutputDirection ) * sin( theta )
  9627. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9628. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9629. }
  9630. void main() {
  9631. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9632. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9633. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9634. }
  9635. axis = normalize( axis );
  9636. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9637. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9638. for ( int i = 1; i < n; i++ ) {
  9639. if ( i >= samples ) {
  9640. break;
  9641. }
  9642. float theta = dTheta * float( i );
  9643. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9644. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9645. }
  9646. }
  9647. `,
  9648. blending: NoBlending,
  9649. depthTest: false,
  9650. depthWrite: false
  9651. } );
  9652. return shaderMaterial;
  9653. }
  9654. function _getEquirectMaterial() {
  9655. return new ShaderMaterial( {
  9656. name: 'EquirectangularToCubeUV',
  9657. uniforms: {
  9658. 'envMap': { value: null }
  9659. },
  9660. vertexShader: _getCommonVertexShader(),
  9661. fragmentShader: /* glsl */`
  9662. precision mediump float;
  9663. precision mediump int;
  9664. varying vec3 vOutputDirection;
  9665. uniform sampler2D envMap;
  9666. #include <common>
  9667. void main() {
  9668. vec3 outputDirection = normalize( vOutputDirection );
  9669. vec2 uv = equirectUv( outputDirection );
  9670. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9671. }
  9672. `,
  9673. blending: NoBlending,
  9674. depthTest: false,
  9675. depthWrite: false
  9676. } );
  9677. }
  9678. function _getCubemapMaterial() {
  9679. return new ShaderMaterial( {
  9680. name: 'CubemapToCubeUV',
  9681. uniforms: {
  9682. 'envMap': { value: null },
  9683. 'flipEnvMap': { value: - 1 }
  9684. },
  9685. vertexShader: _getCommonVertexShader(),
  9686. fragmentShader: /* glsl */`
  9687. precision mediump float;
  9688. precision mediump int;
  9689. uniform float flipEnvMap;
  9690. varying vec3 vOutputDirection;
  9691. uniform samplerCube envMap;
  9692. void main() {
  9693. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9694. }
  9695. `,
  9696. blending: NoBlending,
  9697. depthTest: false,
  9698. depthWrite: false
  9699. } );
  9700. }
  9701. function _getCommonVertexShader() {
  9702. return /* glsl */`
  9703. precision mediump float;
  9704. precision mediump int;
  9705. attribute float faceIndex;
  9706. varying vec3 vOutputDirection;
  9707. // RH coordinate system; PMREM face-indexing convention
  9708. vec3 getDirection( vec2 uv, float face ) {
  9709. uv = 2.0 * uv - 1.0;
  9710. vec3 direction = vec3( uv, 1.0 );
  9711. if ( face == 0.0 ) {
  9712. direction = direction.zyx; // ( 1, v, u ) pos x
  9713. } else if ( face == 1.0 ) {
  9714. direction = direction.xzy;
  9715. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9716. } else if ( face == 2.0 ) {
  9717. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9718. } else if ( face == 3.0 ) {
  9719. direction = direction.zyx;
  9720. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9721. } else if ( face == 4.0 ) {
  9722. direction = direction.xzy;
  9723. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9724. } else if ( face == 5.0 ) {
  9725. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9726. }
  9727. return direction;
  9728. }
  9729. void main() {
  9730. vOutputDirection = getDirection( uv, faceIndex );
  9731. gl_Position = vec4( position, 1.0 );
  9732. }
  9733. `;
  9734. }
  9735. function WebGLCubeUVMaps( renderer ) {
  9736. let cubeUVmaps = new WeakMap();
  9737. let pmremGenerator = null;
  9738. function get( texture ) {
  9739. if ( texture && texture.isTexture ) {
  9740. const mapping = texture.mapping;
  9741. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9742. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9743. // equirect/cube map to cubeUV conversion
  9744. if ( isEquirectMap || isCubeMap ) {
  9745. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9746. texture.needsPMREMUpdate = false;
  9747. let renderTarget = cubeUVmaps.get( texture );
  9748. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9749. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9750. cubeUVmaps.set( texture, renderTarget );
  9751. return renderTarget.texture;
  9752. } else {
  9753. if ( cubeUVmaps.has( texture ) ) {
  9754. return cubeUVmaps.get( texture ).texture;
  9755. } else {
  9756. const image = texture.image;
  9757. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9758. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9759. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9760. cubeUVmaps.set( texture, renderTarget );
  9761. texture.addEventListener( 'dispose', onTextureDispose );
  9762. return renderTarget.texture;
  9763. } else {
  9764. // image not yet ready. try the conversion next frame
  9765. return null;
  9766. }
  9767. }
  9768. }
  9769. }
  9770. }
  9771. return texture;
  9772. }
  9773. function isCubeTextureComplete( image ) {
  9774. let count = 0;
  9775. const length = 6;
  9776. for ( let i = 0; i < length; i ++ ) {
  9777. if ( image[ i ] !== undefined ) count ++;
  9778. }
  9779. return count === length;
  9780. }
  9781. function onTextureDispose( event ) {
  9782. const texture = event.target;
  9783. texture.removeEventListener( 'dispose', onTextureDispose );
  9784. const cubemapUV = cubeUVmaps.get( texture );
  9785. if ( cubemapUV !== undefined ) {
  9786. cubeUVmaps.delete( texture );
  9787. cubemapUV.dispose();
  9788. }
  9789. }
  9790. function dispose() {
  9791. cubeUVmaps = new WeakMap();
  9792. if ( pmremGenerator !== null ) {
  9793. pmremGenerator.dispose();
  9794. pmremGenerator = null;
  9795. }
  9796. }
  9797. return {
  9798. get: get,
  9799. dispose: dispose
  9800. };
  9801. }
  9802. function WebGLExtensions( gl ) {
  9803. const extensions = {};
  9804. function getExtension( name ) {
  9805. if ( extensions[ name ] !== undefined ) {
  9806. return extensions[ name ];
  9807. }
  9808. let extension;
  9809. switch ( name ) {
  9810. case 'WEBGL_depth_texture':
  9811. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9812. break;
  9813. case 'EXT_texture_filter_anisotropic':
  9814. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9815. break;
  9816. case 'WEBGL_compressed_texture_s3tc':
  9817. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9818. break;
  9819. case 'WEBGL_compressed_texture_pvrtc':
  9820. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9821. break;
  9822. default:
  9823. extension = gl.getExtension( name );
  9824. }
  9825. extensions[ name ] = extension;
  9826. return extension;
  9827. }
  9828. return {
  9829. has: function ( name ) {
  9830. return getExtension( name ) !== null;
  9831. },
  9832. init: function ( capabilities ) {
  9833. if ( capabilities.isWebGL2 ) {
  9834. getExtension( 'EXT_color_buffer_float' );
  9835. } else {
  9836. getExtension( 'WEBGL_depth_texture' );
  9837. getExtension( 'OES_texture_float' );
  9838. getExtension( 'OES_texture_half_float' );
  9839. getExtension( 'OES_texture_half_float_linear' );
  9840. getExtension( 'OES_standard_derivatives' );
  9841. getExtension( 'OES_element_index_uint' );
  9842. getExtension( 'OES_vertex_array_object' );
  9843. getExtension( 'ANGLE_instanced_arrays' );
  9844. }
  9845. getExtension( 'OES_texture_float_linear' );
  9846. getExtension( 'EXT_color_buffer_half_float' );
  9847. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9848. },
  9849. get: function ( name ) {
  9850. const extension = getExtension( name );
  9851. if ( extension === null ) {
  9852. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9853. }
  9854. return extension;
  9855. }
  9856. };
  9857. }
  9858. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9859. const geometries = {};
  9860. const wireframeAttributes = new WeakMap();
  9861. function onGeometryDispose( event ) {
  9862. const geometry = event.target;
  9863. if ( geometry.index !== null ) {
  9864. attributes.remove( geometry.index );
  9865. }
  9866. for ( const name in geometry.attributes ) {
  9867. attributes.remove( geometry.attributes[ name ] );
  9868. }
  9869. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9870. delete geometries[ geometry.id ];
  9871. const attribute = wireframeAttributes.get( geometry );
  9872. if ( attribute ) {
  9873. attributes.remove( attribute );
  9874. wireframeAttributes.delete( geometry );
  9875. }
  9876. bindingStates.releaseStatesOfGeometry( geometry );
  9877. if ( geometry.isInstancedBufferGeometry === true ) {
  9878. delete geometry._maxInstanceCount;
  9879. }
  9880. //
  9881. info.memory.geometries --;
  9882. }
  9883. function get( object, geometry ) {
  9884. if ( geometries[ geometry.id ] === true ) return geometry;
  9885. geometry.addEventListener( 'dispose', onGeometryDispose );
  9886. geometries[ geometry.id ] = true;
  9887. info.memory.geometries ++;
  9888. return geometry;
  9889. }
  9890. function update( geometry ) {
  9891. const geometryAttributes = geometry.attributes;
  9892. // Updating index buffer in VAO now. See WebGLBindingStates.
  9893. for ( const name in geometryAttributes ) {
  9894. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  9895. }
  9896. // morph targets
  9897. const morphAttributes = geometry.morphAttributes;
  9898. for ( const name in morphAttributes ) {
  9899. const array = morphAttributes[ name ];
  9900. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9901. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  9902. }
  9903. }
  9904. }
  9905. function updateWireframeAttribute( geometry ) {
  9906. const indices = [];
  9907. const geometryIndex = geometry.index;
  9908. const geometryPosition = geometry.attributes.position;
  9909. let version = 0;
  9910. if ( geometryIndex !== null ) {
  9911. const array = geometryIndex.array;
  9912. version = geometryIndex.version;
  9913. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9914. const a = array[ i + 0 ];
  9915. const b = array[ i + 1 ];
  9916. const c = array[ i + 2 ];
  9917. indices.push( a, b, b, c, c, a );
  9918. }
  9919. } else {
  9920. const array = geometryPosition.array;
  9921. version = geometryPosition.version;
  9922. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9923. const a = i + 0;
  9924. const b = i + 1;
  9925. const c = i + 2;
  9926. indices.push( a, b, b, c, c, a );
  9927. }
  9928. }
  9929. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9930. attribute.version = version;
  9931. // Updating index buffer in VAO now. See WebGLBindingStates
  9932. //
  9933. const previousAttribute = wireframeAttributes.get( geometry );
  9934. if ( previousAttribute ) attributes.remove( previousAttribute );
  9935. //
  9936. wireframeAttributes.set( geometry, attribute );
  9937. }
  9938. function getWireframeAttribute( geometry ) {
  9939. const currentAttribute = wireframeAttributes.get( geometry );
  9940. if ( currentAttribute ) {
  9941. const geometryIndex = geometry.index;
  9942. if ( geometryIndex !== null ) {
  9943. // if the attribute is obsolete, create a new one
  9944. if ( currentAttribute.version < geometryIndex.version ) {
  9945. updateWireframeAttribute( geometry );
  9946. }
  9947. }
  9948. } else {
  9949. updateWireframeAttribute( geometry );
  9950. }
  9951. return wireframeAttributes.get( geometry );
  9952. }
  9953. return {
  9954. get: get,
  9955. update: update,
  9956. getWireframeAttribute: getWireframeAttribute
  9957. };
  9958. }
  9959. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9960. const isWebGL2 = capabilities.isWebGL2;
  9961. let mode;
  9962. function setMode( value ) {
  9963. mode = value;
  9964. }
  9965. let type, bytesPerElement;
  9966. function setIndex( value ) {
  9967. type = value.type;
  9968. bytesPerElement = value.bytesPerElement;
  9969. }
  9970. function render( start, count ) {
  9971. gl.drawElements( mode, count, type, start * bytesPerElement );
  9972. info.update( count, mode, 1 );
  9973. }
  9974. function renderInstances( start, count, primcount ) {
  9975. if ( primcount === 0 ) return;
  9976. let extension, methodName;
  9977. if ( isWebGL2 ) {
  9978. extension = gl;
  9979. methodName = 'drawElementsInstanced';
  9980. } else {
  9981. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9982. methodName = 'drawElementsInstancedANGLE';
  9983. if ( extension === null ) {
  9984. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9985. return;
  9986. }
  9987. }
  9988. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9989. info.update( count, mode, primcount );
  9990. }
  9991. //
  9992. this.setMode = setMode;
  9993. this.setIndex = setIndex;
  9994. this.render = render;
  9995. this.renderInstances = renderInstances;
  9996. }
  9997. function WebGLInfo( gl ) {
  9998. const memory = {
  9999. geometries: 0,
  10000. textures: 0
  10001. };
  10002. const render = {
  10003. frame: 0,
  10004. calls: 0,
  10005. triangles: 0,
  10006. points: 0,
  10007. lines: 0
  10008. };
  10009. function update( count, mode, instanceCount ) {
  10010. render.calls ++;
  10011. switch ( mode ) {
  10012. case gl.TRIANGLES:
  10013. render.triangles += instanceCount * ( count / 3 );
  10014. break;
  10015. case gl.LINES:
  10016. render.lines += instanceCount * ( count / 2 );
  10017. break;
  10018. case gl.LINE_STRIP:
  10019. render.lines += instanceCount * ( count - 1 );
  10020. break;
  10021. case gl.LINE_LOOP:
  10022. render.lines += instanceCount * count;
  10023. break;
  10024. case gl.POINTS:
  10025. render.points += instanceCount * count;
  10026. break;
  10027. default:
  10028. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10029. break;
  10030. }
  10031. }
  10032. function reset() {
  10033. render.frame ++;
  10034. render.calls = 0;
  10035. render.triangles = 0;
  10036. render.points = 0;
  10037. render.lines = 0;
  10038. }
  10039. return {
  10040. memory: memory,
  10041. render: render,
  10042. programs: null,
  10043. autoReset: true,
  10044. reset: reset,
  10045. update: update
  10046. };
  10047. }
  10048. function numericalSort( a, b ) {
  10049. return a[ 0 ] - b[ 0 ];
  10050. }
  10051. function absNumericalSort( a, b ) {
  10052. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10053. }
  10054. function WebGLMorphtargets( gl, capabilities, textures ) {
  10055. const influencesList = {};
  10056. const morphInfluences = new Float32Array( 8 );
  10057. const morphTextures = new WeakMap();
  10058. const morph = new Vector4();
  10059. const workInfluences = [];
  10060. for ( let i = 0; i < 8; i ++ ) {
  10061. workInfluences[ i ] = [ i, 0 ];
  10062. }
  10063. function update( object, geometry, material, program ) {
  10064. const objectInfluences = object.morphTargetInfluences;
  10065. if ( capabilities.isWebGL2 === true ) {
  10066. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10067. // into an array of data textures. Each layer represents a single morph target.
  10068. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10069. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10070. let entry = morphTextures.get( geometry );
  10071. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10072. if ( entry !== undefined ) entry.texture.dispose();
  10073. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10074. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10075. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10076. const morphTargets = geometry.morphAttributes.position || [];
  10077. const morphNormals = geometry.morphAttributes.normal || [];
  10078. const morphColors = geometry.morphAttributes.color || [];
  10079. let vertexDataCount = 0;
  10080. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10081. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10082. if ( hasMorphColors === true ) vertexDataCount = 3;
  10083. let width = geometry.attributes.position.count * vertexDataCount;
  10084. let height = 1;
  10085. if ( width > capabilities.maxTextureSize ) {
  10086. height = Math.ceil( width / capabilities.maxTextureSize );
  10087. width = capabilities.maxTextureSize;
  10088. }
  10089. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10090. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10091. texture.type = FloatType;
  10092. texture.needsUpdate = true;
  10093. // fill buffer
  10094. const vertexDataStride = vertexDataCount * 4;
  10095. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10096. const morphTarget = morphTargets[ i ];
  10097. const morphNormal = morphNormals[ i ];
  10098. const morphColor = morphColors[ i ];
  10099. const offset = width * height * 4 * i;
  10100. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10101. const stride = j * vertexDataStride;
  10102. if ( hasMorphPosition === true ) {
  10103. morph.fromBufferAttribute( morphTarget, j );
  10104. buffer[ offset + stride + 0 ] = morph.x;
  10105. buffer[ offset + stride + 1 ] = morph.y;
  10106. buffer[ offset + stride + 2 ] = morph.z;
  10107. buffer[ offset + stride + 3 ] = 0;
  10108. }
  10109. if ( hasMorphNormals === true ) {
  10110. morph.fromBufferAttribute( morphNormal, j );
  10111. buffer[ offset + stride + 4 ] = morph.x;
  10112. buffer[ offset + stride + 5 ] = morph.y;
  10113. buffer[ offset + stride + 6 ] = morph.z;
  10114. buffer[ offset + stride + 7 ] = 0;
  10115. }
  10116. if ( hasMorphColors === true ) {
  10117. morph.fromBufferAttribute( morphColor, j );
  10118. buffer[ offset + stride + 8 ] = morph.x;
  10119. buffer[ offset + stride + 9 ] = morph.y;
  10120. buffer[ offset + stride + 10 ] = morph.z;
  10121. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10122. }
  10123. }
  10124. }
  10125. entry = {
  10126. count: morphTargetsCount,
  10127. texture: texture,
  10128. size: new Vector2( width, height )
  10129. };
  10130. morphTextures.set( geometry, entry );
  10131. function disposeTexture() {
  10132. texture.dispose();
  10133. morphTextures.delete( geometry );
  10134. geometry.removeEventListener( 'dispose', disposeTexture );
  10135. }
  10136. geometry.addEventListener( 'dispose', disposeTexture );
  10137. }
  10138. //
  10139. let morphInfluencesSum = 0;
  10140. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10141. morphInfluencesSum += objectInfluences[ i ];
  10142. }
  10143. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10144. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10145. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10146. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10147. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10148. } else {
  10149. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10150. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10151. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10152. let influences = influencesList[ geometry.id ];
  10153. if ( influences === undefined || influences.length !== length ) {
  10154. // initialise list
  10155. influences = [];
  10156. for ( let i = 0; i < length; i ++ ) {
  10157. influences[ i ] = [ i, 0 ];
  10158. }
  10159. influencesList[ geometry.id ] = influences;
  10160. }
  10161. // Collect influences
  10162. for ( let i = 0; i < length; i ++ ) {
  10163. const influence = influences[ i ];
  10164. influence[ 0 ] = i;
  10165. influence[ 1 ] = objectInfluences[ i ];
  10166. }
  10167. influences.sort( absNumericalSort );
  10168. for ( let i = 0; i < 8; i ++ ) {
  10169. if ( i < length && influences[ i ][ 1 ] ) {
  10170. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10171. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10172. } else {
  10173. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10174. workInfluences[ i ][ 1 ] = 0;
  10175. }
  10176. }
  10177. workInfluences.sort( numericalSort );
  10178. const morphTargets = geometry.morphAttributes.position;
  10179. const morphNormals = geometry.morphAttributes.normal;
  10180. let morphInfluencesSum = 0;
  10181. for ( let i = 0; i < 8; i ++ ) {
  10182. const influence = workInfluences[ i ];
  10183. const index = influence[ 0 ];
  10184. const value = influence[ 1 ];
  10185. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10186. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10187. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10188. }
  10189. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10190. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10191. }
  10192. morphInfluences[ i ] = value;
  10193. morphInfluencesSum += value;
  10194. } else {
  10195. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10196. geometry.deleteAttribute( 'morphTarget' + i );
  10197. }
  10198. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10199. geometry.deleteAttribute( 'morphNormal' + i );
  10200. }
  10201. morphInfluences[ i ] = 0;
  10202. }
  10203. }
  10204. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10205. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10206. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10207. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10208. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10209. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10210. }
  10211. }
  10212. return {
  10213. update: update
  10214. };
  10215. }
  10216. function WebGLObjects( gl, geometries, attributes, info ) {
  10217. let updateMap = new WeakMap();
  10218. function update( object ) {
  10219. const frame = info.render.frame;
  10220. const geometry = object.geometry;
  10221. const buffergeometry = geometries.get( object, geometry );
  10222. // Update once per frame
  10223. if ( updateMap.get( buffergeometry ) !== frame ) {
  10224. geometries.update( buffergeometry );
  10225. updateMap.set( buffergeometry, frame );
  10226. }
  10227. if ( object.isInstancedMesh ) {
  10228. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10229. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10230. }
  10231. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10232. if ( object.instanceColor !== null ) {
  10233. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10234. }
  10235. }
  10236. return buffergeometry;
  10237. }
  10238. function dispose() {
  10239. updateMap = new WeakMap();
  10240. }
  10241. function onInstancedMeshDispose( event ) {
  10242. const instancedMesh = event.target;
  10243. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10244. attributes.remove( instancedMesh.instanceMatrix );
  10245. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10246. }
  10247. return {
  10248. update: update,
  10249. dispose: dispose
  10250. };
  10251. }
  10252. /**
  10253. * Uniforms of a program.
  10254. * Those form a tree structure with a special top-level container for the root,
  10255. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10256. *
  10257. *
  10258. * Properties of inner nodes including the top-level container:
  10259. *
  10260. * .seq - array of nested uniforms
  10261. * .map - nested uniforms by name
  10262. *
  10263. *
  10264. * Methods of all nodes except the top-level container:
  10265. *
  10266. * .setValue( gl, value, [textures] )
  10267. *
  10268. * uploads a uniform value(s)
  10269. * the 'textures' parameter is needed for sampler uniforms
  10270. *
  10271. *
  10272. * Static methods of the top-level container (textures factorizations):
  10273. *
  10274. * .upload( gl, seq, values, textures )
  10275. *
  10276. * sets uniforms in 'seq' to 'values[id].value'
  10277. *
  10278. * .seqWithValue( seq, values ) : filteredSeq
  10279. *
  10280. * filters 'seq' entries with corresponding entry in values
  10281. *
  10282. *
  10283. * Methods of the top-level container (textures factorizations):
  10284. *
  10285. * .setValue( gl, name, value, textures )
  10286. *
  10287. * sets uniform with name 'name' to 'value'
  10288. *
  10289. * .setOptional( gl, obj, prop )
  10290. *
  10291. * like .set for an optional property of the object
  10292. *
  10293. */
  10294. const emptyTexture = /*@__PURE__*/ new Texture();
  10295. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10296. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10297. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10298. // --- Utilities ---
  10299. // Array Caches (provide typed arrays for temporary by size)
  10300. const arrayCacheF32 = [];
  10301. const arrayCacheI32 = [];
  10302. // Float32Array caches used for uploading Matrix uniforms
  10303. const mat4array = new Float32Array( 16 );
  10304. const mat3array = new Float32Array( 9 );
  10305. const mat2array = new Float32Array( 4 );
  10306. // Flattening for arrays of vectors and matrices
  10307. function flatten( array, nBlocks, blockSize ) {
  10308. const firstElem = array[ 0 ];
  10309. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10310. // unoptimized: ! isNaN( firstElem )
  10311. // see http://jacksondunstan.com/articles/983
  10312. const n = nBlocks * blockSize;
  10313. let r = arrayCacheF32[ n ];
  10314. if ( r === undefined ) {
  10315. r = new Float32Array( n );
  10316. arrayCacheF32[ n ] = r;
  10317. }
  10318. if ( nBlocks !== 0 ) {
  10319. firstElem.toArray( r, 0 );
  10320. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10321. offset += blockSize;
  10322. array[ i ].toArray( r, offset );
  10323. }
  10324. }
  10325. return r;
  10326. }
  10327. function arraysEqual( a, b ) {
  10328. if ( a.length !== b.length ) return false;
  10329. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10330. if ( a[ i ] !== b[ i ] ) return false;
  10331. }
  10332. return true;
  10333. }
  10334. function copyArray( a, b ) {
  10335. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10336. a[ i ] = b[ i ];
  10337. }
  10338. }
  10339. // Texture unit allocation
  10340. function allocTexUnits( textures, n ) {
  10341. let r = arrayCacheI32[ n ];
  10342. if ( r === undefined ) {
  10343. r = new Int32Array( n );
  10344. arrayCacheI32[ n ] = r;
  10345. }
  10346. for ( let i = 0; i !== n; ++ i ) {
  10347. r[ i ] = textures.allocateTextureUnit();
  10348. }
  10349. return r;
  10350. }
  10351. // --- Setters ---
  10352. // Note: Defining these methods externally, because they come in a bunch
  10353. // and this way their names minify.
  10354. // Single scalar
  10355. function setValueV1f( gl, v ) {
  10356. const cache = this.cache;
  10357. if ( cache[ 0 ] === v ) return;
  10358. gl.uniform1f( this.addr, v );
  10359. cache[ 0 ] = v;
  10360. }
  10361. // Single float vector (from flat array or THREE.VectorN)
  10362. function setValueV2f( gl, v ) {
  10363. const cache = this.cache;
  10364. if ( v.x !== undefined ) {
  10365. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10366. gl.uniform2f( this.addr, v.x, v.y );
  10367. cache[ 0 ] = v.x;
  10368. cache[ 1 ] = v.y;
  10369. }
  10370. } else {
  10371. if ( arraysEqual( cache, v ) ) return;
  10372. gl.uniform2fv( this.addr, v );
  10373. copyArray( cache, v );
  10374. }
  10375. }
  10376. function setValueV3f( gl, v ) {
  10377. const cache = this.cache;
  10378. if ( v.x !== undefined ) {
  10379. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10380. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10381. cache[ 0 ] = v.x;
  10382. cache[ 1 ] = v.y;
  10383. cache[ 2 ] = v.z;
  10384. }
  10385. } else if ( v.r !== undefined ) {
  10386. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10387. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10388. cache[ 0 ] = v.r;
  10389. cache[ 1 ] = v.g;
  10390. cache[ 2 ] = v.b;
  10391. }
  10392. } else {
  10393. if ( arraysEqual( cache, v ) ) return;
  10394. gl.uniform3fv( this.addr, v );
  10395. copyArray( cache, v );
  10396. }
  10397. }
  10398. function setValueV4f( gl, v ) {
  10399. const cache = this.cache;
  10400. if ( v.x !== undefined ) {
  10401. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10402. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10403. cache[ 0 ] = v.x;
  10404. cache[ 1 ] = v.y;
  10405. cache[ 2 ] = v.z;
  10406. cache[ 3 ] = v.w;
  10407. }
  10408. } else {
  10409. if ( arraysEqual( cache, v ) ) return;
  10410. gl.uniform4fv( this.addr, v );
  10411. copyArray( cache, v );
  10412. }
  10413. }
  10414. // Single matrix (from flat array or THREE.MatrixN)
  10415. function setValueM2( gl, v ) {
  10416. const cache = this.cache;
  10417. const elements = v.elements;
  10418. if ( elements === undefined ) {
  10419. if ( arraysEqual( cache, v ) ) return;
  10420. gl.uniformMatrix2fv( this.addr, false, v );
  10421. copyArray( cache, v );
  10422. } else {
  10423. if ( arraysEqual( cache, elements ) ) return;
  10424. mat2array.set( elements );
  10425. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10426. copyArray( cache, elements );
  10427. }
  10428. }
  10429. function setValueM3( gl, v ) {
  10430. const cache = this.cache;
  10431. const elements = v.elements;
  10432. if ( elements === undefined ) {
  10433. if ( arraysEqual( cache, v ) ) return;
  10434. gl.uniformMatrix3fv( this.addr, false, v );
  10435. copyArray( cache, v );
  10436. } else {
  10437. if ( arraysEqual( cache, elements ) ) return;
  10438. mat3array.set( elements );
  10439. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10440. copyArray( cache, elements );
  10441. }
  10442. }
  10443. function setValueM4( gl, v ) {
  10444. const cache = this.cache;
  10445. const elements = v.elements;
  10446. if ( elements === undefined ) {
  10447. if ( arraysEqual( cache, v ) ) return;
  10448. gl.uniformMatrix4fv( this.addr, false, v );
  10449. copyArray( cache, v );
  10450. } else {
  10451. if ( arraysEqual( cache, elements ) ) return;
  10452. mat4array.set( elements );
  10453. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10454. copyArray( cache, elements );
  10455. }
  10456. }
  10457. // Single integer / boolean
  10458. function setValueV1i( gl, v ) {
  10459. const cache = this.cache;
  10460. if ( cache[ 0 ] === v ) return;
  10461. gl.uniform1i( this.addr, v );
  10462. cache[ 0 ] = v;
  10463. }
  10464. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10465. function setValueV2i( gl, v ) {
  10466. const cache = this.cache;
  10467. if ( v.x !== undefined ) {
  10468. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10469. gl.uniform2i( this.addr, v.x, v.y );
  10470. cache[ 0 ] = v.x;
  10471. cache[ 1 ] = v.y;
  10472. }
  10473. } else {
  10474. if ( arraysEqual( cache, v ) ) return;
  10475. gl.uniform2iv( this.addr, v );
  10476. copyArray( cache, v );
  10477. }
  10478. }
  10479. function setValueV3i( gl, v ) {
  10480. const cache = this.cache;
  10481. if ( v.x !== undefined ) {
  10482. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10483. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10484. cache[ 0 ] = v.x;
  10485. cache[ 1 ] = v.y;
  10486. cache[ 2 ] = v.z;
  10487. }
  10488. } else {
  10489. if ( arraysEqual( cache, v ) ) return;
  10490. gl.uniform3iv( this.addr, v );
  10491. copyArray( cache, v );
  10492. }
  10493. }
  10494. function setValueV4i( gl, v ) {
  10495. const cache = this.cache;
  10496. if ( v.x !== undefined ) {
  10497. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10498. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10499. cache[ 0 ] = v.x;
  10500. cache[ 1 ] = v.y;
  10501. cache[ 2 ] = v.z;
  10502. cache[ 3 ] = v.w;
  10503. }
  10504. } else {
  10505. if ( arraysEqual( cache, v ) ) return;
  10506. gl.uniform4iv( this.addr, v );
  10507. copyArray( cache, v );
  10508. }
  10509. }
  10510. // Single unsigned integer
  10511. function setValueV1ui( gl, v ) {
  10512. const cache = this.cache;
  10513. if ( cache[ 0 ] === v ) return;
  10514. gl.uniform1ui( this.addr, v );
  10515. cache[ 0 ] = v;
  10516. }
  10517. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10518. function setValueV2ui( gl, v ) {
  10519. const cache = this.cache;
  10520. if ( v.x !== undefined ) {
  10521. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10522. gl.uniform2ui( this.addr, v.x, v.y );
  10523. cache[ 0 ] = v.x;
  10524. cache[ 1 ] = v.y;
  10525. }
  10526. } else {
  10527. if ( arraysEqual( cache, v ) ) return;
  10528. gl.uniform2uiv( this.addr, v );
  10529. copyArray( cache, v );
  10530. }
  10531. }
  10532. function setValueV3ui( gl, v ) {
  10533. const cache = this.cache;
  10534. if ( v.x !== undefined ) {
  10535. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10536. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10537. cache[ 0 ] = v.x;
  10538. cache[ 1 ] = v.y;
  10539. cache[ 2 ] = v.z;
  10540. }
  10541. } else {
  10542. if ( arraysEqual( cache, v ) ) return;
  10543. gl.uniform3uiv( this.addr, v );
  10544. copyArray( cache, v );
  10545. }
  10546. }
  10547. function setValueV4ui( gl, v ) {
  10548. const cache = this.cache;
  10549. if ( v.x !== undefined ) {
  10550. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10551. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10552. cache[ 0 ] = v.x;
  10553. cache[ 1 ] = v.y;
  10554. cache[ 2 ] = v.z;
  10555. cache[ 3 ] = v.w;
  10556. }
  10557. } else {
  10558. if ( arraysEqual( cache, v ) ) return;
  10559. gl.uniform4uiv( this.addr, v );
  10560. copyArray( cache, v );
  10561. }
  10562. }
  10563. // Single texture (2D / Cube)
  10564. function setValueT1( gl, v, textures ) {
  10565. const cache = this.cache;
  10566. const unit = textures.allocateTextureUnit();
  10567. if ( cache[ 0 ] !== unit ) {
  10568. gl.uniform1i( this.addr, unit );
  10569. cache[ 0 ] = unit;
  10570. }
  10571. textures.setTexture2D( v || emptyTexture, unit );
  10572. }
  10573. function setValueT3D1( gl, v, textures ) {
  10574. const cache = this.cache;
  10575. const unit = textures.allocateTextureUnit();
  10576. if ( cache[ 0 ] !== unit ) {
  10577. gl.uniform1i( this.addr, unit );
  10578. cache[ 0 ] = unit;
  10579. }
  10580. textures.setTexture3D( v || empty3dTexture, unit );
  10581. }
  10582. function setValueT6( gl, v, textures ) {
  10583. const cache = this.cache;
  10584. const unit = textures.allocateTextureUnit();
  10585. if ( cache[ 0 ] !== unit ) {
  10586. gl.uniform1i( this.addr, unit );
  10587. cache[ 0 ] = unit;
  10588. }
  10589. textures.setTextureCube( v || emptyCubeTexture, unit );
  10590. }
  10591. function setValueT2DArray1( gl, v, textures ) {
  10592. const cache = this.cache;
  10593. const unit = textures.allocateTextureUnit();
  10594. if ( cache[ 0 ] !== unit ) {
  10595. gl.uniform1i( this.addr, unit );
  10596. cache[ 0 ] = unit;
  10597. }
  10598. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10599. }
  10600. // Helper to pick the right setter for the singular case
  10601. function getSingularSetter( type ) {
  10602. switch ( type ) {
  10603. case 0x1406: return setValueV1f; // FLOAT
  10604. case 0x8b50: return setValueV2f; // _VEC2
  10605. case 0x8b51: return setValueV3f; // _VEC3
  10606. case 0x8b52: return setValueV4f; // _VEC4
  10607. case 0x8b5a: return setValueM2; // _MAT2
  10608. case 0x8b5b: return setValueM3; // _MAT3
  10609. case 0x8b5c: return setValueM4; // _MAT4
  10610. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10611. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10612. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10613. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10614. case 0x1405: return setValueV1ui; // UINT
  10615. case 0x8dc6: return setValueV2ui; // _VEC2
  10616. case 0x8dc7: return setValueV3ui; // _VEC3
  10617. case 0x8dc8: return setValueV4ui; // _VEC4
  10618. case 0x8b5e: // SAMPLER_2D
  10619. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10620. case 0x8dca: // INT_SAMPLER_2D
  10621. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10622. case 0x8b62: // SAMPLER_2D_SHADOW
  10623. return setValueT1;
  10624. case 0x8b5f: // SAMPLER_3D
  10625. case 0x8dcb: // INT_SAMPLER_3D
  10626. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10627. return setValueT3D1;
  10628. case 0x8b60: // SAMPLER_CUBE
  10629. case 0x8dcc: // INT_SAMPLER_CUBE
  10630. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10631. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10632. return setValueT6;
  10633. case 0x8dc1: // SAMPLER_2D_ARRAY
  10634. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10635. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10636. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10637. return setValueT2DArray1;
  10638. }
  10639. }
  10640. // Array of scalars
  10641. function setValueV1fArray( gl, v ) {
  10642. gl.uniform1fv( this.addr, v );
  10643. }
  10644. // Array of vectors (from flat array or array of THREE.VectorN)
  10645. function setValueV2fArray( gl, v ) {
  10646. const data = flatten( v, this.size, 2 );
  10647. gl.uniform2fv( this.addr, data );
  10648. }
  10649. function setValueV3fArray( gl, v ) {
  10650. const data = flatten( v, this.size, 3 );
  10651. gl.uniform3fv( this.addr, data );
  10652. }
  10653. function setValueV4fArray( gl, v ) {
  10654. const data = flatten( v, this.size, 4 );
  10655. gl.uniform4fv( this.addr, data );
  10656. }
  10657. // Array of matrices (from flat array or array of THREE.MatrixN)
  10658. function setValueM2Array( gl, v ) {
  10659. const data = flatten( v, this.size, 4 );
  10660. gl.uniformMatrix2fv( this.addr, false, data );
  10661. }
  10662. function setValueM3Array( gl, v ) {
  10663. const data = flatten( v, this.size, 9 );
  10664. gl.uniformMatrix3fv( this.addr, false, data );
  10665. }
  10666. function setValueM4Array( gl, v ) {
  10667. const data = flatten( v, this.size, 16 );
  10668. gl.uniformMatrix4fv( this.addr, false, data );
  10669. }
  10670. // Array of integer / boolean
  10671. function setValueV1iArray( gl, v ) {
  10672. gl.uniform1iv( this.addr, v );
  10673. }
  10674. // Array of integer / boolean vectors (from flat array)
  10675. function setValueV2iArray( gl, v ) {
  10676. gl.uniform2iv( this.addr, v );
  10677. }
  10678. function setValueV3iArray( gl, v ) {
  10679. gl.uniform3iv( this.addr, v );
  10680. }
  10681. function setValueV4iArray( gl, v ) {
  10682. gl.uniform4iv( this.addr, v );
  10683. }
  10684. // Array of unsigned integer
  10685. function setValueV1uiArray( gl, v ) {
  10686. gl.uniform1uiv( this.addr, v );
  10687. }
  10688. // Array of unsigned integer vectors (from flat array)
  10689. function setValueV2uiArray( gl, v ) {
  10690. gl.uniform2uiv( this.addr, v );
  10691. }
  10692. function setValueV3uiArray( gl, v ) {
  10693. gl.uniform3uiv( this.addr, v );
  10694. }
  10695. function setValueV4uiArray( gl, v ) {
  10696. gl.uniform4uiv( this.addr, v );
  10697. }
  10698. // Array of textures (2D / 3D / Cube / 2DArray)
  10699. function setValueT1Array( gl, v, textures ) {
  10700. const cache = this.cache;
  10701. const n = v.length;
  10702. const units = allocTexUnits( textures, n );
  10703. if ( ! arraysEqual( cache, units ) ) {
  10704. gl.uniform1iv( this.addr, units );
  10705. copyArray( cache, units );
  10706. }
  10707. for ( let i = 0; i !== n; ++ i ) {
  10708. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10709. }
  10710. }
  10711. function setValueT3DArray( gl, v, textures ) {
  10712. const cache = this.cache;
  10713. const n = v.length;
  10714. const units = allocTexUnits( textures, n );
  10715. if ( ! arraysEqual( cache, units ) ) {
  10716. gl.uniform1iv( this.addr, units );
  10717. copyArray( cache, units );
  10718. }
  10719. for ( let i = 0; i !== n; ++ i ) {
  10720. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10721. }
  10722. }
  10723. function setValueT6Array( gl, v, textures ) {
  10724. const cache = this.cache;
  10725. const n = v.length;
  10726. const units = allocTexUnits( textures, n );
  10727. if ( ! arraysEqual( cache, units ) ) {
  10728. gl.uniform1iv( this.addr, units );
  10729. copyArray( cache, units );
  10730. }
  10731. for ( let i = 0; i !== n; ++ i ) {
  10732. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10733. }
  10734. }
  10735. function setValueT2DArrayArray( gl, v, textures ) {
  10736. const cache = this.cache;
  10737. const n = v.length;
  10738. const units = allocTexUnits( textures, n );
  10739. if ( ! arraysEqual( cache, units ) ) {
  10740. gl.uniform1iv( this.addr, units );
  10741. copyArray( cache, units );
  10742. }
  10743. for ( let i = 0; i !== n; ++ i ) {
  10744. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10745. }
  10746. }
  10747. // Helper to pick the right setter for a pure (bottom-level) array
  10748. function getPureArraySetter( type ) {
  10749. switch ( type ) {
  10750. case 0x1406: return setValueV1fArray; // FLOAT
  10751. case 0x8b50: return setValueV2fArray; // _VEC2
  10752. case 0x8b51: return setValueV3fArray; // _VEC3
  10753. case 0x8b52: return setValueV4fArray; // _VEC4
  10754. case 0x8b5a: return setValueM2Array; // _MAT2
  10755. case 0x8b5b: return setValueM3Array; // _MAT3
  10756. case 0x8b5c: return setValueM4Array; // _MAT4
  10757. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10758. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10759. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10760. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10761. case 0x1405: return setValueV1uiArray; // UINT
  10762. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10763. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10764. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10765. case 0x8b5e: // SAMPLER_2D
  10766. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10767. case 0x8dca: // INT_SAMPLER_2D
  10768. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10769. case 0x8b62: // SAMPLER_2D_SHADOW
  10770. return setValueT1Array;
  10771. case 0x8b5f: // SAMPLER_3D
  10772. case 0x8dcb: // INT_SAMPLER_3D
  10773. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10774. return setValueT3DArray;
  10775. case 0x8b60: // SAMPLER_CUBE
  10776. case 0x8dcc: // INT_SAMPLER_CUBE
  10777. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10778. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10779. return setValueT6Array;
  10780. case 0x8dc1: // SAMPLER_2D_ARRAY
  10781. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10782. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10783. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10784. return setValueT2DArrayArray;
  10785. }
  10786. }
  10787. // --- Uniform Classes ---
  10788. class SingleUniform {
  10789. constructor( id, activeInfo, addr ) {
  10790. this.id = id;
  10791. this.addr = addr;
  10792. this.cache = [];
  10793. this.setValue = getSingularSetter( activeInfo.type );
  10794. // this.path = activeInfo.name; // DEBUG
  10795. }
  10796. }
  10797. class PureArrayUniform {
  10798. constructor( id, activeInfo, addr ) {
  10799. this.id = id;
  10800. this.addr = addr;
  10801. this.cache = [];
  10802. this.size = activeInfo.size;
  10803. this.setValue = getPureArraySetter( activeInfo.type );
  10804. // this.path = activeInfo.name; // DEBUG
  10805. }
  10806. }
  10807. class StructuredUniform {
  10808. constructor( id ) {
  10809. this.id = id;
  10810. this.seq = [];
  10811. this.map = {};
  10812. }
  10813. setValue( gl, value, textures ) {
  10814. const seq = this.seq;
  10815. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10816. const u = seq[ i ];
  10817. u.setValue( gl, value[ u.id ], textures );
  10818. }
  10819. }
  10820. }
  10821. // --- Top-level ---
  10822. // Parser - builds up the property tree from the path strings
  10823. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10824. // extracts
  10825. // - the identifier (member name or array index)
  10826. // - followed by an optional right bracket (found when array index)
  10827. // - followed by an optional left bracket or dot (type of subscript)
  10828. //
  10829. // Note: These portions can be read in a non-overlapping fashion and
  10830. // allow straightforward parsing of the hierarchy that WebGL encodes
  10831. // in the uniform names.
  10832. function addUniform( container, uniformObject ) {
  10833. container.seq.push( uniformObject );
  10834. container.map[ uniformObject.id ] = uniformObject;
  10835. }
  10836. function parseUniform( activeInfo, addr, container ) {
  10837. const path = activeInfo.name,
  10838. pathLength = path.length;
  10839. // reset RegExp object, because of the early exit of a previous run
  10840. RePathPart.lastIndex = 0;
  10841. while ( true ) {
  10842. const match = RePathPart.exec( path ),
  10843. matchEnd = RePathPart.lastIndex;
  10844. let id = match[ 1 ];
  10845. const idIsIndex = match[ 2 ] === ']',
  10846. subscript = match[ 3 ];
  10847. if ( idIsIndex ) id = id | 0; // convert to integer
  10848. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10849. // bare name or "pure" bottom-level array "[0]" suffix
  10850. addUniform( container, subscript === undefined ?
  10851. new SingleUniform( id, activeInfo, addr ) :
  10852. new PureArrayUniform( id, activeInfo, addr ) );
  10853. break;
  10854. } else {
  10855. // step into inner node / create it in case it doesn't exist
  10856. const map = container.map;
  10857. let next = map[ id ];
  10858. if ( next === undefined ) {
  10859. next = new StructuredUniform( id );
  10860. addUniform( container, next );
  10861. }
  10862. container = next;
  10863. }
  10864. }
  10865. }
  10866. // Root Container
  10867. class WebGLUniforms {
  10868. constructor( gl, program ) {
  10869. this.seq = [];
  10870. this.map = {};
  10871. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  10872. for ( let i = 0; i < n; ++ i ) {
  10873. const info = gl.getActiveUniform( program, i ),
  10874. addr = gl.getUniformLocation( program, info.name );
  10875. parseUniform( info, addr, this );
  10876. }
  10877. }
  10878. setValue( gl, name, value, textures ) {
  10879. const u = this.map[ name ];
  10880. if ( u !== undefined ) u.setValue( gl, value, textures );
  10881. }
  10882. setOptional( gl, object, name ) {
  10883. const v = object[ name ];
  10884. if ( v !== undefined ) this.setValue( gl, name, v );
  10885. }
  10886. static upload( gl, seq, values, textures ) {
  10887. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10888. const u = seq[ i ],
  10889. v = values[ u.id ];
  10890. if ( v.needsUpdate !== false ) {
  10891. // note: always updating when .needsUpdate is undefined
  10892. u.setValue( gl, v.value, textures );
  10893. }
  10894. }
  10895. }
  10896. static seqWithValue( seq, values ) {
  10897. const r = [];
  10898. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10899. const u = seq[ i ];
  10900. if ( u.id in values ) r.push( u );
  10901. }
  10902. return r;
  10903. }
  10904. }
  10905. function WebGLShader( gl, type, string ) {
  10906. const shader = gl.createShader( type );
  10907. gl.shaderSource( shader, string );
  10908. gl.compileShader( shader );
  10909. return shader;
  10910. }
  10911. let programIdCount = 0;
  10912. function handleSource( string, errorLine ) {
  10913. const lines = string.split( '\n' );
  10914. const lines2 = [];
  10915. const from = Math.max( errorLine - 6, 0 );
  10916. const to = Math.min( errorLine + 6, lines.length );
  10917. for ( let i = from; i < to; i ++ ) {
  10918. const line = i + 1;
  10919. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10920. }
  10921. return lines2.join( '\n' );
  10922. }
  10923. function getEncodingComponents( encoding ) {
  10924. switch ( encoding ) {
  10925. case LinearEncoding:
  10926. return [ 'Linear', '( value )' ];
  10927. case sRGBEncoding:
  10928. return [ 'sRGB', '( value )' ];
  10929. default:
  10930. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10931. return [ 'Linear', '( value )' ];
  10932. }
  10933. }
  10934. function getShaderErrors( gl, shader, type ) {
  10935. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  10936. const errors = gl.getShaderInfoLog( shader ).trim();
  10937. if ( status && errors === '' ) return '';
  10938. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10939. if ( errorMatches ) {
  10940. // --enable-privileged-webgl-extension
  10941. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10942. const errorLine = parseInt( errorMatches[ 1 ] );
  10943. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10944. } else {
  10945. return errors;
  10946. }
  10947. }
  10948. function getTexelEncodingFunction( functionName, encoding ) {
  10949. const components = getEncodingComponents( encoding );
  10950. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10951. }
  10952. function getToneMappingFunction( functionName, toneMapping ) {
  10953. let toneMappingName;
  10954. switch ( toneMapping ) {
  10955. case LinearToneMapping:
  10956. toneMappingName = 'Linear';
  10957. break;
  10958. case ReinhardToneMapping:
  10959. toneMappingName = 'Reinhard';
  10960. break;
  10961. case CineonToneMapping:
  10962. toneMappingName = 'OptimizedCineon';
  10963. break;
  10964. case ACESFilmicToneMapping:
  10965. toneMappingName = 'ACESFilmic';
  10966. break;
  10967. case CustomToneMapping:
  10968. toneMappingName = 'Custom';
  10969. break;
  10970. default:
  10971. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10972. toneMappingName = 'Linear';
  10973. }
  10974. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10975. }
  10976. function generateExtensions( parameters ) {
  10977. const chunks = [
  10978. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10979. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10980. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10981. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10982. ];
  10983. return chunks.filter( filterEmptyLine ).join( '\n' );
  10984. }
  10985. function generateDefines( defines ) {
  10986. const chunks = [];
  10987. for ( const name in defines ) {
  10988. const value = defines[ name ];
  10989. if ( value === false ) continue;
  10990. chunks.push( '#define ' + name + ' ' + value );
  10991. }
  10992. return chunks.join( '\n' );
  10993. }
  10994. function fetchAttributeLocations( gl, program ) {
  10995. const attributes = {};
  10996. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  10997. for ( let i = 0; i < n; i ++ ) {
  10998. const info = gl.getActiveAttrib( program, i );
  10999. const name = info.name;
  11000. let locationSize = 1;
  11001. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11002. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11003. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11004. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11005. attributes[ name ] = {
  11006. type: info.type,
  11007. location: gl.getAttribLocation( program, name ),
  11008. locationSize: locationSize
  11009. };
  11010. }
  11011. return attributes;
  11012. }
  11013. function filterEmptyLine( string ) {
  11014. return string !== '';
  11015. }
  11016. function replaceLightNums( string, parameters ) {
  11017. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11018. return string
  11019. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11020. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11021. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11022. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11023. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11024. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11025. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11026. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11027. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11028. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11029. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11030. }
  11031. function replaceClippingPlaneNums( string, parameters ) {
  11032. return string
  11033. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11034. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11035. }
  11036. // Resolve Includes
  11037. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11038. function resolveIncludes( string ) {
  11039. return string.replace( includePattern, includeReplacer );
  11040. }
  11041. function includeReplacer( match, include ) {
  11042. const string = ShaderChunk[ include ];
  11043. if ( string === undefined ) {
  11044. throw new Error( 'Can not resolve #include <' + include + '>' );
  11045. }
  11046. return resolveIncludes( string );
  11047. }
  11048. // Unroll Loops
  11049. 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;
  11050. function unrollLoops( string ) {
  11051. return string.replace( unrollLoopPattern, loopReplacer );
  11052. }
  11053. function loopReplacer( match, start, end, snippet ) {
  11054. let string = '';
  11055. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11056. string += snippet
  11057. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11058. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11059. }
  11060. return string;
  11061. }
  11062. //
  11063. function generatePrecision( parameters ) {
  11064. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11065. if ( parameters.precision === 'highp' ) {
  11066. precisionstring += '\n#define HIGH_PRECISION';
  11067. } else if ( parameters.precision === 'mediump' ) {
  11068. precisionstring += '\n#define MEDIUM_PRECISION';
  11069. } else if ( parameters.precision === 'lowp' ) {
  11070. precisionstring += '\n#define LOW_PRECISION';
  11071. }
  11072. return precisionstring;
  11073. }
  11074. function generateShadowMapTypeDefine( parameters ) {
  11075. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11076. if ( parameters.shadowMapType === PCFShadowMap ) {
  11077. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11078. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11079. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11080. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11081. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11082. }
  11083. return shadowMapTypeDefine;
  11084. }
  11085. function generateEnvMapTypeDefine( parameters ) {
  11086. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11087. if ( parameters.envMap ) {
  11088. switch ( parameters.envMapMode ) {
  11089. case CubeReflectionMapping:
  11090. case CubeRefractionMapping:
  11091. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11092. break;
  11093. case CubeUVReflectionMapping:
  11094. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11095. break;
  11096. }
  11097. }
  11098. return envMapTypeDefine;
  11099. }
  11100. function generateEnvMapModeDefine( parameters ) {
  11101. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11102. if ( parameters.envMap ) {
  11103. switch ( parameters.envMapMode ) {
  11104. case CubeRefractionMapping:
  11105. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11106. break;
  11107. }
  11108. }
  11109. return envMapModeDefine;
  11110. }
  11111. function generateEnvMapBlendingDefine( parameters ) {
  11112. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11113. if ( parameters.envMap ) {
  11114. switch ( parameters.combine ) {
  11115. case MultiplyOperation:
  11116. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11117. break;
  11118. case MixOperation:
  11119. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11120. break;
  11121. case AddOperation:
  11122. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11123. break;
  11124. }
  11125. }
  11126. return envMapBlendingDefine;
  11127. }
  11128. function generateCubeUVSize( parameters ) {
  11129. const imageHeight = parameters.envMapCubeUVHeight;
  11130. if ( imageHeight === null ) return null;
  11131. const maxMip = Math.log2( imageHeight ) - 2;
  11132. const texelHeight = 1.0 / imageHeight;
  11133. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11134. return { texelWidth, texelHeight, maxMip };
  11135. }
  11136. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11137. // TODO Send this event to Three.js DevTools
  11138. // console.log( 'WebGLProgram', cacheKey );
  11139. const gl = renderer.getContext();
  11140. const defines = parameters.defines;
  11141. let vertexShader = parameters.vertexShader;
  11142. let fragmentShader = parameters.fragmentShader;
  11143. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11144. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11145. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11146. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11147. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11148. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11149. const customDefines = generateDefines( defines );
  11150. const program = gl.createProgram();
  11151. let prefixVertex, prefixFragment;
  11152. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11153. if ( parameters.isRawShaderMaterial ) {
  11154. prefixVertex = [
  11155. customDefines
  11156. ].filter( filterEmptyLine ).join( '\n' );
  11157. if ( prefixVertex.length > 0 ) {
  11158. prefixVertex += '\n';
  11159. }
  11160. prefixFragment = [
  11161. customExtensions,
  11162. customDefines
  11163. ].filter( filterEmptyLine ).join( '\n' );
  11164. if ( prefixFragment.length > 0 ) {
  11165. prefixFragment += '\n';
  11166. }
  11167. } else {
  11168. prefixVertex = [
  11169. generatePrecision( parameters ),
  11170. '#define SHADER_NAME ' + parameters.shaderName,
  11171. customDefines,
  11172. parameters.instancing ? '#define USE_INSTANCING' : '',
  11173. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11174. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11175. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11176. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11177. parameters.map ? '#define USE_MAP' : '',
  11178. parameters.envMap ? '#define USE_ENVMAP' : '',
  11179. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11180. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11181. parameters.aoMap ? '#define USE_AOMAP' : '',
  11182. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11183. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11184. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11185. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11186. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11187. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11188. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11189. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11190. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11191. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11192. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11193. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11194. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11195. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11196. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11197. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11198. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11199. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11200. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11201. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11202. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11203. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11204. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11205. parameters.vertexColors ? '#define USE_COLOR' : '',
  11206. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11207. parameters.vertexUvs ? '#define USE_UV' : '',
  11208. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11209. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11210. parameters.skinning ? '#define USE_SKINNING' : '',
  11211. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11212. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11213. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11214. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11215. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11216. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11217. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11218. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11219. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11220. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11221. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11222. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11223. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11224. 'uniform mat4 modelMatrix;',
  11225. 'uniform mat4 modelViewMatrix;',
  11226. 'uniform mat4 projectionMatrix;',
  11227. 'uniform mat4 viewMatrix;',
  11228. 'uniform mat3 normalMatrix;',
  11229. 'uniform vec3 cameraPosition;',
  11230. 'uniform bool isOrthographic;',
  11231. '#ifdef USE_INSTANCING',
  11232. ' attribute mat4 instanceMatrix;',
  11233. '#endif',
  11234. '#ifdef USE_INSTANCING_COLOR',
  11235. ' attribute vec3 instanceColor;',
  11236. '#endif',
  11237. 'attribute vec3 position;',
  11238. 'attribute vec3 normal;',
  11239. 'attribute vec2 uv;',
  11240. '#ifdef USE_TANGENT',
  11241. ' attribute vec4 tangent;',
  11242. '#endif',
  11243. '#if defined( USE_COLOR_ALPHA )',
  11244. ' attribute vec4 color;',
  11245. '#elif defined( USE_COLOR )',
  11246. ' attribute vec3 color;',
  11247. '#endif',
  11248. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11249. ' attribute vec3 morphTarget0;',
  11250. ' attribute vec3 morphTarget1;',
  11251. ' attribute vec3 morphTarget2;',
  11252. ' attribute vec3 morphTarget3;',
  11253. ' #ifdef USE_MORPHNORMALS',
  11254. ' attribute vec3 morphNormal0;',
  11255. ' attribute vec3 morphNormal1;',
  11256. ' attribute vec3 morphNormal2;',
  11257. ' attribute vec3 morphNormal3;',
  11258. ' #else',
  11259. ' attribute vec3 morphTarget4;',
  11260. ' attribute vec3 morphTarget5;',
  11261. ' attribute vec3 morphTarget6;',
  11262. ' attribute vec3 morphTarget7;',
  11263. ' #endif',
  11264. '#endif',
  11265. '#ifdef USE_SKINNING',
  11266. ' attribute vec4 skinIndex;',
  11267. ' attribute vec4 skinWeight;',
  11268. '#endif',
  11269. '\n'
  11270. ].filter( filterEmptyLine ).join( '\n' );
  11271. prefixFragment = [
  11272. customExtensions,
  11273. generatePrecision( parameters ),
  11274. '#define SHADER_NAME ' + parameters.shaderName,
  11275. customDefines,
  11276. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11277. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11278. parameters.map ? '#define USE_MAP' : '',
  11279. parameters.matcap ? '#define USE_MATCAP' : '',
  11280. parameters.envMap ? '#define USE_ENVMAP' : '',
  11281. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11282. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11283. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11284. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11285. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11286. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11287. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11288. parameters.aoMap ? '#define USE_AOMAP' : '',
  11289. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11290. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11291. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11292. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11293. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11294. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11295. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11296. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11297. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11298. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11299. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11300. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11301. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11302. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11303. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11304. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11305. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11306. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11307. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11308. parameters.sheen ? '#define USE_SHEEN' : '',
  11309. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11310. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11311. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11312. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11313. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11314. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11315. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11316. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11317. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11318. parameters.vertexUvs ? '#define USE_UV' : '',
  11319. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11320. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11321. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11322. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11323. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11324. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11325. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11326. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11327. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11328. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11329. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11330. 'uniform mat4 viewMatrix;',
  11331. 'uniform vec3 cameraPosition;',
  11332. 'uniform bool isOrthographic;',
  11333. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11334. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11335. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11336. parameters.dithering ? '#define DITHERING' : '',
  11337. parameters.opaque ? '#define OPAQUE' : '',
  11338. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11339. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11340. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11341. '\n'
  11342. ].filter( filterEmptyLine ).join( '\n' );
  11343. }
  11344. vertexShader = resolveIncludes( vertexShader );
  11345. vertexShader = replaceLightNums( vertexShader, parameters );
  11346. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11347. fragmentShader = resolveIncludes( fragmentShader );
  11348. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11349. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11350. vertexShader = unrollLoops( vertexShader );
  11351. fragmentShader = unrollLoops( fragmentShader );
  11352. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11353. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11354. versionString = '#version 300 es\n';
  11355. prefixVertex = [
  11356. 'precision mediump sampler2DArray;',
  11357. '#define attribute in',
  11358. '#define varying out',
  11359. '#define texture2D texture'
  11360. ].join( '\n' ) + '\n' + prefixVertex;
  11361. prefixFragment = [
  11362. '#define varying in',
  11363. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11364. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11365. '#define gl_FragDepthEXT gl_FragDepth',
  11366. '#define texture2D texture',
  11367. '#define textureCube texture',
  11368. '#define texture2DProj textureProj',
  11369. '#define texture2DLodEXT textureLod',
  11370. '#define texture2DProjLodEXT textureProjLod',
  11371. '#define textureCubeLodEXT textureLod',
  11372. '#define texture2DGradEXT textureGrad',
  11373. '#define texture2DProjGradEXT textureProjGrad',
  11374. '#define textureCubeGradEXT textureGrad'
  11375. ].join( '\n' ) + '\n' + prefixFragment;
  11376. }
  11377. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11378. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11379. // console.log( '*VERTEX*', vertexGlsl );
  11380. // console.log( '*FRAGMENT*', fragmentGlsl );
  11381. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11382. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11383. gl.attachShader( program, glVertexShader );
  11384. gl.attachShader( program, glFragmentShader );
  11385. // Force a particular attribute to index 0.
  11386. if ( parameters.index0AttributeName !== undefined ) {
  11387. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11388. } else if ( parameters.morphTargets === true ) {
  11389. // programs with morphTargets displace position out of attribute 0
  11390. gl.bindAttribLocation( program, 0, 'position' );
  11391. }
  11392. gl.linkProgram( program );
  11393. // check for link errors
  11394. if ( renderer.debug.checkShaderErrors ) {
  11395. const programLog = gl.getProgramInfoLog( program ).trim();
  11396. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11397. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11398. let runnable = true;
  11399. let haveDiagnostics = true;
  11400. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11401. runnable = false;
  11402. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11403. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11404. console.error(
  11405. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11406. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11407. 'Program Info Log: ' + programLog + '\n' +
  11408. vertexErrors + '\n' +
  11409. fragmentErrors
  11410. );
  11411. } else if ( programLog !== '' ) {
  11412. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11413. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11414. haveDiagnostics = false;
  11415. }
  11416. if ( haveDiagnostics ) {
  11417. this.diagnostics = {
  11418. runnable: runnable,
  11419. programLog: programLog,
  11420. vertexShader: {
  11421. log: vertexLog,
  11422. prefix: prefixVertex
  11423. },
  11424. fragmentShader: {
  11425. log: fragmentLog,
  11426. prefix: prefixFragment
  11427. }
  11428. };
  11429. }
  11430. }
  11431. // Clean up
  11432. // Crashes in iOS9 and iOS10. #18402
  11433. // gl.detachShader( program, glVertexShader );
  11434. // gl.detachShader( program, glFragmentShader );
  11435. gl.deleteShader( glVertexShader );
  11436. gl.deleteShader( glFragmentShader );
  11437. // set up caching for uniform locations
  11438. let cachedUniforms;
  11439. this.getUniforms = function () {
  11440. if ( cachedUniforms === undefined ) {
  11441. cachedUniforms = new WebGLUniforms( gl, program );
  11442. }
  11443. return cachedUniforms;
  11444. };
  11445. // set up caching for attribute locations
  11446. let cachedAttributes;
  11447. this.getAttributes = function () {
  11448. if ( cachedAttributes === undefined ) {
  11449. cachedAttributes = fetchAttributeLocations( gl, program );
  11450. }
  11451. return cachedAttributes;
  11452. };
  11453. // free resource
  11454. this.destroy = function () {
  11455. bindingStates.releaseStatesOfProgram( this );
  11456. gl.deleteProgram( program );
  11457. this.program = undefined;
  11458. };
  11459. //
  11460. this.name = parameters.shaderName;
  11461. this.id = programIdCount ++;
  11462. this.cacheKey = cacheKey;
  11463. this.usedTimes = 1;
  11464. this.program = program;
  11465. this.vertexShader = glVertexShader;
  11466. this.fragmentShader = glFragmentShader;
  11467. return this;
  11468. }
  11469. let _id = 0;
  11470. class WebGLShaderCache {
  11471. constructor() {
  11472. this.shaderCache = new Map();
  11473. this.materialCache = new Map();
  11474. }
  11475. update( material ) {
  11476. const vertexShader = material.vertexShader;
  11477. const fragmentShader = material.fragmentShader;
  11478. const vertexShaderStage = this._getShaderStage( vertexShader );
  11479. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11480. const materialShaders = this._getShaderCacheForMaterial( material );
  11481. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11482. materialShaders.add( vertexShaderStage );
  11483. vertexShaderStage.usedTimes ++;
  11484. }
  11485. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11486. materialShaders.add( fragmentShaderStage );
  11487. fragmentShaderStage.usedTimes ++;
  11488. }
  11489. return this;
  11490. }
  11491. remove( material ) {
  11492. const materialShaders = this.materialCache.get( material );
  11493. for ( const shaderStage of materialShaders ) {
  11494. shaderStage.usedTimes --;
  11495. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11496. }
  11497. this.materialCache.delete( material );
  11498. return this;
  11499. }
  11500. getVertexShaderID( material ) {
  11501. return this._getShaderStage( material.vertexShader ).id;
  11502. }
  11503. getFragmentShaderID( material ) {
  11504. return this._getShaderStage( material.fragmentShader ).id;
  11505. }
  11506. dispose() {
  11507. this.shaderCache.clear();
  11508. this.materialCache.clear();
  11509. }
  11510. _getShaderCacheForMaterial( material ) {
  11511. const cache = this.materialCache;
  11512. let set = cache.get( material );
  11513. if ( set === undefined ) {
  11514. set = new Set();
  11515. cache.set( material, set );
  11516. }
  11517. return set;
  11518. }
  11519. _getShaderStage( code ) {
  11520. const cache = this.shaderCache;
  11521. let stage = cache.get( code );
  11522. if ( stage === undefined ) {
  11523. stage = new WebGLShaderStage( code );
  11524. cache.set( code, stage );
  11525. }
  11526. return stage;
  11527. }
  11528. }
  11529. class WebGLShaderStage {
  11530. constructor( code ) {
  11531. this.id = _id ++;
  11532. this.code = code;
  11533. this.usedTimes = 0;
  11534. }
  11535. }
  11536. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11537. const _programLayers = new Layers();
  11538. const _customShaders = new WebGLShaderCache();
  11539. const programs = [];
  11540. const isWebGL2 = capabilities.isWebGL2;
  11541. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11542. const vertexTextures = capabilities.vertexTextures;
  11543. let precision = capabilities.precision;
  11544. const shaderIDs = {
  11545. MeshDepthMaterial: 'depth',
  11546. MeshDistanceMaterial: 'distanceRGBA',
  11547. MeshNormalMaterial: 'normal',
  11548. MeshBasicMaterial: 'basic',
  11549. MeshLambertMaterial: 'lambert',
  11550. MeshPhongMaterial: 'phong',
  11551. MeshToonMaterial: 'toon',
  11552. MeshStandardMaterial: 'physical',
  11553. MeshPhysicalMaterial: 'physical',
  11554. MeshMatcapMaterial: 'matcap',
  11555. LineBasicMaterial: 'basic',
  11556. LineDashedMaterial: 'dashed',
  11557. PointsMaterial: 'points',
  11558. ShadowMaterial: 'shadow',
  11559. SpriteMaterial: 'sprite'
  11560. };
  11561. function getParameters( material, lights, shadows, scene, object ) {
  11562. const fog = scene.fog;
  11563. const geometry = object.geometry;
  11564. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11565. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11566. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11567. const shaderID = shaderIDs[ material.type ];
  11568. // heuristics to create shader parameters according to lights in the scene
  11569. // (not to blow over maxLights budget)
  11570. if ( material.precision !== null ) {
  11571. precision = capabilities.getMaxPrecision( material.precision );
  11572. if ( precision !== material.precision ) {
  11573. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11574. }
  11575. }
  11576. //
  11577. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11578. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11579. let morphTextureStride = 0;
  11580. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11581. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11582. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11583. //
  11584. let vertexShader, fragmentShader;
  11585. let customVertexShaderID, customFragmentShaderID;
  11586. if ( shaderID ) {
  11587. const shader = ShaderLib[ shaderID ];
  11588. vertexShader = shader.vertexShader;
  11589. fragmentShader = shader.fragmentShader;
  11590. } else {
  11591. vertexShader = material.vertexShader;
  11592. fragmentShader = material.fragmentShader;
  11593. _customShaders.update( material );
  11594. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11595. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11596. }
  11597. const currentRenderTarget = renderer.getRenderTarget();
  11598. const useAlphaTest = material.alphaTest > 0;
  11599. const useClearcoat = material.clearcoat > 0;
  11600. const useIridescence = material.iridescence > 0;
  11601. const parameters = {
  11602. isWebGL2: isWebGL2,
  11603. shaderID: shaderID,
  11604. shaderName: material.type,
  11605. vertexShader: vertexShader,
  11606. fragmentShader: fragmentShader,
  11607. defines: material.defines,
  11608. customVertexShaderID: customVertexShaderID,
  11609. customFragmentShaderID: customFragmentShaderID,
  11610. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11611. glslVersion: material.glslVersion,
  11612. precision: precision,
  11613. instancing: object.isInstancedMesh === true,
  11614. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11615. supportsVertexTextures: vertexTextures,
  11616. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11617. map: !! material.map,
  11618. matcap: !! material.matcap,
  11619. envMap: !! envMap,
  11620. envMapMode: envMap && envMap.mapping,
  11621. envMapCubeUVHeight: envMapCubeUVHeight,
  11622. lightMap: !! material.lightMap,
  11623. aoMap: !! material.aoMap,
  11624. emissiveMap: !! material.emissiveMap,
  11625. bumpMap: !! material.bumpMap,
  11626. normalMap: !! material.normalMap,
  11627. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11628. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11629. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11630. clearcoat: useClearcoat,
  11631. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11632. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11633. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11634. iridescence: useIridescence,
  11635. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11636. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11637. displacementMap: !! material.displacementMap,
  11638. roughnessMap: !! material.roughnessMap,
  11639. metalnessMap: !! material.metalnessMap,
  11640. specularMap: !! material.specularMap,
  11641. specularIntensityMap: !! material.specularIntensityMap,
  11642. specularColorMap: !! material.specularColorMap,
  11643. opaque: material.transparent === false && material.blending === NormalBlending,
  11644. alphaMap: !! material.alphaMap,
  11645. alphaTest: useAlphaTest,
  11646. gradientMap: !! material.gradientMap,
  11647. sheen: material.sheen > 0,
  11648. sheenColorMap: !! material.sheenColorMap,
  11649. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11650. transmission: material.transmission > 0,
  11651. transmissionMap: !! material.transmissionMap,
  11652. thicknessMap: !! material.thicknessMap,
  11653. combine: material.combine,
  11654. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11655. vertexColors: material.vertexColors,
  11656. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11657. 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,
  11658. 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,
  11659. fog: !! fog,
  11660. useFog: material.fog === true,
  11661. fogExp2: ( fog && fog.isFogExp2 ),
  11662. flatShading: !! material.flatShading,
  11663. sizeAttenuation: material.sizeAttenuation,
  11664. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11665. skinning: object.isSkinnedMesh === true,
  11666. morphTargets: geometry.morphAttributes.position !== undefined,
  11667. morphNormals: geometry.morphAttributes.normal !== undefined,
  11668. morphColors: geometry.morphAttributes.color !== undefined,
  11669. morphTargetsCount: morphTargetsCount,
  11670. morphTextureStride: morphTextureStride,
  11671. numDirLights: lights.directional.length,
  11672. numPointLights: lights.point.length,
  11673. numSpotLights: lights.spot.length,
  11674. numSpotLightMaps: lights.spotLightMap.length,
  11675. numRectAreaLights: lights.rectArea.length,
  11676. numHemiLights: lights.hemi.length,
  11677. numDirLightShadows: lights.directionalShadowMap.length,
  11678. numPointLightShadows: lights.pointShadowMap.length,
  11679. numSpotLightShadows: lights.spotShadowMap.length,
  11680. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11681. numClippingPlanes: clipping.numPlanes,
  11682. numClipIntersection: clipping.numIntersection,
  11683. dithering: material.dithering,
  11684. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11685. shadowMapType: renderer.shadowMap.type,
  11686. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11687. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11688. premultipliedAlpha: material.premultipliedAlpha,
  11689. doubleSided: material.side === DoubleSide,
  11690. flipSided: material.side === BackSide,
  11691. useDepthPacking: !! material.depthPacking,
  11692. depthPacking: material.depthPacking || 0,
  11693. index0AttributeName: material.index0AttributeName,
  11694. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11695. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11696. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11697. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11698. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11699. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11700. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11701. customProgramCacheKey: material.customProgramCacheKey()
  11702. };
  11703. return parameters;
  11704. }
  11705. function getProgramCacheKey( parameters ) {
  11706. const array = [];
  11707. if ( parameters.shaderID ) {
  11708. array.push( parameters.shaderID );
  11709. } else {
  11710. array.push( parameters.customVertexShaderID );
  11711. array.push( parameters.customFragmentShaderID );
  11712. }
  11713. if ( parameters.defines !== undefined ) {
  11714. for ( const name in parameters.defines ) {
  11715. array.push( name );
  11716. array.push( parameters.defines[ name ] );
  11717. }
  11718. }
  11719. if ( parameters.isRawShaderMaterial === false ) {
  11720. getProgramCacheKeyParameters( array, parameters );
  11721. getProgramCacheKeyBooleans( array, parameters );
  11722. array.push( renderer.outputEncoding );
  11723. }
  11724. array.push( parameters.customProgramCacheKey );
  11725. return array.join();
  11726. }
  11727. function getProgramCacheKeyParameters( array, parameters ) {
  11728. array.push( parameters.precision );
  11729. array.push( parameters.outputEncoding );
  11730. array.push( parameters.envMapMode );
  11731. array.push( parameters.envMapCubeUVHeight );
  11732. array.push( parameters.combine );
  11733. array.push( parameters.vertexUvs );
  11734. array.push( parameters.fogExp2 );
  11735. array.push( parameters.sizeAttenuation );
  11736. array.push( parameters.morphTargetsCount );
  11737. array.push( parameters.morphAttributeCount );
  11738. array.push( parameters.numDirLights );
  11739. array.push( parameters.numPointLights );
  11740. array.push( parameters.numSpotLights );
  11741. array.push( parameters.numSpotLightMaps );
  11742. array.push( parameters.numHemiLights );
  11743. array.push( parameters.numRectAreaLights );
  11744. array.push( parameters.numDirLightShadows );
  11745. array.push( parameters.numPointLightShadows );
  11746. array.push( parameters.numSpotLightShadows );
  11747. array.push( parameters.numSpotLightShadowsWithMaps );
  11748. array.push( parameters.shadowMapType );
  11749. array.push( parameters.toneMapping );
  11750. array.push( parameters.numClippingPlanes );
  11751. array.push( parameters.numClipIntersection );
  11752. array.push( parameters.depthPacking );
  11753. }
  11754. function getProgramCacheKeyBooleans( array, parameters ) {
  11755. _programLayers.disableAll();
  11756. if ( parameters.isWebGL2 )
  11757. _programLayers.enable( 0 );
  11758. if ( parameters.supportsVertexTextures )
  11759. _programLayers.enable( 1 );
  11760. if ( parameters.instancing )
  11761. _programLayers.enable( 2 );
  11762. if ( parameters.instancingColor )
  11763. _programLayers.enable( 3 );
  11764. if ( parameters.map )
  11765. _programLayers.enable( 4 );
  11766. if ( parameters.matcap )
  11767. _programLayers.enable( 5 );
  11768. if ( parameters.envMap )
  11769. _programLayers.enable( 6 );
  11770. if ( parameters.lightMap )
  11771. _programLayers.enable( 7 );
  11772. if ( parameters.aoMap )
  11773. _programLayers.enable( 8 );
  11774. if ( parameters.emissiveMap )
  11775. _programLayers.enable( 9 );
  11776. if ( parameters.bumpMap )
  11777. _programLayers.enable( 10 );
  11778. if ( parameters.normalMap )
  11779. _programLayers.enable( 11 );
  11780. if ( parameters.objectSpaceNormalMap )
  11781. _programLayers.enable( 12 );
  11782. if ( parameters.tangentSpaceNormalMap )
  11783. _programLayers.enable( 13 );
  11784. if ( parameters.clearcoat )
  11785. _programLayers.enable( 14 );
  11786. if ( parameters.clearcoatMap )
  11787. _programLayers.enable( 15 );
  11788. if ( parameters.clearcoatRoughnessMap )
  11789. _programLayers.enable( 16 );
  11790. if ( parameters.clearcoatNormalMap )
  11791. _programLayers.enable( 17 );
  11792. if ( parameters.iridescence )
  11793. _programLayers.enable( 18 );
  11794. if ( parameters.iridescenceMap )
  11795. _programLayers.enable( 19 );
  11796. if ( parameters.iridescenceThicknessMap )
  11797. _programLayers.enable( 20 );
  11798. if ( parameters.displacementMap )
  11799. _programLayers.enable( 21 );
  11800. if ( parameters.specularMap )
  11801. _programLayers.enable( 22 );
  11802. if ( parameters.roughnessMap )
  11803. _programLayers.enable( 23 );
  11804. if ( parameters.metalnessMap )
  11805. _programLayers.enable( 24 );
  11806. if ( parameters.gradientMap )
  11807. _programLayers.enable( 25 );
  11808. if ( parameters.alphaMap )
  11809. _programLayers.enable( 26 );
  11810. if ( parameters.alphaTest )
  11811. _programLayers.enable( 27 );
  11812. if ( parameters.vertexColors )
  11813. _programLayers.enable( 28 );
  11814. if ( parameters.vertexAlphas )
  11815. _programLayers.enable( 29 );
  11816. if ( parameters.vertexUvs )
  11817. _programLayers.enable( 30 );
  11818. if ( parameters.vertexTangents )
  11819. _programLayers.enable( 31 );
  11820. if ( parameters.uvsVertexOnly )
  11821. _programLayers.enable( 32 );
  11822. array.push( _programLayers.mask );
  11823. _programLayers.disableAll();
  11824. if ( parameters.fog )
  11825. _programLayers.enable( 0 );
  11826. if ( parameters.useFog )
  11827. _programLayers.enable( 1 );
  11828. if ( parameters.flatShading )
  11829. _programLayers.enable( 2 );
  11830. if ( parameters.logarithmicDepthBuffer )
  11831. _programLayers.enable( 3 );
  11832. if ( parameters.skinning )
  11833. _programLayers.enable( 4 );
  11834. if ( parameters.morphTargets )
  11835. _programLayers.enable( 5 );
  11836. if ( parameters.morphNormals )
  11837. _programLayers.enable( 6 );
  11838. if ( parameters.morphColors )
  11839. _programLayers.enable( 7 );
  11840. if ( parameters.premultipliedAlpha )
  11841. _programLayers.enable( 8 );
  11842. if ( parameters.shadowMapEnabled )
  11843. _programLayers.enable( 9 );
  11844. if ( parameters.physicallyCorrectLights )
  11845. _programLayers.enable( 10 );
  11846. if ( parameters.doubleSided )
  11847. _programLayers.enable( 11 );
  11848. if ( parameters.flipSided )
  11849. _programLayers.enable( 12 );
  11850. if ( parameters.useDepthPacking )
  11851. _programLayers.enable( 13 );
  11852. if ( parameters.dithering )
  11853. _programLayers.enable( 14 );
  11854. if ( parameters.specularIntensityMap )
  11855. _programLayers.enable( 15 );
  11856. if ( parameters.specularColorMap )
  11857. _programLayers.enable( 16 );
  11858. if ( parameters.transmission )
  11859. _programLayers.enable( 17 );
  11860. if ( parameters.transmissionMap )
  11861. _programLayers.enable( 18 );
  11862. if ( parameters.thicknessMap )
  11863. _programLayers.enable( 19 );
  11864. if ( parameters.sheen )
  11865. _programLayers.enable( 20 );
  11866. if ( parameters.sheenColorMap )
  11867. _programLayers.enable( 21 );
  11868. if ( parameters.sheenRoughnessMap )
  11869. _programLayers.enable( 22 );
  11870. if ( parameters.decodeVideoTexture )
  11871. _programLayers.enable( 23 );
  11872. if ( parameters.opaque )
  11873. _programLayers.enable( 24 );
  11874. array.push( _programLayers.mask );
  11875. }
  11876. function getUniforms( material ) {
  11877. const shaderID = shaderIDs[ material.type ];
  11878. let uniforms;
  11879. if ( shaderID ) {
  11880. const shader = ShaderLib[ shaderID ];
  11881. uniforms = UniformsUtils.clone( shader.uniforms );
  11882. } else {
  11883. uniforms = material.uniforms;
  11884. }
  11885. return uniforms;
  11886. }
  11887. function acquireProgram( parameters, cacheKey ) {
  11888. let program;
  11889. // Check if code has been already compiled
  11890. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11891. const preexistingProgram = programs[ p ];
  11892. if ( preexistingProgram.cacheKey === cacheKey ) {
  11893. program = preexistingProgram;
  11894. ++ program.usedTimes;
  11895. break;
  11896. }
  11897. }
  11898. if ( program === undefined ) {
  11899. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11900. programs.push( program );
  11901. }
  11902. return program;
  11903. }
  11904. function releaseProgram( program ) {
  11905. if ( -- program.usedTimes === 0 ) {
  11906. // Remove from unordered set
  11907. const i = programs.indexOf( program );
  11908. programs[ i ] = programs[ programs.length - 1 ];
  11909. programs.pop();
  11910. // Free WebGL resources
  11911. program.destroy();
  11912. }
  11913. }
  11914. function releaseShaderCache( material ) {
  11915. _customShaders.remove( material );
  11916. }
  11917. function dispose() {
  11918. _customShaders.dispose();
  11919. }
  11920. return {
  11921. getParameters: getParameters,
  11922. getProgramCacheKey: getProgramCacheKey,
  11923. getUniforms: getUniforms,
  11924. acquireProgram: acquireProgram,
  11925. releaseProgram: releaseProgram,
  11926. releaseShaderCache: releaseShaderCache,
  11927. // Exposed for resource monitoring & error feedback via renderer.info:
  11928. programs: programs,
  11929. dispose: dispose
  11930. };
  11931. }
  11932. function WebGLProperties() {
  11933. let properties = new WeakMap();
  11934. function get( object ) {
  11935. let map = properties.get( object );
  11936. if ( map === undefined ) {
  11937. map = {};
  11938. properties.set( object, map );
  11939. }
  11940. return map;
  11941. }
  11942. function remove( object ) {
  11943. properties.delete( object );
  11944. }
  11945. function update( object, key, value ) {
  11946. properties.get( object )[ key ] = value;
  11947. }
  11948. function dispose() {
  11949. properties = new WeakMap();
  11950. }
  11951. return {
  11952. get: get,
  11953. remove: remove,
  11954. update: update,
  11955. dispose: dispose
  11956. };
  11957. }
  11958. function painterSortStable( a, b ) {
  11959. if ( a.groupOrder !== b.groupOrder ) {
  11960. return a.groupOrder - b.groupOrder;
  11961. } else if ( a.renderOrder !== b.renderOrder ) {
  11962. return a.renderOrder - b.renderOrder;
  11963. } else if ( a.material.id !== b.material.id ) {
  11964. return a.material.id - b.material.id;
  11965. } else if ( a.z !== b.z ) {
  11966. return a.z - b.z;
  11967. } else {
  11968. return a.id - b.id;
  11969. }
  11970. }
  11971. function reversePainterSortStable( a, b ) {
  11972. if ( a.groupOrder !== b.groupOrder ) {
  11973. return a.groupOrder - b.groupOrder;
  11974. } else if ( a.renderOrder !== b.renderOrder ) {
  11975. return a.renderOrder - b.renderOrder;
  11976. } else if ( a.z !== b.z ) {
  11977. return b.z - a.z;
  11978. } else {
  11979. return a.id - b.id;
  11980. }
  11981. }
  11982. function WebGLRenderList() {
  11983. const renderItems = [];
  11984. let renderItemsIndex = 0;
  11985. const opaque = [];
  11986. const transmissive = [];
  11987. const transparent = [];
  11988. function init() {
  11989. renderItemsIndex = 0;
  11990. opaque.length = 0;
  11991. transmissive.length = 0;
  11992. transparent.length = 0;
  11993. }
  11994. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11995. let renderItem = renderItems[ renderItemsIndex ];
  11996. if ( renderItem === undefined ) {
  11997. renderItem = {
  11998. id: object.id,
  11999. object: object,
  12000. geometry: geometry,
  12001. material: material,
  12002. groupOrder: groupOrder,
  12003. renderOrder: object.renderOrder,
  12004. z: z,
  12005. group: group
  12006. };
  12007. renderItems[ renderItemsIndex ] = renderItem;
  12008. } else {
  12009. renderItem.id = object.id;
  12010. renderItem.object = object;
  12011. renderItem.geometry = geometry;
  12012. renderItem.material = material;
  12013. renderItem.groupOrder = groupOrder;
  12014. renderItem.renderOrder = object.renderOrder;
  12015. renderItem.z = z;
  12016. renderItem.group = group;
  12017. }
  12018. renderItemsIndex ++;
  12019. return renderItem;
  12020. }
  12021. function push( object, geometry, material, groupOrder, z, group ) {
  12022. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12023. if ( material.transmission > 0.0 ) {
  12024. transmissive.push( renderItem );
  12025. } else if ( material.transparent === true ) {
  12026. transparent.push( renderItem );
  12027. } else {
  12028. opaque.push( renderItem );
  12029. }
  12030. }
  12031. function unshift( object, geometry, material, groupOrder, z, group ) {
  12032. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12033. if ( material.transmission > 0.0 ) {
  12034. transmissive.unshift( renderItem );
  12035. } else if ( material.transparent === true ) {
  12036. transparent.unshift( renderItem );
  12037. } else {
  12038. opaque.unshift( renderItem );
  12039. }
  12040. }
  12041. function sort( customOpaqueSort, customTransparentSort ) {
  12042. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12043. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12044. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12045. }
  12046. function finish() {
  12047. // Clear references from inactive renderItems in the list
  12048. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12049. const renderItem = renderItems[ i ];
  12050. if ( renderItem.id === null ) break;
  12051. renderItem.id = null;
  12052. renderItem.object = null;
  12053. renderItem.geometry = null;
  12054. renderItem.material = null;
  12055. renderItem.group = null;
  12056. }
  12057. }
  12058. return {
  12059. opaque: opaque,
  12060. transmissive: transmissive,
  12061. transparent: transparent,
  12062. init: init,
  12063. push: push,
  12064. unshift: unshift,
  12065. finish: finish,
  12066. sort: sort
  12067. };
  12068. }
  12069. function WebGLRenderLists() {
  12070. let lists = new WeakMap();
  12071. function get( scene, renderCallDepth ) {
  12072. const listArray = lists.get( scene );
  12073. let list;
  12074. if ( listArray === undefined ) {
  12075. list = new WebGLRenderList();
  12076. lists.set( scene, [ list ] );
  12077. } else {
  12078. if ( renderCallDepth >= listArray.length ) {
  12079. list = new WebGLRenderList();
  12080. listArray.push( list );
  12081. } else {
  12082. list = listArray[ renderCallDepth ];
  12083. }
  12084. }
  12085. return list;
  12086. }
  12087. function dispose() {
  12088. lists = new WeakMap();
  12089. }
  12090. return {
  12091. get: get,
  12092. dispose: dispose
  12093. };
  12094. }
  12095. function UniformsCache() {
  12096. const lights = {};
  12097. return {
  12098. get: function ( light ) {
  12099. if ( lights[ light.id ] !== undefined ) {
  12100. return lights[ light.id ];
  12101. }
  12102. let uniforms;
  12103. switch ( light.type ) {
  12104. case 'DirectionalLight':
  12105. uniforms = {
  12106. direction: new Vector3(),
  12107. color: new Color()
  12108. };
  12109. break;
  12110. case 'SpotLight':
  12111. uniforms = {
  12112. position: new Vector3(),
  12113. direction: new Vector3(),
  12114. color: new Color(),
  12115. distance: 0,
  12116. coneCos: 0,
  12117. penumbraCos: 0,
  12118. decay: 0
  12119. };
  12120. break;
  12121. case 'PointLight':
  12122. uniforms = {
  12123. position: new Vector3(),
  12124. color: new Color(),
  12125. distance: 0,
  12126. decay: 0
  12127. };
  12128. break;
  12129. case 'HemisphereLight':
  12130. uniforms = {
  12131. direction: new Vector3(),
  12132. skyColor: new Color(),
  12133. groundColor: new Color()
  12134. };
  12135. break;
  12136. case 'RectAreaLight':
  12137. uniforms = {
  12138. color: new Color(),
  12139. position: new Vector3(),
  12140. halfWidth: new Vector3(),
  12141. halfHeight: new Vector3()
  12142. };
  12143. break;
  12144. }
  12145. lights[ light.id ] = uniforms;
  12146. return uniforms;
  12147. }
  12148. };
  12149. }
  12150. function ShadowUniformsCache() {
  12151. const lights = {};
  12152. return {
  12153. get: function ( light ) {
  12154. if ( lights[ light.id ] !== undefined ) {
  12155. return lights[ light.id ];
  12156. }
  12157. let uniforms;
  12158. switch ( light.type ) {
  12159. case 'DirectionalLight':
  12160. uniforms = {
  12161. shadowBias: 0,
  12162. shadowNormalBias: 0,
  12163. shadowRadius: 1,
  12164. shadowMapSize: new Vector2()
  12165. };
  12166. break;
  12167. case 'SpotLight':
  12168. uniforms = {
  12169. shadowBias: 0,
  12170. shadowNormalBias: 0,
  12171. shadowRadius: 1,
  12172. shadowMapSize: new Vector2()
  12173. };
  12174. break;
  12175. case 'PointLight':
  12176. uniforms = {
  12177. shadowBias: 0,
  12178. shadowNormalBias: 0,
  12179. shadowRadius: 1,
  12180. shadowMapSize: new Vector2(),
  12181. shadowCameraNear: 1,
  12182. shadowCameraFar: 1000
  12183. };
  12184. break;
  12185. // TODO (abelnation): set RectAreaLight shadow uniforms
  12186. }
  12187. lights[ light.id ] = uniforms;
  12188. return uniforms;
  12189. }
  12190. };
  12191. }
  12192. let nextVersion = 0;
  12193. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12194. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12195. }
  12196. function WebGLLights( extensions, capabilities ) {
  12197. const cache = new UniformsCache();
  12198. const shadowCache = ShadowUniformsCache();
  12199. const state = {
  12200. version: 0,
  12201. hash: {
  12202. directionalLength: - 1,
  12203. pointLength: - 1,
  12204. spotLength: - 1,
  12205. rectAreaLength: - 1,
  12206. hemiLength: - 1,
  12207. numDirectionalShadows: - 1,
  12208. numPointShadows: - 1,
  12209. numSpotShadows: - 1,
  12210. numSpotMaps: - 1
  12211. },
  12212. ambient: [ 0, 0, 0 ],
  12213. probe: [],
  12214. directional: [],
  12215. directionalShadow: [],
  12216. directionalShadowMap: [],
  12217. directionalShadowMatrix: [],
  12218. spot: [],
  12219. spotLightMap: [],
  12220. spotShadow: [],
  12221. spotShadowMap: [],
  12222. spotLightMatrix: [],
  12223. rectArea: [],
  12224. rectAreaLTC1: null,
  12225. rectAreaLTC2: null,
  12226. point: [],
  12227. pointShadow: [],
  12228. pointShadowMap: [],
  12229. pointShadowMatrix: [],
  12230. hemi: [],
  12231. numSpotLightShadowsWithMaps: 0
  12232. };
  12233. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12234. const vector3 = new Vector3();
  12235. const matrix4 = new Matrix4();
  12236. const matrix42 = new Matrix4();
  12237. function setup( lights, physicallyCorrectLights ) {
  12238. let r = 0, g = 0, b = 0;
  12239. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12240. let directionalLength = 0;
  12241. let pointLength = 0;
  12242. let spotLength = 0;
  12243. let rectAreaLength = 0;
  12244. let hemiLength = 0;
  12245. let numDirectionalShadows = 0;
  12246. let numPointShadows = 0;
  12247. let numSpotShadows = 0;
  12248. let numSpotMaps = 0;
  12249. let numSpotShadowsWithMaps = 0;
  12250. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12251. lights.sort( shadowCastingAndTexturingLightsFirst );
  12252. // artist-friendly light intensity scaling factor
  12253. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12254. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12255. const light = lights[ i ];
  12256. const color = light.color;
  12257. const intensity = light.intensity;
  12258. const distance = light.distance;
  12259. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12260. if ( light.isAmbientLight ) {
  12261. r += color.r * intensity * scaleFactor;
  12262. g += color.g * intensity * scaleFactor;
  12263. b += color.b * intensity * scaleFactor;
  12264. } else if ( light.isLightProbe ) {
  12265. for ( let j = 0; j < 9; j ++ ) {
  12266. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12267. }
  12268. } else if ( light.isDirectionalLight ) {
  12269. const uniforms = cache.get( light );
  12270. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12271. if ( light.castShadow ) {
  12272. const shadow = light.shadow;
  12273. const shadowUniforms = shadowCache.get( light );
  12274. shadowUniforms.shadowBias = shadow.bias;
  12275. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12276. shadowUniforms.shadowRadius = shadow.radius;
  12277. shadowUniforms.shadowMapSize = shadow.mapSize;
  12278. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12279. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12280. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12281. numDirectionalShadows ++;
  12282. }
  12283. state.directional[ directionalLength ] = uniforms;
  12284. directionalLength ++;
  12285. } else if ( light.isSpotLight ) {
  12286. const uniforms = cache.get( light );
  12287. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12288. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12289. uniforms.distance = distance;
  12290. uniforms.coneCos = Math.cos( light.angle );
  12291. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12292. uniforms.decay = light.decay;
  12293. state.spot[ spotLength ] = uniforms;
  12294. const shadow = light.shadow;
  12295. if ( light.map ) {
  12296. state.spotLightMap[ numSpotMaps ] = light.map;
  12297. numSpotMaps ++;
  12298. // make sure the lightMatrix is up to date
  12299. // TODO : do it if required only
  12300. shadow.updateMatrices( light );
  12301. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12302. }
  12303. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12304. if ( light.castShadow ) {
  12305. const shadowUniforms = shadowCache.get( light );
  12306. shadowUniforms.shadowBias = shadow.bias;
  12307. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12308. shadowUniforms.shadowRadius = shadow.radius;
  12309. shadowUniforms.shadowMapSize = shadow.mapSize;
  12310. state.spotShadow[ spotLength ] = shadowUniforms;
  12311. state.spotShadowMap[ spotLength ] = shadowMap;
  12312. numSpotShadows ++;
  12313. }
  12314. spotLength ++;
  12315. } else if ( light.isRectAreaLight ) {
  12316. const uniforms = cache.get( light );
  12317. uniforms.color.copy( color ).multiplyScalar( intensity );
  12318. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12319. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12320. state.rectArea[ rectAreaLength ] = uniforms;
  12321. rectAreaLength ++;
  12322. } else if ( light.isPointLight ) {
  12323. const uniforms = cache.get( light );
  12324. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12325. uniforms.distance = light.distance;
  12326. uniforms.decay = light.decay;
  12327. if ( light.castShadow ) {
  12328. const shadow = light.shadow;
  12329. const shadowUniforms = shadowCache.get( light );
  12330. shadowUniforms.shadowBias = shadow.bias;
  12331. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12332. shadowUniforms.shadowRadius = shadow.radius;
  12333. shadowUniforms.shadowMapSize = shadow.mapSize;
  12334. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12335. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12336. state.pointShadow[ pointLength ] = shadowUniforms;
  12337. state.pointShadowMap[ pointLength ] = shadowMap;
  12338. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12339. numPointShadows ++;
  12340. }
  12341. state.point[ pointLength ] = uniforms;
  12342. pointLength ++;
  12343. } else if ( light.isHemisphereLight ) {
  12344. const uniforms = cache.get( light );
  12345. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12346. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12347. state.hemi[ hemiLength ] = uniforms;
  12348. hemiLength ++;
  12349. }
  12350. }
  12351. if ( rectAreaLength > 0 ) {
  12352. if ( capabilities.isWebGL2 ) {
  12353. // WebGL 2
  12354. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12355. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12356. } else {
  12357. // WebGL 1
  12358. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12359. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12360. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12361. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12362. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12363. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12364. } else {
  12365. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12366. }
  12367. }
  12368. }
  12369. state.ambient[ 0 ] = r;
  12370. state.ambient[ 1 ] = g;
  12371. state.ambient[ 2 ] = b;
  12372. const hash = state.hash;
  12373. if ( hash.directionalLength !== directionalLength ||
  12374. hash.pointLength !== pointLength ||
  12375. hash.spotLength !== spotLength ||
  12376. hash.rectAreaLength !== rectAreaLength ||
  12377. hash.hemiLength !== hemiLength ||
  12378. hash.numDirectionalShadows !== numDirectionalShadows ||
  12379. hash.numPointShadows !== numPointShadows ||
  12380. hash.numSpotShadows !== numSpotShadows ||
  12381. hash.numSpotMaps !== numSpotMaps ) {
  12382. state.directional.length = directionalLength;
  12383. state.spot.length = spotLength;
  12384. state.rectArea.length = rectAreaLength;
  12385. state.point.length = pointLength;
  12386. state.hemi.length = hemiLength;
  12387. state.directionalShadow.length = numDirectionalShadows;
  12388. state.directionalShadowMap.length = numDirectionalShadows;
  12389. state.pointShadow.length = numPointShadows;
  12390. state.pointShadowMap.length = numPointShadows;
  12391. state.spotShadow.length = numSpotShadows;
  12392. state.spotShadowMap.length = numSpotShadows;
  12393. state.directionalShadowMatrix.length = numDirectionalShadows;
  12394. state.pointShadowMatrix.length = numPointShadows;
  12395. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12396. state.spotLightMap.length = numSpotMaps;
  12397. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12398. hash.directionalLength = directionalLength;
  12399. hash.pointLength = pointLength;
  12400. hash.spotLength = spotLength;
  12401. hash.rectAreaLength = rectAreaLength;
  12402. hash.hemiLength = hemiLength;
  12403. hash.numDirectionalShadows = numDirectionalShadows;
  12404. hash.numPointShadows = numPointShadows;
  12405. hash.numSpotShadows = numSpotShadows;
  12406. hash.numSpotMaps = numSpotMaps;
  12407. state.version = nextVersion ++;
  12408. }
  12409. }
  12410. function setupView( lights, camera ) {
  12411. let directionalLength = 0;
  12412. let pointLength = 0;
  12413. let spotLength = 0;
  12414. let rectAreaLength = 0;
  12415. let hemiLength = 0;
  12416. const viewMatrix = camera.matrixWorldInverse;
  12417. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12418. const light = lights[ i ];
  12419. if ( light.isDirectionalLight ) {
  12420. const uniforms = state.directional[ directionalLength ];
  12421. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12422. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12423. uniforms.direction.sub( vector3 );
  12424. uniforms.direction.transformDirection( viewMatrix );
  12425. directionalLength ++;
  12426. } else if ( light.isSpotLight ) {
  12427. const uniforms = state.spot[ spotLength ];
  12428. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12429. uniforms.position.applyMatrix4( viewMatrix );
  12430. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12431. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12432. uniforms.direction.sub( vector3 );
  12433. uniforms.direction.transformDirection( viewMatrix );
  12434. spotLength ++;
  12435. } else if ( light.isRectAreaLight ) {
  12436. const uniforms = state.rectArea[ rectAreaLength ];
  12437. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12438. uniforms.position.applyMatrix4( viewMatrix );
  12439. // extract local rotation of light to derive width/height half vectors
  12440. matrix42.identity();
  12441. matrix4.copy( light.matrixWorld );
  12442. matrix4.premultiply( viewMatrix );
  12443. matrix42.extractRotation( matrix4 );
  12444. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12445. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12446. uniforms.halfWidth.applyMatrix4( matrix42 );
  12447. uniforms.halfHeight.applyMatrix4( matrix42 );
  12448. rectAreaLength ++;
  12449. } else if ( light.isPointLight ) {
  12450. const uniforms = state.point[ pointLength ];
  12451. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12452. uniforms.position.applyMatrix4( viewMatrix );
  12453. pointLength ++;
  12454. } else if ( light.isHemisphereLight ) {
  12455. const uniforms = state.hemi[ hemiLength ];
  12456. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12457. uniforms.direction.transformDirection( viewMatrix );
  12458. hemiLength ++;
  12459. }
  12460. }
  12461. }
  12462. return {
  12463. setup: setup,
  12464. setupView: setupView,
  12465. state: state
  12466. };
  12467. }
  12468. function WebGLRenderState( extensions, capabilities ) {
  12469. const lights = new WebGLLights( extensions, capabilities );
  12470. const lightsArray = [];
  12471. const shadowsArray = [];
  12472. function init() {
  12473. lightsArray.length = 0;
  12474. shadowsArray.length = 0;
  12475. }
  12476. function pushLight( light ) {
  12477. lightsArray.push( light );
  12478. }
  12479. function pushShadow( shadowLight ) {
  12480. shadowsArray.push( shadowLight );
  12481. }
  12482. function setupLights( physicallyCorrectLights ) {
  12483. lights.setup( lightsArray, physicallyCorrectLights );
  12484. }
  12485. function setupLightsView( camera ) {
  12486. lights.setupView( lightsArray, camera );
  12487. }
  12488. const state = {
  12489. lightsArray: lightsArray,
  12490. shadowsArray: shadowsArray,
  12491. lights: lights
  12492. };
  12493. return {
  12494. init: init,
  12495. state: state,
  12496. setupLights: setupLights,
  12497. setupLightsView: setupLightsView,
  12498. pushLight: pushLight,
  12499. pushShadow: pushShadow
  12500. };
  12501. }
  12502. function WebGLRenderStates( extensions, capabilities ) {
  12503. let renderStates = new WeakMap();
  12504. function get( scene, renderCallDepth = 0 ) {
  12505. const renderStateArray = renderStates.get( scene );
  12506. let renderState;
  12507. if ( renderStateArray === undefined ) {
  12508. renderState = new WebGLRenderState( extensions, capabilities );
  12509. renderStates.set( scene, [ renderState ] );
  12510. } else {
  12511. if ( renderCallDepth >= renderStateArray.length ) {
  12512. renderState = new WebGLRenderState( extensions, capabilities );
  12513. renderStateArray.push( renderState );
  12514. } else {
  12515. renderState = renderStateArray[ renderCallDepth ];
  12516. }
  12517. }
  12518. return renderState;
  12519. }
  12520. function dispose() {
  12521. renderStates = new WeakMap();
  12522. }
  12523. return {
  12524. get: get,
  12525. dispose: dispose
  12526. };
  12527. }
  12528. class MeshDepthMaterial extends Material {
  12529. constructor( parameters ) {
  12530. super();
  12531. this.isMeshDepthMaterial = true;
  12532. this.type = 'MeshDepthMaterial';
  12533. this.depthPacking = BasicDepthPacking;
  12534. this.map = null;
  12535. this.alphaMap = null;
  12536. this.displacementMap = null;
  12537. this.displacementScale = 1;
  12538. this.displacementBias = 0;
  12539. this.wireframe = false;
  12540. this.wireframeLinewidth = 1;
  12541. this.setValues( parameters );
  12542. }
  12543. copy( source ) {
  12544. super.copy( source );
  12545. this.depthPacking = source.depthPacking;
  12546. this.map = source.map;
  12547. this.alphaMap = source.alphaMap;
  12548. this.displacementMap = source.displacementMap;
  12549. this.displacementScale = source.displacementScale;
  12550. this.displacementBias = source.displacementBias;
  12551. this.wireframe = source.wireframe;
  12552. this.wireframeLinewidth = source.wireframeLinewidth;
  12553. return this;
  12554. }
  12555. }
  12556. class MeshDistanceMaterial extends Material {
  12557. constructor( parameters ) {
  12558. super();
  12559. this.isMeshDistanceMaterial = true;
  12560. this.type = 'MeshDistanceMaterial';
  12561. this.referencePosition = new Vector3();
  12562. this.nearDistance = 1;
  12563. this.farDistance = 1000;
  12564. this.map = null;
  12565. this.alphaMap = null;
  12566. this.displacementMap = null;
  12567. this.displacementScale = 1;
  12568. this.displacementBias = 0;
  12569. this.setValues( parameters );
  12570. }
  12571. copy( source ) {
  12572. super.copy( source );
  12573. this.referencePosition.copy( source.referencePosition );
  12574. this.nearDistance = source.nearDistance;
  12575. this.farDistance = source.farDistance;
  12576. this.map = source.map;
  12577. this.alphaMap = source.alphaMap;
  12578. this.displacementMap = source.displacementMap;
  12579. this.displacementScale = source.displacementScale;
  12580. this.displacementBias = source.displacementBias;
  12581. return this;
  12582. }
  12583. }
  12584. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12585. 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}";
  12586. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12587. let _frustum = new Frustum();
  12588. const _shadowMapSize = new Vector2(),
  12589. _viewportSize = new Vector2(),
  12590. _viewport = new Vector4(),
  12591. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12592. _distanceMaterial = new MeshDistanceMaterial(),
  12593. _materialCache = {},
  12594. _maxTextureSize = _capabilities.maxTextureSize;
  12595. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12596. const shadowMaterialVertical = new ShaderMaterial( {
  12597. defines: {
  12598. VSM_SAMPLES: 8
  12599. },
  12600. uniforms: {
  12601. shadow_pass: { value: null },
  12602. resolution: { value: new Vector2() },
  12603. radius: { value: 4.0 }
  12604. },
  12605. vertexShader: vertex,
  12606. fragmentShader: fragment
  12607. } );
  12608. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12609. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12610. const fullScreenTri = new BufferGeometry();
  12611. fullScreenTri.setAttribute(
  12612. 'position',
  12613. new BufferAttribute(
  12614. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12615. 3
  12616. )
  12617. );
  12618. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12619. const scope = this;
  12620. this.enabled = false;
  12621. this.autoUpdate = true;
  12622. this.needsUpdate = false;
  12623. this.type = PCFShadowMap;
  12624. this.render = function ( lights, scene, camera ) {
  12625. if ( scope.enabled === false ) return;
  12626. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12627. if ( lights.length === 0 ) return;
  12628. const currentRenderTarget = _renderer.getRenderTarget();
  12629. const activeCubeFace = _renderer.getActiveCubeFace();
  12630. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12631. const _state = _renderer.state;
  12632. // Set GL state for depth map.
  12633. _state.setBlending( NoBlending );
  12634. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12635. _state.buffers.depth.setTest( true );
  12636. _state.setScissorTest( false );
  12637. // render depth map
  12638. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12639. const light = lights[ i ];
  12640. const shadow = light.shadow;
  12641. if ( shadow === undefined ) {
  12642. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12643. continue;
  12644. }
  12645. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12646. _shadowMapSize.copy( shadow.mapSize );
  12647. const shadowFrameExtents = shadow.getFrameExtents();
  12648. _shadowMapSize.multiply( shadowFrameExtents );
  12649. _viewportSize.copy( shadow.mapSize );
  12650. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12651. if ( _shadowMapSize.x > _maxTextureSize ) {
  12652. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12653. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12654. shadow.mapSize.x = _viewportSize.x;
  12655. }
  12656. if ( _shadowMapSize.y > _maxTextureSize ) {
  12657. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12658. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12659. shadow.mapSize.y = _viewportSize.y;
  12660. }
  12661. }
  12662. if ( shadow.map === null ) {
  12663. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12664. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12665. shadow.map.texture.name = light.name + '.shadowMap';
  12666. shadow.camera.updateProjectionMatrix();
  12667. }
  12668. _renderer.setRenderTarget( shadow.map );
  12669. _renderer.clear();
  12670. const viewportCount = shadow.getViewportCount();
  12671. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12672. const viewport = shadow.getViewport( vp );
  12673. _viewport.set(
  12674. _viewportSize.x * viewport.x,
  12675. _viewportSize.y * viewport.y,
  12676. _viewportSize.x * viewport.z,
  12677. _viewportSize.y * viewport.w
  12678. );
  12679. _state.viewport( _viewport );
  12680. shadow.updateMatrices( light, vp );
  12681. _frustum = shadow.getFrustum();
  12682. renderObject( scene, camera, shadow.camera, light, this.type );
  12683. }
  12684. // do blur pass for VSM
  12685. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12686. VSMPass( shadow, camera );
  12687. }
  12688. shadow.needsUpdate = false;
  12689. }
  12690. scope.needsUpdate = false;
  12691. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12692. };
  12693. function VSMPass( shadow, camera ) {
  12694. const geometry = _objects.update( fullScreenMesh );
  12695. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12696. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12697. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12698. shadowMaterialVertical.needsUpdate = true;
  12699. shadowMaterialHorizontal.needsUpdate = true;
  12700. }
  12701. if ( shadow.mapPass === null ) {
  12702. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12703. }
  12704. // vertical pass
  12705. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12706. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12707. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12708. _renderer.setRenderTarget( shadow.mapPass );
  12709. _renderer.clear();
  12710. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12711. // horizontal pass
  12712. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12713. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12714. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12715. _renderer.setRenderTarget( shadow.map );
  12716. _renderer.clear();
  12717. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12718. }
  12719. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12720. let result = null;
  12721. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12722. if ( customMaterial !== undefined ) {
  12723. result = customMaterial;
  12724. } else {
  12725. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12726. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12727. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12728. ( material.alphaMap && material.alphaTest > 0 ) ||
  12729. ( material.map && material.alphaTest > 0 ) ) {
  12730. // in this case we need a unique material instance reflecting the
  12731. // appropriate state
  12732. const keyA = result.uuid, keyB = material.uuid;
  12733. let materialsForVariant = _materialCache[ keyA ];
  12734. if ( materialsForVariant === undefined ) {
  12735. materialsForVariant = {};
  12736. _materialCache[ keyA ] = materialsForVariant;
  12737. }
  12738. let cachedMaterial = materialsForVariant[ keyB ];
  12739. if ( cachedMaterial === undefined ) {
  12740. cachedMaterial = result.clone();
  12741. materialsForVariant[ keyB ] = cachedMaterial;
  12742. }
  12743. result = cachedMaterial;
  12744. }
  12745. }
  12746. result.visible = material.visible;
  12747. result.wireframe = material.wireframe;
  12748. if ( type === VSMShadowMap ) {
  12749. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12750. } else {
  12751. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12752. }
  12753. result.alphaMap = material.alphaMap;
  12754. result.alphaTest = material.alphaTest;
  12755. result.map = material.map;
  12756. result.clipShadows = material.clipShadows;
  12757. result.clippingPlanes = material.clippingPlanes;
  12758. result.clipIntersection = material.clipIntersection;
  12759. result.displacementMap = material.displacementMap;
  12760. result.displacementScale = material.displacementScale;
  12761. result.displacementBias = material.displacementBias;
  12762. result.wireframeLinewidth = material.wireframeLinewidth;
  12763. result.linewidth = material.linewidth;
  12764. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12765. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12766. result.nearDistance = shadowCameraNear;
  12767. result.farDistance = shadowCameraFar;
  12768. }
  12769. return result;
  12770. }
  12771. function renderObject( object, camera, shadowCamera, light, type ) {
  12772. if ( object.visible === false ) return;
  12773. const visible = object.layers.test( camera.layers );
  12774. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12775. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12776. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12777. const geometry = _objects.update( object );
  12778. const material = object.material;
  12779. if ( Array.isArray( material ) ) {
  12780. const groups = geometry.groups;
  12781. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12782. const group = groups[ k ];
  12783. const groupMaterial = material[ group.materialIndex ];
  12784. if ( groupMaterial && groupMaterial.visible ) {
  12785. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12786. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12787. }
  12788. }
  12789. } else if ( material.visible ) {
  12790. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12791. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12792. }
  12793. }
  12794. }
  12795. const children = object.children;
  12796. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12797. renderObject( children[ i ], camera, shadowCamera, light, type );
  12798. }
  12799. }
  12800. }
  12801. function WebGLState( gl, extensions, capabilities ) {
  12802. const isWebGL2 = capabilities.isWebGL2;
  12803. function ColorBuffer() {
  12804. let locked = false;
  12805. const color = new Vector4();
  12806. let currentColorMask = null;
  12807. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12808. return {
  12809. setMask: function ( colorMask ) {
  12810. if ( currentColorMask !== colorMask && ! locked ) {
  12811. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12812. currentColorMask = colorMask;
  12813. }
  12814. },
  12815. setLocked: function ( lock ) {
  12816. locked = lock;
  12817. },
  12818. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12819. if ( premultipliedAlpha === true ) {
  12820. r *= a; g *= a; b *= a;
  12821. }
  12822. color.set( r, g, b, a );
  12823. if ( currentColorClear.equals( color ) === false ) {
  12824. gl.clearColor( r, g, b, a );
  12825. currentColorClear.copy( color );
  12826. }
  12827. },
  12828. reset: function () {
  12829. locked = false;
  12830. currentColorMask = null;
  12831. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12832. }
  12833. };
  12834. }
  12835. function DepthBuffer() {
  12836. let locked = false;
  12837. let currentDepthMask = null;
  12838. let currentDepthFunc = null;
  12839. let currentDepthClear = null;
  12840. return {
  12841. setTest: function ( depthTest ) {
  12842. if ( depthTest ) {
  12843. enable( gl.DEPTH_TEST );
  12844. } else {
  12845. disable( gl.DEPTH_TEST );
  12846. }
  12847. },
  12848. setMask: function ( depthMask ) {
  12849. if ( currentDepthMask !== depthMask && ! locked ) {
  12850. gl.depthMask( depthMask );
  12851. currentDepthMask = depthMask;
  12852. }
  12853. },
  12854. setFunc: function ( depthFunc ) {
  12855. if ( currentDepthFunc !== depthFunc ) {
  12856. switch ( depthFunc ) {
  12857. case NeverDepth:
  12858. gl.depthFunc( gl.NEVER );
  12859. break;
  12860. case AlwaysDepth:
  12861. gl.depthFunc( gl.ALWAYS );
  12862. break;
  12863. case LessDepth:
  12864. gl.depthFunc( gl.LESS );
  12865. break;
  12866. case LessEqualDepth:
  12867. gl.depthFunc( gl.LEQUAL );
  12868. break;
  12869. case EqualDepth:
  12870. gl.depthFunc( gl.EQUAL );
  12871. break;
  12872. case GreaterEqualDepth:
  12873. gl.depthFunc( gl.GEQUAL );
  12874. break;
  12875. case GreaterDepth:
  12876. gl.depthFunc( gl.GREATER );
  12877. break;
  12878. case NotEqualDepth:
  12879. gl.depthFunc( gl.NOTEQUAL );
  12880. break;
  12881. default:
  12882. gl.depthFunc( gl.LEQUAL );
  12883. }
  12884. currentDepthFunc = depthFunc;
  12885. }
  12886. },
  12887. setLocked: function ( lock ) {
  12888. locked = lock;
  12889. },
  12890. setClear: function ( depth ) {
  12891. if ( currentDepthClear !== depth ) {
  12892. gl.clearDepth( depth );
  12893. currentDepthClear = depth;
  12894. }
  12895. },
  12896. reset: function () {
  12897. locked = false;
  12898. currentDepthMask = null;
  12899. currentDepthFunc = null;
  12900. currentDepthClear = null;
  12901. }
  12902. };
  12903. }
  12904. function StencilBuffer() {
  12905. let locked = false;
  12906. let currentStencilMask = null;
  12907. let currentStencilFunc = null;
  12908. let currentStencilRef = null;
  12909. let currentStencilFuncMask = null;
  12910. let currentStencilFail = null;
  12911. let currentStencilZFail = null;
  12912. let currentStencilZPass = null;
  12913. let currentStencilClear = null;
  12914. return {
  12915. setTest: function ( stencilTest ) {
  12916. if ( ! locked ) {
  12917. if ( stencilTest ) {
  12918. enable( gl.STENCIL_TEST );
  12919. } else {
  12920. disable( gl.STENCIL_TEST );
  12921. }
  12922. }
  12923. },
  12924. setMask: function ( stencilMask ) {
  12925. if ( currentStencilMask !== stencilMask && ! locked ) {
  12926. gl.stencilMask( stencilMask );
  12927. currentStencilMask = stencilMask;
  12928. }
  12929. },
  12930. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12931. if ( currentStencilFunc !== stencilFunc ||
  12932. currentStencilRef !== stencilRef ||
  12933. currentStencilFuncMask !== stencilMask ) {
  12934. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12935. currentStencilFunc = stencilFunc;
  12936. currentStencilRef = stencilRef;
  12937. currentStencilFuncMask = stencilMask;
  12938. }
  12939. },
  12940. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12941. if ( currentStencilFail !== stencilFail ||
  12942. currentStencilZFail !== stencilZFail ||
  12943. currentStencilZPass !== stencilZPass ) {
  12944. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12945. currentStencilFail = stencilFail;
  12946. currentStencilZFail = stencilZFail;
  12947. currentStencilZPass = stencilZPass;
  12948. }
  12949. },
  12950. setLocked: function ( lock ) {
  12951. locked = lock;
  12952. },
  12953. setClear: function ( stencil ) {
  12954. if ( currentStencilClear !== stencil ) {
  12955. gl.clearStencil( stencil );
  12956. currentStencilClear = stencil;
  12957. }
  12958. },
  12959. reset: function () {
  12960. locked = false;
  12961. currentStencilMask = null;
  12962. currentStencilFunc = null;
  12963. currentStencilRef = null;
  12964. currentStencilFuncMask = null;
  12965. currentStencilFail = null;
  12966. currentStencilZFail = null;
  12967. currentStencilZPass = null;
  12968. currentStencilClear = null;
  12969. }
  12970. };
  12971. }
  12972. //
  12973. const colorBuffer = new ColorBuffer();
  12974. const depthBuffer = new DepthBuffer();
  12975. const stencilBuffer = new StencilBuffer();
  12976. const uboBindings = new WeakMap();
  12977. const uboProgramMap = new WeakMap();
  12978. let enabledCapabilities = {};
  12979. let currentBoundFramebuffers = {};
  12980. let currentDrawbuffers = new WeakMap();
  12981. let defaultDrawbuffers = [];
  12982. let currentProgram = null;
  12983. let currentBlendingEnabled = false;
  12984. let currentBlending = null;
  12985. let currentBlendEquation = null;
  12986. let currentBlendSrc = null;
  12987. let currentBlendDst = null;
  12988. let currentBlendEquationAlpha = null;
  12989. let currentBlendSrcAlpha = null;
  12990. let currentBlendDstAlpha = null;
  12991. let currentPremultipledAlpha = false;
  12992. let currentFlipSided = null;
  12993. let currentCullFace = null;
  12994. let currentLineWidth = null;
  12995. let currentPolygonOffsetFactor = null;
  12996. let currentPolygonOffsetUnits = null;
  12997. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  12998. let lineWidthAvailable = false;
  12999. let version = 0;
  13000. const glVersion = gl.getParameter( gl.VERSION );
  13001. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13002. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13003. lineWidthAvailable = ( version >= 1.0 );
  13004. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13005. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13006. lineWidthAvailable = ( version >= 2.0 );
  13007. }
  13008. let currentTextureSlot = null;
  13009. let currentBoundTextures = {};
  13010. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13011. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13012. const currentScissor = new Vector4().fromArray( scissorParam );
  13013. const currentViewport = new Vector4().fromArray( viewportParam );
  13014. function createTexture( type, target, count ) {
  13015. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13016. const texture = gl.createTexture();
  13017. gl.bindTexture( type, texture );
  13018. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13019. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13020. for ( let i = 0; i < count; i ++ ) {
  13021. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13022. }
  13023. return texture;
  13024. }
  13025. const emptyTextures = {};
  13026. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13027. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13028. // init
  13029. colorBuffer.setClear( 0, 0, 0, 1 );
  13030. depthBuffer.setClear( 1 );
  13031. stencilBuffer.setClear( 0 );
  13032. enable( gl.DEPTH_TEST );
  13033. depthBuffer.setFunc( LessEqualDepth );
  13034. setFlipSided( false );
  13035. setCullFace( CullFaceBack );
  13036. enable( gl.CULL_FACE );
  13037. setBlending( NoBlending );
  13038. //
  13039. function enable( id ) {
  13040. if ( enabledCapabilities[ id ] !== true ) {
  13041. gl.enable( id );
  13042. enabledCapabilities[ id ] = true;
  13043. }
  13044. }
  13045. function disable( id ) {
  13046. if ( enabledCapabilities[ id ] !== false ) {
  13047. gl.disable( id );
  13048. enabledCapabilities[ id ] = false;
  13049. }
  13050. }
  13051. function bindFramebuffer( target, framebuffer ) {
  13052. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13053. gl.bindFramebuffer( target, framebuffer );
  13054. currentBoundFramebuffers[ target ] = framebuffer;
  13055. if ( isWebGL2 ) {
  13056. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13057. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13058. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13059. }
  13060. if ( target === gl.FRAMEBUFFER ) {
  13061. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13062. }
  13063. }
  13064. return true;
  13065. }
  13066. return false;
  13067. }
  13068. function drawBuffers( renderTarget, framebuffer ) {
  13069. let drawBuffers = defaultDrawbuffers;
  13070. let needsUpdate = false;
  13071. if ( renderTarget ) {
  13072. drawBuffers = currentDrawbuffers.get( framebuffer );
  13073. if ( drawBuffers === undefined ) {
  13074. drawBuffers = [];
  13075. currentDrawbuffers.set( framebuffer, drawBuffers );
  13076. }
  13077. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13078. const textures = renderTarget.texture;
  13079. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13080. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13081. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13082. }
  13083. drawBuffers.length = textures.length;
  13084. needsUpdate = true;
  13085. }
  13086. } else {
  13087. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13088. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13089. needsUpdate = true;
  13090. }
  13091. }
  13092. } else {
  13093. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13094. drawBuffers[ 0 ] = gl.BACK;
  13095. needsUpdate = true;
  13096. }
  13097. }
  13098. if ( needsUpdate ) {
  13099. if ( capabilities.isWebGL2 ) {
  13100. gl.drawBuffers( drawBuffers );
  13101. } else {
  13102. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13103. }
  13104. }
  13105. }
  13106. function useProgram( program ) {
  13107. if ( currentProgram !== program ) {
  13108. gl.useProgram( program );
  13109. currentProgram = program;
  13110. return true;
  13111. }
  13112. return false;
  13113. }
  13114. const equationToGL = {
  13115. [ AddEquation ]: gl.FUNC_ADD,
  13116. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13117. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13118. };
  13119. if ( isWebGL2 ) {
  13120. equationToGL[ MinEquation ] = gl.MIN;
  13121. equationToGL[ MaxEquation ] = gl.MAX;
  13122. } else {
  13123. const extension = extensions.get( 'EXT_blend_minmax' );
  13124. if ( extension !== null ) {
  13125. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13126. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13127. }
  13128. }
  13129. const factorToGL = {
  13130. [ ZeroFactor ]: gl.ZERO,
  13131. [ OneFactor ]: gl.ONE,
  13132. [ SrcColorFactor ]: gl.SRC_COLOR,
  13133. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13134. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13135. [ DstColorFactor ]: gl.DST_COLOR,
  13136. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13137. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13138. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13139. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13140. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13141. };
  13142. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13143. if ( blending === NoBlending ) {
  13144. if ( currentBlendingEnabled === true ) {
  13145. disable( gl.BLEND );
  13146. currentBlendingEnabled = false;
  13147. }
  13148. return;
  13149. }
  13150. if ( currentBlendingEnabled === false ) {
  13151. enable( gl.BLEND );
  13152. currentBlendingEnabled = true;
  13153. }
  13154. if ( blending !== CustomBlending ) {
  13155. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13156. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13157. gl.blendEquation( gl.FUNC_ADD );
  13158. currentBlendEquation = AddEquation;
  13159. currentBlendEquationAlpha = AddEquation;
  13160. }
  13161. if ( premultipliedAlpha ) {
  13162. switch ( blending ) {
  13163. case NormalBlending:
  13164. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13165. break;
  13166. case AdditiveBlending:
  13167. gl.blendFunc( gl.ONE, gl.ONE );
  13168. break;
  13169. case SubtractiveBlending:
  13170. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13171. break;
  13172. case MultiplyBlending:
  13173. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13174. break;
  13175. default:
  13176. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13177. break;
  13178. }
  13179. } else {
  13180. switch ( blending ) {
  13181. case NormalBlending:
  13182. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13183. break;
  13184. case AdditiveBlending:
  13185. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13186. break;
  13187. case SubtractiveBlending:
  13188. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13189. break;
  13190. case MultiplyBlending:
  13191. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13192. break;
  13193. default:
  13194. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13195. break;
  13196. }
  13197. }
  13198. currentBlendSrc = null;
  13199. currentBlendDst = null;
  13200. currentBlendSrcAlpha = null;
  13201. currentBlendDstAlpha = null;
  13202. currentBlending = blending;
  13203. currentPremultipledAlpha = premultipliedAlpha;
  13204. }
  13205. return;
  13206. }
  13207. // custom blending
  13208. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13209. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13210. blendDstAlpha = blendDstAlpha || blendDst;
  13211. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13212. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13213. currentBlendEquation = blendEquation;
  13214. currentBlendEquationAlpha = blendEquationAlpha;
  13215. }
  13216. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13217. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13218. currentBlendSrc = blendSrc;
  13219. currentBlendDst = blendDst;
  13220. currentBlendSrcAlpha = blendSrcAlpha;
  13221. currentBlendDstAlpha = blendDstAlpha;
  13222. }
  13223. currentBlending = blending;
  13224. currentPremultipledAlpha = false;
  13225. }
  13226. function setMaterial( material, frontFaceCW ) {
  13227. material.side === DoubleSide
  13228. ? disable( gl.CULL_FACE )
  13229. : enable( gl.CULL_FACE );
  13230. let flipSided = ( material.side === BackSide );
  13231. if ( frontFaceCW ) flipSided = ! flipSided;
  13232. setFlipSided( flipSided );
  13233. ( material.blending === NormalBlending && material.transparent === false )
  13234. ? setBlending( NoBlending )
  13235. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13236. depthBuffer.setFunc( material.depthFunc );
  13237. depthBuffer.setTest( material.depthTest );
  13238. depthBuffer.setMask( material.depthWrite );
  13239. colorBuffer.setMask( material.colorWrite );
  13240. const stencilWrite = material.stencilWrite;
  13241. stencilBuffer.setTest( stencilWrite );
  13242. if ( stencilWrite ) {
  13243. stencilBuffer.setMask( material.stencilWriteMask );
  13244. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13245. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13246. }
  13247. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13248. material.alphaToCoverage === true
  13249. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13250. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13251. }
  13252. //
  13253. function setFlipSided( flipSided ) {
  13254. if ( currentFlipSided !== flipSided ) {
  13255. if ( flipSided ) {
  13256. gl.frontFace( gl.CW );
  13257. } else {
  13258. gl.frontFace( gl.CCW );
  13259. }
  13260. currentFlipSided = flipSided;
  13261. }
  13262. }
  13263. function setCullFace( cullFace ) {
  13264. if ( cullFace !== CullFaceNone ) {
  13265. enable( gl.CULL_FACE );
  13266. if ( cullFace !== currentCullFace ) {
  13267. if ( cullFace === CullFaceBack ) {
  13268. gl.cullFace( gl.BACK );
  13269. } else if ( cullFace === CullFaceFront ) {
  13270. gl.cullFace( gl.FRONT );
  13271. } else {
  13272. gl.cullFace( gl.FRONT_AND_BACK );
  13273. }
  13274. }
  13275. } else {
  13276. disable( gl.CULL_FACE );
  13277. }
  13278. currentCullFace = cullFace;
  13279. }
  13280. function setLineWidth( width ) {
  13281. if ( width !== currentLineWidth ) {
  13282. if ( lineWidthAvailable ) gl.lineWidth( width );
  13283. currentLineWidth = width;
  13284. }
  13285. }
  13286. function setPolygonOffset( polygonOffset, factor, units ) {
  13287. if ( polygonOffset ) {
  13288. enable( gl.POLYGON_OFFSET_FILL );
  13289. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13290. gl.polygonOffset( factor, units );
  13291. currentPolygonOffsetFactor = factor;
  13292. currentPolygonOffsetUnits = units;
  13293. }
  13294. } else {
  13295. disable( gl.POLYGON_OFFSET_FILL );
  13296. }
  13297. }
  13298. function setScissorTest( scissorTest ) {
  13299. if ( scissorTest ) {
  13300. enable( gl.SCISSOR_TEST );
  13301. } else {
  13302. disable( gl.SCISSOR_TEST );
  13303. }
  13304. }
  13305. // texture
  13306. function activeTexture( webglSlot ) {
  13307. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13308. if ( currentTextureSlot !== webglSlot ) {
  13309. gl.activeTexture( webglSlot );
  13310. currentTextureSlot = webglSlot;
  13311. }
  13312. }
  13313. function bindTexture( webglType, webglTexture, webglSlot ) {
  13314. if ( webglSlot === undefined ) {
  13315. if ( currentTextureSlot === null ) {
  13316. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13317. } else {
  13318. webglSlot = currentTextureSlot;
  13319. }
  13320. }
  13321. let boundTexture = currentBoundTextures[ webglSlot ];
  13322. if ( boundTexture === undefined ) {
  13323. boundTexture = { type: undefined, texture: undefined };
  13324. currentBoundTextures[ webglSlot ] = boundTexture;
  13325. }
  13326. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13327. if ( currentTextureSlot !== webglSlot ) {
  13328. gl.activeTexture( webglSlot );
  13329. currentTextureSlot = webglSlot;
  13330. }
  13331. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13332. boundTexture.type = webglType;
  13333. boundTexture.texture = webglTexture;
  13334. }
  13335. }
  13336. function unbindTexture() {
  13337. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13338. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13339. gl.bindTexture( boundTexture.type, null );
  13340. boundTexture.type = undefined;
  13341. boundTexture.texture = undefined;
  13342. }
  13343. }
  13344. function compressedTexImage2D() {
  13345. try {
  13346. gl.compressedTexImage2D.apply( gl, arguments );
  13347. } catch ( error ) {
  13348. console.error( 'THREE.WebGLState:', error );
  13349. }
  13350. }
  13351. function compressedTexImage3D() {
  13352. try {
  13353. gl.compressedTexImage3D.apply( gl, arguments );
  13354. } catch ( error ) {
  13355. console.error( 'THREE.WebGLState:', error );
  13356. }
  13357. }
  13358. function texSubImage2D() {
  13359. try {
  13360. gl.texSubImage2D.apply( gl, arguments );
  13361. } catch ( error ) {
  13362. console.error( 'THREE.WebGLState:', error );
  13363. }
  13364. }
  13365. function texSubImage3D() {
  13366. try {
  13367. gl.texSubImage3D.apply( gl, arguments );
  13368. } catch ( error ) {
  13369. console.error( 'THREE.WebGLState:', error );
  13370. }
  13371. }
  13372. function compressedTexSubImage2D() {
  13373. try {
  13374. gl.compressedTexSubImage2D.apply( gl, arguments );
  13375. } catch ( error ) {
  13376. console.error( 'THREE.WebGLState:', error );
  13377. }
  13378. }
  13379. function compressedTexSubImage3D() {
  13380. try {
  13381. gl.compressedTexSubImage3D.apply( gl, arguments );
  13382. } catch ( error ) {
  13383. console.error( 'THREE.WebGLState:', error );
  13384. }
  13385. }
  13386. function texStorage2D() {
  13387. try {
  13388. gl.texStorage2D.apply( gl, arguments );
  13389. } catch ( error ) {
  13390. console.error( 'THREE.WebGLState:', error );
  13391. }
  13392. }
  13393. function texStorage3D() {
  13394. try {
  13395. gl.texStorage3D.apply( gl, arguments );
  13396. } catch ( error ) {
  13397. console.error( 'THREE.WebGLState:', error );
  13398. }
  13399. }
  13400. function texImage2D() {
  13401. try {
  13402. gl.texImage2D.apply( gl, arguments );
  13403. } catch ( error ) {
  13404. console.error( 'THREE.WebGLState:', error );
  13405. }
  13406. }
  13407. function texImage3D() {
  13408. try {
  13409. gl.texImage3D.apply( gl, arguments );
  13410. } catch ( error ) {
  13411. console.error( 'THREE.WebGLState:', error );
  13412. }
  13413. }
  13414. //
  13415. function scissor( scissor ) {
  13416. if ( currentScissor.equals( scissor ) === false ) {
  13417. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13418. currentScissor.copy( scissor );
  13419. }
  13420. }
  13421. function viewport( viewport ) {
  13422. if ( currentViewport.equals( viewport ) === false ) {
  13423. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13424. currentViewport.copy( viewport );
  13425. }
  13426. }
  13427. function updateUBOMapping( uniformsGroup, program ) {
  13428. let mapping = uboProgramMap.get( program );
  13429. if ( mapping === undefined ) {
  13430. mapping = new WeakMap();
  13431. uboProgramMap.set( program, mapping );
  13432. }
  13433. let blockIndex = mapping.get( uniformsGroup );
  13434. if ( blockIndex === undefined ) {
  13435. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13436. mapping.set( uniformsGroup, blockIndex );
  13437. }
  13438. }
  13439. function uniformBlockBinding( uniformsGroup, program ) {
  13440. const mapping = uboProgramMap.get( program );
  13441. const blockIndex = mapping.get( uniformsGroup );
  13442. if ( uboBindings.get( program ) !== blockIndex ) {
  13443. // bind shader specific block index to global block point
  13444. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13445. uboBindings.set( program, blockIndex );
  13446. }
  13447. }
  13448. //
  13449. function reset() {
  13450. // reset state
  13451. gl.disable( gl.BLEND );
  13452. gl.disable( gl.CULL_FACE );
  13453. gl.disable( gl.DEPTH_TEST );
  13454. gl.disable( gl.POLYGON_OFFSET_FILL );
  13455. gl.disable( gl.SCISSOR_TEST );
  13456. gl.disable( gl.STENCIL_TEST );
  13457. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13458. gl.blendEquation( gl.FUNC_ADD );
  13459. gl.blendFunc( gl.ONE, gl.ZERO );
  13460. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  13461. gl.colorMask( true, true, true, true );
  13462. gl.clearColor( 0, 0, 0, 0 );
  13463. gl.depthMask( true );
  13464. gl.depthFunc( gl.LESS );
  13465. gl.clearDepth( 1 );
  13466. gl.stencilMask( 0xffffffff );
  13467. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  13468. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  13469. gl.clearStencil( 0 );
  13470. gl.cullFace( gl.BACK );
  13471. gl.frontFace( gl.CCW );
  13472. gl.polygonOffset( 0, 0 );
  13473. gl.activeTexture( gl.TEXTURE0 );
  13474. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  13475. if ( isWebGL2 === true ) {
  13476. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  13477. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  13478. }
  13479. gl.useProgram( null );
  13480. gl.lineWidth( 1 );
  13481. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13482. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13483. // reset internals
  13484. enabledCapabilities = {};
  13485. currentTextureSlot = null;
  13486. currentBoundTextures = {};
  13487. currentBoundFramebuffers = {};
  13488. currentDrawbuffers = new WeakMap();
  13489. defaultDrawbuffers = [];
  13490. currentProgram = null;
  13491. currentBlendingEnabled = false;
  13492. currentBlending = null;
  13493. currentBlendEquation = null;
  13494. currentBlendSrc = null;
  13495. currentBlendDst = null;
  13496. currentBlendEquationAlpha = null;
  13497. currentBlendSrcAlpha = null;
  13498. currentBlendDstAlpha = null;
  13499. currentPremultipledAlpha = false;
  13500. currentFlipSided = null;
  13501. currentCullFace = null;
  13502. currentLineWidth = null;
  13503. currentPolygonOffsetFactor = null;
  13504. currentPolygonOffsetUnits = null;
  13505. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13506. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13507. colorBuffer.reset();
  13508. depthBuffer.reset();
  13509. stencilBuffer.reset();
  13510. }
  13511. return {
  13512. buffers: {
  13513. color: colorBuffer,
  13514. depth: depthBuffer,
  13515. stencil: stencilBuffer
  13516. },
  13517. enable: enable,
  13518. disable: disable,
  13519. bindFramebuffer: bindFramebuffer,
  13520. drawBuffers: drawBuffers,
  13521. useProgram: useProgram,
  13522. setBlending: setBlending,
  13523. setMaterial: setMaterial,
  13524. setFlipSided: setFlipSided,
  13525. setCullFace: setCullFace,
  13526. setLineWidth: setLineWidth,
  13527. setPolygonOffset: setPolygonOffset,
  13528. setScissorTest: setScissorTest,
  13529. activeTexture: activeTexture,
  13530. bindTexture: bindTexture,
  13531. unbindTexture: unbindTexture,
  13532. compressedTexImage2D: compressedTexImage2D,
  13533. compressedTexImage3D: compressedTexImage3D,
  13534. texImage2D: texImage2D,
  13535. texImage3D: texImage3D,
  13536. updateUBOMapping: updateUBOMapping,
  13537. uniformBlockBinding: uniformBlockBinding,
  13538. texStorage2D: texStorage2D,
  13539. texStorage3D: texStorage3D,
  13540. texSubImage2D: texSubImage2D,
  13541. texSubImage3D: texSubImage3D,
  13542. compressedTexSubImage2D: compressedTexSubImage2D,
  13543. compressedTexSubImage3D: compressedTexSubImage3D,
  13544. scissor: scissor,
  13545. viewport: viewport,
  13546. reset: reset
  13547. };
  13548. }
  13549. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13550. const isWebGL2 = capabilities.isWebGL2;
  13551. const maxTextures = capabilities.maxTextures;
  13552. const maxCubemapSize = capabilities.maxCubemapSize;
  13553. const maxTextureSize = capabilities.maxTextureSize;
  13554. const maxSamples = capabilities.maxSamples;
  13555. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13556. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13557. const _videoTextures = new WeakMap();
  13558. let _canvas;
  13559. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13560. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13561. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13562. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13563. let useOffscreenCanvas = false;
  13564. try {
  13565. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13566. // eslint-disable-next-line compat/compat
  13567. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13568. } catch ( err ) {
  13569. // Ignore any errors
  13570. }
  13571. function createCanvas( width, height ) {
  13572. // Use OffscreenCanvas when available. Specially needed in web workers
  13573. return useOffscreenCanvas ?
  13574. // eslint-disable-next-line compat/compat
  13575. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13576. }
  13577. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13578. let scale = 1;
  13579. // handle case if texture exceeds max size
  13580. if ( image.width > maxSize || image.height > maxSize ) {
  13581. scale = maxSize / Math.max( image.width, image.height );
  13582. }
  13583. // only perform resize if necessary
  13584. if ( scale < 1 || needsPowerOfTwo === true ) {
  13585. // only perform resize for certain image types
  13586. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13587. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13588. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13589. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13590. const width = floor( scale * image.width );
  13591. const height = floor( scale * image.height );
  13592. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13593. // cube textures can't reuse the same canvas
  13594. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13595. canvas.width = width;
  13596. canvas.height = height;
  13597. const context = canvas.getContext( '2d' );
  13598. context.drawImage( image, 0, 0, width, height );
  13599. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13600. return canvas;
  13601. } else {
  13602. if ( 'data' in image ) {
  13603. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13604. }
  13605. return image;
  13606. }
  13607. }
  13608. return image;
  13609. }
  13610. function isPowerOfTwo$1( image ) {
  13611. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13612. }
  13613. function textureNeedsPowerOfTwo( texture ) {
  13614. if ( isWebGL2 ) return false;
  13615. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13616. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13617. }
  13618. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13619. return texture.generateMipmaps && supportsMips &&
  13620. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13621. }
  13622. function generateMipmap( target ) {
  13623. _gl.generateMipmap( target );
  13624. }
  13625. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13626. if ( isWebGL2 === false ) return glFormat;
  13627. if ( internalFormatName !== null ) {
  13628. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13629. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13630. }
  13631. let internalFormat = glFormat;
  13632. if ( glFormat === _gl.RED ) {
  13633. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  13634. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  13635. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  13636. }
  13637. if ( glFormat === _gl.RG ) {
  13638. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  13639. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  13640. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  13641. }
  13642. if ( glFormat === _gl.RGBA ) {
  13643. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  13644. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  13645. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13646. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  13647. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  13648. }
  13649. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  13650. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  13651. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  13652. extensions.get( 'EXT_color_buffer_float' );
  13653. }
  13654. return internalFormat;
  13655. }
  13656. function getMipLevels( texture, image, supportsMips ) {
  13657. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13658. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13659. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13660. // user-defined mipmaps
  13661. return texture.mipmaps.length;
  13662. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13663. return image.mipmaps.length;
  13664. } else {
  13665. // texture without mipmaps (only base level)
  13666. return 1;
  13667. }
  13668. }
  13669. // Fallback filters for non-power-of-2 textures
  13670. function filterFallback( f ) {
  13671. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13672. return _gl.NEAREST;
  13673. }
  13674. return _gl.LINEAR;
  13675. }
  13676. //
  13677. function onTextureDispose( event ) {
  13678. const texture = event.target;
  13679. texture.removeEventListener( 'dispose', onTextureDispose );
  13680. deallocateTexture( texture );
  13681. if ( texture.isVideoTexture ) {
  13682. _videoTextures.delete( texture );
  13683. }
  13684. }
  13685. function onRenderTargetDispose( event ) {
  13686. const renderTarget = event.target;
  13687. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13688. deallocateRenderTarget( renderTarget );
  13689. }
  13690. //
  13691. function deallocateTexture( texture ) {
  13692. const textureProperties = properties.get( texture );
  13693. if ( textureProperties.__webglInit === undefined ) return;
  13694. // check if it's necessary to remove the WebGLTexture object
  13695. const source = texture.source;
  13696. const webglTextures = _sources.get( source );
  13697. if ( webglTextures ) {
  13698. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13699. webglTexture.usedTimes --;
  13700. // the WebGLTexture object is not used anymore, remove it
  13701. if ( webglTexture.usedTimes === 0 ) {
  13702. deleteTexture( texture );
  13703. }
  13704. // remove the weak map entry if no WebGLTexture uses the source anymore
  13705. if ( Object.keys( webglTextures ).length === 0 ) {
  13706. _sources.delete( source );
  13707. }
  13708. }
  13709. properties.remove( texture );
  13710. }
  13711. function deleteTexture( texture ) {
  13712. const textureProperties = properties.get( texture );
  13713. _gl.deleteTexture( textureProperties.__webglTexture );
  13714. const source = texture.source;
  13715. const webglTextures = _sources.get( source );
  13716. delete webglTextures[ textureProperties.__cacheKey ];
  13717. info.memory.textures --;
  13718. }
  13719. function deallocateRenderTarget( renderTarget ) {
  13720. const texture = renderTarget.texture;
  13721. const renderTargetProperties = properties.get( renderTarget );
  13722. const textureProperties = properties.get( texture );
  13723. if ( textureProperties.__webglTexture !== undefined ) {
  13724. _gl.deleteTexture( textureProperties.__webglTexture );
  13725. info.memory.textures --;
  13726. }
  13727. if ( renderTarget.depthTexture ) {
  13728. renderTarget.depthTexture.dispose();
  13729. }
  13730. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13731. for ( let i = 0; i < 6; i ++ ) {
  13732. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13733. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13734. }
  13735. } else {
  13736. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13737. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13738. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13739. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13740. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13741. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13742. }
  13743. }
  13744. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13745. }
  13746. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13747. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13748. const attachmentProperties = properties.get( texture[ i ] );
  13749. if ( attachmentProperties.__webglTexture ) {
  13750. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13751. info.memory.textures --;
  13752. }
  13753. properties.remove( texture[ i ] );
  13754. }
  13755. }
  13756. properties.remove( texture );
  13757. properties.remove( renderTarget );
  13758. }
  13759. //
  13760. let textureUnits = 0;
  13761. function resetTextureUnits() {
  13762. textureUnits = 0;
  13763. }
  13764. function allocateTextureUnit() {
  13765. const textureUnit = textureUnits;
  13766. if ( textureUnit >= maxTextures ) {
  13767. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13768. }
  13769. textureUnits += 1;
  13770. return textureUnit;
  13771. }
  13772. function getTextureCacheKey( texture ) {
  13773. const array = [];
  13774. array.push( texture.wrapS );
  13775. array.push( texture.wrapT );
  13776. array.push( texture.wrapR || 0 );
  13777. array.push( texture.magFilter );
  13778. array.push( texture.minFilter );
  13779. array.push( texture.anisotropy );
  13780. array.push( texture.internalFormat );
  13781. array.push( texture.format );
  13782. array.push( texture.type );
  13783. array.push( texture.generateMipmaps );
  13784. array.push( texture.premultiplyAlpha );
  13785. array.push( texture.flipY );
  13786. array.push( texture.unpackAlignment );
  13787. array.push( texture.encoding );
  13788. return array.join();
  13789. }
  13790. //
  13791. function setTexture2D( texture, slot ) {
  13792. const textureProperties = properties.get( texture );
  13793. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13794. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13795. const image = texture.image;
  13796. if ( image === null ) {
  13797. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13798. } else if ( image.complete === false ) {
  13799. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13800. } else {
  13801. uploadTexture( textureProperties, texture, slot );
  13802. return;
  13803. }
  13804. }
  13805. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13806. }
  13807. function setTexture2DArray( texture, slot ) {
  13808. const textureProperties = properties.get( texture );
  13809. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13810. uploadTexture( textureProperties, texture, slot );
  13811. return;
  13812. }
  13813. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13814. }
  13815. function setTexture3D( texture, slot ) {
  13816. const textureProperties = properties.get( texture );
  13817. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13818. uploadTexture( textureProperties, texture, slot );
  13819. return;
  13820. }
  13821. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13822. }
  13823. function setTextureCube( texture, slot ) {
  13824. const textureProperties = properties.get( texture );
  13825. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13826. uploadCubeTexture( textureProperties, texture, slot );
  13827. return;
  13828. }
  13829. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13830. }
  13831. const wrappingToGL = {
  13832. [ RepeatWrapping ]: _gl.REPEAT,
  13833. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  13834. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  13835. };
  13836. const filterToGL = {
  13837. [ NearestFilter ]: _gl.NEAREST,
  13838. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  13839. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  13840. [ LinearFilter ]: _gl.LINEAR,
  13841. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  13842. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  13843. };
  13844. function setTextureParameters( textureType, texture, supportsMips ) {
  13845. if ( supportsMips ) {
  13846. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  13847. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  13848. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  13849. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  13850. }
  13851. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  13852. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  13853. } else {
  13854. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13855. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13856. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  13857. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  13858. }
  13859. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13860. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13861. }
  13862. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13863. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13864. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13865. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13866. }
  13867. }
  13868. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13869. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13870. if ( texture.magFilter === NearestFilter ) return;
  13871. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  13872. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13873. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13874. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13875. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13876. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13877. }
  13878. }
  13879. }
  13880. function initTexture( textureProperties, texture ) {
  13881. let forceUpload = false;
  13882. if ( textureProperties.__webglInit === undefined ) {
  13883. textureProperties.__webglInit = true;
  13884. texture.addEventListener( 'dispose', onTextureDispose );
  13885. }
  13886. // create Source <-> WebGLTextures mapping if necessary
  13887. const source = texture.source;
  13888. let webglTextures = _sources.get( source );
  13889. if ( webglTextures === undefined ) {
  13890. webglTextures = {};
  13891. _sources.set( source, webglTextures );
  13892. }
  13893. // check if there is already a WebGLTexture object for the given texture parameters
  13894. const textureCacheKey = getTextureCacheKey( texture );
  13895. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13896. // if not, create a new instance of WebGLTexture
  13897. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13898. // create new entry
  13899. webglTextures[ textureCacheKey ] = {
  13900. texture: _gl.createTexture(),
  13901. usedTimes: 0
  13902. };
  13903. info.memory.textures ++;
  13904. // when a new instance of WebGLTexture was created, a texture upload is required
  13905. // even if the image contents are identical
  13906. forceUpload = true;
  13907. }
  13908. webglTextures[ textureCacheKey ].usedTimes ++;
  13909. // every time the texture cache key changes, it's necessary to check if an instance of
  13910. // WebGLTexture can be deleted in order to avoid a memory leak.
  13911. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13912. if ( webglTexture !== undefined ) {
  13913. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13914. if ( webglTexture.usedTimes === 0 ) {
  13915. deleteTexture( texture );
  13916. }
  13917. }
  13918. // store references to cache key and WebGLTexture object
  13919. textureProperties.__cacheKey = textureCacheKey;
  13920. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13921. }
  13922. return forceUpload;
  13923. }
  13924. function uploadTexture( textureProperties, texture, slot ) {
  13925. let textureType = _gl.TEXTURE_2D;
  13926. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  13927. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  13928. const forceUpload = initTexture( textureProperties, texture );
  13929. const source = texture.source;
  13930. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  13931. const sourceProperties = properties.get( source );
  13932. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  13933. state.activeTexture( _gl.TEXTURE0 + slot );
  13934. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13935. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13936. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13937. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  13938. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13939. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13940. image = verifyColorSpace( texture, image );
  13941. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13942. glFormat = utils.convert( texture.format, texture.encoding );
  13943. let glType = utils.convert( texture.type ),
  13944. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13945. setTextureParameters( textureType, texture, supportsMips );
  13946. let mipmap;
  13947. const mipmaps = texture.mipmaps;
  13948. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13949. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  13950. const levels = getMipLevels( texture, image, supportsMips );
  13951. if ( texture.isDepthTexture ) {
  13952. // populate depth texture with dummy data
  13953. glInternalFormat = _gl.DEPTH_COMPONENT;
  13954. if ( isWebGL2 ) {
  13955. if ( texture.type === FloatType ) {
  13956. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13957. } else if ( texture.type === UnsignedIntType ) {
  13958. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13959. } else if ( texture.type === UnsignedInt248Type ) {
  13960. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13961. } else {
  13962. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13963. }
  13964. } else {
  13965. if ( texture.type === FloatType ) {
  13966. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13967. }
  13968. }
  13969. // validation checks for WebGL 1
  13970. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  13971. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13972. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13973. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13974. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13975. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13976. texture.type = UnsignedIntType;
  13977. glType = utils.convert( texture.type );
  13978. }
  13979. }
  13980. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  13981. // Depth stencil textures need the DEPTH_STENCIL internal format
  13982. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13983. glInternalFormat = _gl.DEPTH_STENCIL;
  13984. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13985. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13986. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13987. if ( texture.type !== UnsignedInt248Type ) {
  13988. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13989. texture.type = UnsignedInt248Type;
  13990. glType = utils.convert( texture.type );
  13991. }
  13992. }
  13993. //
  13994. if ( allocateMemory ) {
  13995. if ( useTexStorage ) {
  13996. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  13997. } else {
  13998. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13999. }
  14000. }
  14001. } else if ( texture.isDataTexture ) {
  14002. // use manually created mipmaps if available
  14003. // if there are no manual mipmaps
  14004. // set 0 level mipmap and then use GL to generate other mipmap levels
  14005. if ( mipmaps.length > 0 && supportsMips ) {
  14006. if ( useTexStorage && allocateMemory ) {
  14007. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14008. }
  14009. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14010. mipmap = mipmaps[ i ];
  14011. if ( useTexStorage ) {
  14012. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14013. } else {
  14014. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14015. }
  14016. }
  14017. texture.generateMipmaps = false;
  14018. } else {
  14019. if ( useTexStorage ) {
  14020. if ( allocateMemory ) {
  14021. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14022. }
  14023. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14024. } else {
  14025. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14026. }
  14027. }
  14028. } else if ( texture.isCompressedTexture ) {
  14029. if ( texture.isCompressedArrayTexture ) {
  14030. if ( useTexStorage && allocateMemory ) {
  14031. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14032. }
  14033. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14034. mipmap = mipmaps[ i ];
  14035. if ( texture.format !== RGBAFormat ) {
  14036. if ( glFormat !== null ) {
  14037. if ( useTexStorage ) {
  14038. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14039. } else {
  14040. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14041. }
  14042. } else {
  14043. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14044. }
  14045. } else {
  14046. if ( useTexStorage ) {
  14047. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14048. } else {
  14049. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14050. }
  14051. }
  14052. }
  14053. } else {
  14054. if ( useTexStorage && allocateMemory ) {
  14055. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14056. }
  14057. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14058. mipmap = mipmaps[ i ];
  14059. if ( texture.format !== RGBAFormat ) {
  14060. if ( glFormat !== null ) {
  14061. if ( useTexStorage ) {
  14062. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14063. } else {
  14064. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14065. }
  14066. } else {
  14067. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14068. }
  14069. } else {
  14070. if ( useTexStorage ) {
  14071. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14072. } else {
  14073. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14074. }
  14075. }
  14076. }
  14077. }
  14078. } else if ( texture.isDataArrayTexture ) {
  14079. if ( useTexStorage ) {
  14080. if ( allocateMemory ) {
  14081. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14082. }
  14083. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14084. } else {
  14085. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14086. }
  14087. } else if ( texture.isData3DTexture ) {
  14088. if ( useTexStorage ) {
  14089. if ( allocateMemory ) {
  14090. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14091. }
  14092. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14093. } else {
  14094. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14095. }
  14096. } else if ( texture.isFramebufferTexture ) {
  14097. if ( allocateMemory ) {
  14098. if ( useTexStorage ) {
  14099. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14100. } else {
  14101. let width = image.width, height = image.height;
  14102. for ( let i = 0; i < levels; i ++ ) {
  14103. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14104. width >>= 1;
  14105. height >>= 1;
  14106. }
  14107. }
  14108. }
  14109. } else {
  14110. // regular Texture (image, video, canvas)
  14111. // use manually created mipmaps if available
  14112. // if there are no manual mipmaps
  14113. // set 0 level mipmap and then use GL to generate other mipmap levels
  14114. if ( mipmaps.length > 0 && supportsMips ) {
  14115. if ( useTexStorage && allocateMemory ) {
  14116. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14117. }
  14118. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14119. mipmap = mipmaps[ i ];
  14120. if ( useTexStorage ) {
  14121. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14122. } else {
  14123. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14124. }
  14125. }
  14126. texture.generateMipmaps = false;
  14127. } else {
  14128. if ( useTexStorage ) {
  14129. if ( allocateMemory ) {
  14130. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14131. }
  14132. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14133. } else {
  14134. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14135. }
  14136. }
  14137. }
  14138. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14139. generateMipmap( textureType );
  14140. }
  14141. sourceProperties.__version = source.version;
  14142. if ( texture.onUpdate ) texture.onUpdate( texture );
  14143. }
  14144. textureProperties.__version = texture.version;
  14145. }
  14146. function uploadCubeTexture( textureProperties, texture, slot ) {
  14147. if ( texture.image.length !== 6 ) return;
  14148. const forceUpload = initTexture( textureProperties, texture );
  14149. const source = texture.source;
  14150. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14151. const sourceProperties = properties.get( source );
  14152. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14153. state.activeTexture( _gl.TEXTURE0 + slot );
  14154. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14155. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14156. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14157. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14158. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14159. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14160. const cubeImage = [];
  14161. for ( let i = 0; i < 6; i ++ ) {
  14162. if ( ! isCompressed && ! isDataTexture ) {
  14163. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14164. } else {
  14165. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14166. }
  14167. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14168. }
  14169. const image = cubeImage[ 0 ],
  14170. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14171. glFormat = utils.convert( texture.format, texture.encoding ),
  14172. glType = utils.convert( texture.type ),
  14173. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14174. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14175. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14176. let levels = getMipLevels( texture, image, supportsMips );
  14177. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14178. let mipmaps;
  14179. if ( isCompressed ) {
  14180. if ( useTexStorage && allocateMemory ) {
  14181. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14182. }
  14183. for ( let i = 0; i < 6; i ++ ) {
  14184. mipmaps = cubeImage[ i ].mipmaps;
  14185. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14186. const mipmap = mipmaps[ j ];
  14187. if ( texture.format !== RGBAFormat ) {
  14188. if ( glFormat !== null ) {
  14189. if ( useTexStorage ) {
  14190. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14191. } else {
  14192. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14193. }
  14194. } else {
  14195. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14196. }
  14197. } else {
  14198. if ( useTexStorage ) {
  14199. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14200. } else {
  14201. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14202. }
  14203. }
  14204. }
  14205. }
  14206. } else {
  14207. mipmaps = texture.mipmaps;
  14208. if ( useTexStorage && allocateMemory ) {
  14209. // TODO: Uniformly handle mipmap definitions
  14210. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14211. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14212. if ( mipmaps.length > 0 ) levels ++;
  14213. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14214. }
  14215. for ( let i = 0; i < 6; i ++ ) {
  14216. if ( isDataTexture ) {
  14217. if ( useTexStorage ) {
  14218. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14219. } else {
  14220. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14221. }
  14222. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14223. const mipmap = mipmaps[ j ];
  14224. const mipmapImage = mipmap.image[ i ].image;
  14225. if ( useTexStorage ) {
  14226. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14227. } else {
  14228. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14229. }
  14230. }
  14231. } else {
  14232. if ( useTexStorage ) {
  14233. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14234. } else {
  14235. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14236. }
  14237. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14238. const mipmap = mipmaps[ j ];
  14239. if ( useTexStorage ) {
  14240. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14241. } else {
  14242. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14243. }
  14244. }
  14245. }
  14246. }
  14247. }
  14248. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14249. // We assume images for cube map have the same size.
  14250. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14251. }
  14252. sourceProperties.__version = source.version;
  14253. if ( texture.onUpdate ) texture.onUpdate( texture );
  14254. }
  14255. textureProperties.__version = texture.version;
  14256. }
  14257. // Render targets
  14258. // Setup storage for target texture and bind it to correct framebuffer
  14259. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14260. const glFormat = utils.convert( texture.format, texture.encoding );
  14261. const glType = utils.convert( texture.type );
  14262. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14263. const renderTargetProperties = properties.get( renderTarget );
  14264. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14265. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14266. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14267. } else {
  14268. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14269. }
  14270. }
  14271. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14272. if ( useMultisampledRTT( renderTarget ) ) {
  14273. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14274. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14275. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14276. }
  14277. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14278. }
  14279. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14280. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14281. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14282. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14283. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14284. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14285. const depthTexture = renderTarget.depthTexture;
  14286. if ( depthTexture && depthTexture.isDepthTexture ) {
  14287. if ( depthTexture.type === FloatType ) {
  14288. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14289. } else if ( depthTexture.type === UnsignedIntType ) {
  14290. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14291. }
  14292. }
  14293. const samples = getRenderTargetSamples( renderTarget );
  14294. if ( useMultisampledRTT( renderTarget ) ) {
  14295. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14296. } else {
  14297. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14298. }
  14299. } else {
  14300. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14301. }
  14302. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14303. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14304. const samples = getRenderTargetSamples( renderTarget );
  14305. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14306. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14307. } else if ( useMultisampledRTT( renderTarget ) ) {
  14308. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14309. } else {
  14310. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14311. }
  14312. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14313. } else {
  14314. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14315. for ( let i = 0; i < textures.length; i ++ ) {
  14316. const texture = textures[ i ];
  14317. const glFormat = utils.convert( texture.format, texture.encoding );
  14318. const glType = utils.convert( texture.type );
  14319. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14320. const samples = getRenderTargetSamples( renderTarget );
  14321. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14322. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14323. } else if ( useMultisampledRTT( renderTarget ) ) {
  14324. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14325. } else {
  14326. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14327. }
  14328. }
  14329. }
  14330. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14331. }
  14332. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14333. function setupDepthTexture( framebuffer, renderTarget ) {
  14334. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14335. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14336. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14337. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14338. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14339. }
  14340. // upload an empty depth texture with framebuffer size
  14341. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14342. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14343. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14344. renderTarget.depthTexture.image.width = renderTarget.width;
  14345. renderTarget.depthTexture.image.height = renderTarget.height;
  14346. renderTarget.depthTexture.needsUpdate = true;
  14347. }
  14348. setTexture2D( renderTarget.depthTexture, 0 );
  14349. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14350. const samples = getRenderTargetSamples( renderTarget );
  14351. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14352. if ( useMultisampledRTT( renderTarget ) ) {
  14353. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14354. } else {
  14355. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14356. }
  14357. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14358. if ( useMultisampledRTT( renderTarget ) ) {
  14359. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14360. } else {
  14361. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14362. }
  14363. } else {
  14364. throw new Error( 'Unknown depthTexture format' );
  14365. }
  14366. }
  14367. // Setup GL resources for a non-texture depth buffer
  14368. function setupDepthRenderbuffer( renderTarget ) {
  14369. const renderTargetProperties = properties.get( renderTarget );
  14370. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14371. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14372. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14373. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14374. } else {
  14375. if ( isCube ) {
  14376. renderTargetProperties.__webglDepthbuffer = [];
  14377. for ( let i = 0; i < 6; i ++ ) {
  14378. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14379. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14380. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14381. }
  14382. } else {
  14383. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14384. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14385. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14386. }
  14387. }
  14388. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14389. }
  14390. // rebind framebuffer with external textures
  14391. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14392. const renderTargetProperties = properties.get( renderTarget );
  14393. if ( colorTexture !== undefined ) {
  14394. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14395. }
  14396. if ( depthTexture !== undefined ) {
  14397. setupDepthRenderbuffer( renderTarget );
  14398. }
  14399. }
  14400. // Set up GL resources for the render target
  14401. function setupRenderTarget( renderTarget ) {
  14402. const texture = renderTarget.texture;
  14403. const renderTargetProperties = properties.get( renderTarget );
  14404. const textureProperties = properties.get( texture );
  14405. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14406. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14407. if ( textureProperties.__webglTexture === undefined ) {
  14408. textureProperties.__webglTexture = _gl.createTexture();
  14409. }
  14410. textureProperties.__version = texture.version;
  14411. info.memory.textures ++;
  14412. }
  14413. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14414. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14415. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14416. // Setup framebuffer
  14417. if ( isCube ) {
  14418. renderTargetProperties.__webglFramebuffer = [];
  14419. for ( let i = 0; i < 6; i ++ ) {
  14420. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14421. }
  14422. } else {
  14423. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14424. if ( isMultipleRenderTargets ) {
  14425. if ( capabilities.drawBuffers ) {
  14426. const textures = renderTarget.texture;
  14427. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14428. const attachmentProperties = properties.get( textures[ i ] );
  14429. if ( attachmentProperties.__webglTexture === undefined ) {
  14430. attachmentProperties.__webglTexture = _gl.createTexture();
  14431. info.memory.textures ++;
  14432. }
  14433. }
  14434. } else {
  14435. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14436. }
  14437. }
  14438. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14439. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14440. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14441. renderTargetProperties.__webglColorRenderbuffer = [];
  14442. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14443. for ( let i = 0; i < textures.length; i ++ ) {
  14444. const texture = textures[ i ];
  14445. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14446. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14447. const glFormat = utils.convert( texture.format, texture.encoding );
  14448. const glType = utils.convert( texture.type );
  14449. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14450. const samples = getRenderTargetSamples( renderTarget );
  14451. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14452. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14453. }
  14454. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14455. if ( renderTarget.depthBuffer ) {
  14456. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14457. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14458. }
  14459. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14460. }
  14461. }
  14462. // Setup color buffer
  14463. if ( isCube ) {
  14464. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  14465. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14466. for ( let i = 0; i < 6; i ++ ) {
  14467. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14468. }
  14469. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14470. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14471. }
  14472. state.unbindTexture();
  14473. } else if ( isMultipleRenderTargets ) {
  14474. const textures = renderTarget.texture;
  14475. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14476. const attachment = textures[ i ];
  14477. const attachmentProperties = properties.get( attachment );
  14478. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  14479. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  14480. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  14481. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14482. generateMipmap( _gl.TEXTURE_2D );
  14483. }
  14484. }
  14485. state.unbindTexture();
  14486. } else {
  14487. let glTextureType = _gl.TEXTURE_2D;
  14488. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14489. if ( isWebGL2 ) {
  14490. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14491. } else {
  14492. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14493. }
  14494. }
  14495. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14496. setTextureParameters( glTextureType, texture, supportsMips );
  14497. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  14498. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14499. generateMipmap( glTextureType );
  14500. }
  14501. state.unbindTexture();
  14502. }
  14503. // Setup depth and stencil buffers
  14504. if ( renderTarget.depthBuffer ) {
  14505. setupDepthRenderbuffer( renderTarget );
  14506. }
  14507. }
  14508. function updateRenderTargetMipmap( renderTarget ) {
  14509. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14510. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14511. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14512. const texture = textures[ i ];
  14513. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14514. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14515. const webglTexture = properties.get( texture ).__webglTexture;
  14516. state.bindTexture( target, webglTexture );
  14517. generateMipmap( target );
  14518. state.unbindTexture();
  14519. }
  14520. }
  14521. }
  14522. function updateMultisampleRenderTarget( renderTarget ) {
  14523. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14524. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14525. const width = renderTarget.width;
  14526. const height = renderTarget.height;
  14527. let mask = _gl.COLOR_BUFFER_BIT;
  14528. const invalidationArray = [];
  14529. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14530. const renderTargetProperties = properties.get( renderTarget );
  14531. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14532. // If MRT we need to remove FBO attachments
  14533. if ( isMultipleRenderTargets ) {
  14534. for ( let i = 0; i < textures.length; i ++ ) {
  14535. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14536. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  14537. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14538. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  14539. }
  14540. }
  14541. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14542. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14543. for ( let i = 0; i < textures.length; i ++ ) {
  14544. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  14545. if ( renderTarget.depthBuffer ) {
  14546. invalidationArray.push( depthStyle );
  14547. }
  14548. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14549. if ( ignoreDepthValues === false ) {
  14550. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  14551. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  14552. }
  14553. if ( isMultipleRenderTargets ) {
  14554. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14555. }
  14556. if ( ignoreDepthValues === true ) {
  14557. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  14558. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  14559. }
  14560. if ( isMultipleRenderTargets ) {
  14561. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14562. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  14563. }
  14564. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  14565. if ( supportsInvalidateFramebuffer ) {
  14566. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  14567. }
  14568. }
  14569. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  14570. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  14571. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14572. if ( isMultipleRenderTargets ) {
  14573. for ( let i = 0; i < textures.length; i ++ ) {
  14574. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14575. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14576. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14577. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14578. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  14579. }
  14580. }
  14581. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  14582. }
  14583. }
  14584. function getRenderTargetSamples( renderTarget ) {
  14585. return Math.min( maxSamples, renderTarget.samples );
  14586. }
  14587. function useMultisampledRTT( renderTarget ) {
  14588. const renderTargetProperties = properties.get( renderTarget );
  14589. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14590. }
  14591. function updateVideoTexture( texture ) {
  14592. const frame = info.render.frame;
  14593. // Check the last frame we updated the VideoTexture
  14594. if ( _videoTextures.get( texture ) !== frame ) {
  14595. _videoTextures.set( texture, frame );
  14596. texture.update();
  14597. }
  14598. }
  14599. function verifyColorSpace( texture, image ) {
  14600. const encoding = texture.encoding;
  14601. const format = texture.format;
  14602. const type = texture.type;
  14603. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14604. if ( encoding !== LinearEncoding ) {
  14605. // sRGB
  14606. if ( encoding === sRGBEncoding ) {
  14607. if ( isWebGL2 === false ) {
  14608. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14609. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14610. texture.format = _SRGBAFormat;
  14611. // it's not possible to generate mips in WebGL 1 with this extension
  14612. texture.minFilter = LinearFilter;
  14613. texture.generateMipmaps = false;
  14614. } else {
  14615. // slow fallback (CPU decode)
  14616. image = ImageUtils.sRGBToLinear( image );
  14617. }
  14618. } else {
  14619. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14620. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14621. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14622. }
  14623. }
  14624. } else {
  14625. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14626. }
  14627. }
  14628. return image;
  14629. }
  14630. //
  14631. this.allocateTextureUnit = allocateTextureUnit;
  14632. this.resetTextureUnits = resetTextureUnits;
  14633. this.setTexture2D = setTexture2D;
  14634. this.setTexture2DArray = setTexture2DArray;
  14635. this.setTexture3D = setTexture3D;
  14636. this.setTextureCube = setTextureCube;
  14637. this.rebindTextures = rebindTextures;
  14638. this.setupRenderTarget = setupRenderTarget;
  14639. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14640. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14641. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14642. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14643. this.useMultisampledRTT = useMultisampledRTT;
  14644. }
  14645. function WebGLUtils( gl, extensions, capabilities ) {
  14646. const isWebGL2 = capabilities.isWebGL2;
  14647. function convert( p, encoding = null ) {
  14648. let extension;
  14649. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  14650. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  14651. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  14652. if ( p === ByteType ) return gl.BYTE;
  14653. if ( p === ShortType ) return gl.SHORT;
  14654. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  14655. if ( p === IntType ) return gl.INT;
  14656. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  14657. if ( p === FloatType ) return gl.FLOAT;
  14658. if ( p === HalfFloatType ) {
  14659. if ( isWebGL2 ) return gl.HALF_FLOAT;
  14660. extension = extensions.get( 'OES_texture_half_float' );
  14661. if ( extension !== null ) {
  14662. return extension.HALF_FLOAT_OES;
  14663. } else {
  14664. return null;
  14665. }
  14666. }
  14667. if ( p === AlphaFormat ) return gl.ALPHA;
  14668. if ( p === RGBAFormat ) return gl.RGBA;
  14669. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  14670. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  14671. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  14672. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  14673. // WebGL 1 sRGB fallback
  14674. if ( p === _SRGBAFormat ) {
  14675. extension = extensions.get( 'EXT_sRGB' );
  14676. if ( extension !== null ) {
  14677. return extension.SRGB_ALPHA_EXT;
  14678. } else {
  14679. return null;
  14680. }
  14681. }
  14682. // WebGL2 formats.
  14683. if ( p === RedFormat ) return gl.RED;
  14684. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  14685. if ( p === RGFormat ) return gl.RG;
  14686. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  14687. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  14688. // S3TC
  14689. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14690. if ( encoding === sRGBEncoding ) {
  14691. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14692. if ( extension !== null ) {
  14693. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14694. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14695. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14696. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14697. } else {
  14698. return null;
  14699. }
  14700. } else {
  14701. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14702. if ( extension !== null ) {
  14703. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14704. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14705. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14706. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14707. } else {
  14708. return null;
  14709. }
  14710. }
  14711. }
  14712. // PVRTC
  14713. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14714. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14715. if ( extension !== null ) {
  14716. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14717. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14718. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14719. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14720. } else {
  14721. return null;
  14722. }
  14723. }
  14724. // ETC1
  14725. if ( p === RGB_ETC1_Format ) {
  14726. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14727. if ( extension !== null ) {
  14728. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14729. } else {
  14730. return null;
  14731. }
  14732. }
  14733. // ETC2
  14734. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14735. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14736. if ( extension !== null ) {
  14737. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14738. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14739. } else {
  14740. return null;
  14741. }
  14742. }
  14743. // ASTC
  14744. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14745. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14746. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14747. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14748. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14749. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14750. if ( extension !== null ) {
  14751. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14752. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14753. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14754. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14755. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14756. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14757. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14758. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14759. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14760. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14761. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14762. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14763. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14764. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14765. } else {
  14766. return null;
  14767. }
  14768. }
  14769. // BPTC
  14770. if ( p === RGBA_BPTC_Format ) {
  14771. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14772. if ( extension !== null ) {
  14773. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14774. } else {
  14775. return null;
  14776. }
  14777. }
  14778. // RGTC
  14779. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  14780. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  14781. if ( extension !== null ) {
  14782. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  14783. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  14784. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  14785. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  14786. } else {
  14787. return null;
  14788. }
  14789. }
  14790. //
  14791. if ( p === UnsignedInt248Type ) {
  14792. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  14793. extension = extensions.get( 'WEBGL_depth_texture' );
  14794. if ( extension !== null ) {
  14795. return extension.UNSIGNED_INT_24_8_WEBGL;
  14796. } else {
  14797. return null;
  14798. }
  14799. }
  14800. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14801. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14802. }
  14803. return { convert: convert };
  14804. }
  14805. class ArrayCamera extends PerspectiveCamera {
  14806. constructor( array = [] ) {
  14807. super();
  14808. this.isArrayCamera = true;
  14809. this.cameras = array;
  14810. }
  14811. }
  14812. class Group extends Object3D {
  14813. constructor() {
  14814. super();
  14815. this.isGroup = true;
  14816. this.type = 'Group';
  14817. }
  14818. }
  14819. const _moveEvent = { type: 'move' };
  14820. class WebXRController {
  14821. constructor() {
  14822. this._targetRay = null;
  14823. this._grip = null;
  14824. this._hand = null;
  14825. }
  14826. getHandSpace() {
  14827. if ( this._hand === null ) {
  14828. this._hand = new Group();
  14829. this._hand.matrixAutoUpdate = false;
  14830. this._hand.visible = false;
  14831. this._hand.joints = {};
  14832. this._hand.inputState = { pinching: false };
  14833. }
  14834. return this._hand;
  14835. }
  14836. getTargetRaySpace() {
  14837. if ( this._targetRay === null ) {
  14838. this._targetRay = new Group();
  14839. this._targetRay.matrixAutoUpdate = false;
  14840. this._targetRay.visible = false;
  14841. this._targetRay.hasLinearVelocity = false;
  14842. this._targetRay.linearVelocity = new Vector3();
  14843. this._targetRay.hasAngularVelocity = false;
  14844. this._targetRay.angularVelocity = new Vector3();
  14845. }
  14846. return this._targetRay;
  14847. }
  14848. getGripSpace() {
  14849. if ( this._grip === null ) {
  14850. this._grip = new Group();
  14851. this._grip.matrixAutoUpdate = false;
  14852. this._grip.visible = false;
  14853. this._grip.hasLinearVelocity = false;
  14854. this._grip.linearVelocity = new Vector3();
  14855. this._grip.hasAngularVelocity = false;
  14856. this._grip.angularVelocity = new Vector3();
  14857. }
  14858. return this._grip;
  14859. }
  14860. dispatchEvent( event ) {
  14861. if ( this._targetRay !== null ) {
  14862. this._targetRay.dispatchEvent( event );
  14863. }
  14864. if ( this._grip !== null ) {
  14865. this._grip.dispatchEvent( event );
  14866. }
  14867. if ( this._hand !== null ) {
  14868. this._hand.dispatchEvent( event );
  14869. }
  14870. return this;
  14871. }
  14872. connect( inputSource ) {
  14873. if ( inputSource && inputSource.hand ) {
  14874. const hand = this._hand;
  14875. if ( hand ) {
  14876. for ( const inputjoint of inputSource.hand.values() ) {
  14877. // Initialize hand with joints when connected
  14878. this._getHandJoint( hand, inputjoint );
  14879. }
  14880. }
  14881. }
  14882. this.dispatchEvent( { type: 'connected', data: inputSource } );
  14883. return this;
  14884. }
  14885. disconnect( inputSource ) {
  14886. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14887. if ( this._targetRay !== null ) {
  14888. this._targetRay.visible = false;
  14889. }
  14890. if ( this._grip !== null ) {
  14891. this._grip.visible = false;
  14892. }
  14893. if ( this._hand !== null ) {
  14894. this._hand.visible = false;
  14895. }
  14896. return this;
  14897. }
  14898. update( inputSource, frame, referenceSpace ) {
  14899. let inputPose = null;
  14900. let gripPose = null;
  14901. let handPose = null;
  14902. const targetRay = this._targetRay;
  14903. const grip = this._grip;
  14904. const hand = this._hand;
  14905. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14906. if ( hand && inputSource.hand ) {
  14907. handPose = true;
  14908. for ( const inputjoint of inputSource.hand.values() ) {
  14909. // Update the joints groups with the XRJoint poses
  14910. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14911. // The transform of this joint will be updated with the joint pose on each frame
  14912. const joint = this._getHandJoint( hand, inputjoint );
  14913. if ( jointPose !== null ) {
  14914. joint.matrix.fromArray( jointPose.transform.matrix );
  14915. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14916. joint.jointRadius = jointPose.radius;
  14917. }
  14918. joint.visible = jointPose !== null;
  14919. }
  14920. // Custom events
  14921. // Check pinchz
  14922. const indexTip = hand.joints[ 'index-finger-tip' ];
  14923. const thumbTip = hand.joints[ 'thumb-tip' ];
  14924. const distance = indexTip.position.distanceTo( thumbTip.position );
  14925. const distanceToPinch = 0.02;
  14926. const threshold = 0.005;
  14927. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14928. hand.inputState.pinching = false;
  14929. this.dispatchEvent( {
  14930. type: 'pinchend',
  14931. handedness: inputSource.handedness,
  14932. target: this
  14933. } );
  14934. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14935. hand.inputState.pinching = true;
  14936. this.dispatchEvent( {
  14937. type: 'pinchstart',
  14938. handedness: inputSource.handedness,
  14939. target: this
  14940. } );
  14941. }
  14942. } else {
  14943. if ( grip !== null && inputSource.gripSpace ) {
  14944. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14945. if ( gripPose !== null ) {
  14946. grip.matrix.fromArray( gripPose.transform.matrix );
  14947. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14948. if ( gripPose.linearVelocity ) {
  14949. grip.hasLinearVelocity = true;
  14950. grip.linearVelocity.copy( gripPose.linearVelocity );
  14951. } else {
  14952. grip.hasLinearVelocity = false;
  14953. }
  14954. if ( gripPose.angularVelocity ) {
  14955. grip.hasAngularVelocity = true;
  14956. grip.angularVelocity.copy( gripPose.angularVelocity );
  14957. } else {
  14958. grip.hasAngularVelocity = false;
  14959. }
  14960. }
  14961. }
  14962. }
  14963. if ( targetRay !== null ) {
  14964. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14965. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14966. if ( inputPose === null && gripPose !== null ) {
  14967. inputPose = gripPose;
  14968. }
  14969. if ( inputPose !== null ) {
  14970. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14971. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14972. if ( inputPose.linearVelocity ) {
  14973. targetRay.hasLinearVelocity = true;
  14974. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14975. } else {
  14976. targetRay.hasLinearVelocity = false;
  14977. }
  14978. if ( inputPose.angularVelocity ) {
  14979. targetRay.hasAngularVelocity = true;
  14980. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14981. } else {
  14982. targetRay.hasAngularVelocity = false;
  14983. }
  14984. this.dispatchEvent( _moveEvent );
  14985. }
  14986. }
  14987. }
  14988. if ( targetRay !== null ) {
  14989. targetRay.visible = ( inputPose !== null );
  14990. }
  14991. if ( grip !== null ) {
  14992. grip.visible = ( gripPose !== null );
  14993. }
  14994. if ( hand !== null ) {
  14995. hand.visible = ( handPose !== null );
  14996. }
  14997. return this;
  14998. }
  14999. // private method
  15000. _getHandJoint( hand, inputjoint ) {
  15001. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15002. const joint = new Group();
  15003. joint.matrixAutoUpdate = false;
  15004. joint.visible = false;
  15005. hand.joints[ inputjoint.jointName ] = joint;
  15006. hand.add( joint );
  15007. }
  15008. return hand.joints[ inputjoint.jointName ];
  15009. }
  15010. }
  15011. class DepthTexture extends Texture {
  15012. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15013. format = format !== undefined ? format : DepthFormat;
  15014. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15015. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15016. }
  15017. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15018. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15019. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15020. this.isDepthTexture = true;
  15021. this.image = { width: width, height: height };
  15022. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15023. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15024. this.flipY = false;
  15025. this.generateMipmaps = false;
  15026. }
  15027. }
  15028. class WebXRManager extends EventDispatcher {
  15029. constructor( renderer, gl ) {
  15030. super();
  15031. const scope = this;
  15032. let session = null;
  15033. let framebufferScaleFactor = 1.0;
  15034. let referenceSpace = null;
  15035. let referenceSpaceType = 'local-floor';
  15036. // Set default foveation to maximum.
  15037. let foveation = 1.0;
  15038. let customReferenceSpace = null;
  15039. let pose = null;
  15040. let glBinding = null;
  15041. let glProjLayer = null;
  15042. let glBaseLayer = null;
  15043. let xrFrame = null;
  15044. const attributes = gl.getContextAttributes();
  15045. let initialRenderTarget = null;
  15046. let newRenderTarget = null;
  15047. const controllers = [];
  15048. const controllerInputSources = [];
  15049. const planes = new Set();
  15050. const planesLastChangedTimes = new Map();
  15051. //
  15052. const cameraL = new PerspectiveCamera();
  15053. cameraL.layers.enable( 1 );
  15054. cameraL.viewport = new Vector4();
  15055. const cameraR = new PerspectiveCamera();
  15056. cameraR.layers.enable( 2 );
  15057. cameraR.viewport = new Vector4();
  15058. const cameras = [ cameraL, cameraR ];
  15059. const cameraVR = new ArrayCamera();
  15060. cameraVR.layers.enable( 1 );
  15061. cameraVR.layers.enable( 2 );
  15062. let _currentDepthNear = null;
  15063. let _currentDepthFar = null;
  15064. //
  15065. this.cameraAutoUpdate = true;
  15066. this.enabled = false;
  15067. this.isPresenting = false;
  15068. this.getController = function ( index ) {
  15069. let controller = controllers[ index ];
  15070. if ( controller === undefined ) {
  15071. controller = new WebXRController();
  15072. controllers[ index ] = controller;
  15073. }
  15074. return controller.getTargetRaySpace();
  15075. };
  15076. this.getControllerGrip = function ( index ) {
  15077. let controller = controllers[ index ];
  15078. if ( controller === undefined ) {
  15079. controller = new WebXRController();
  15080. controllers[ index ] = controller;
  15081. }
  15082. return controller.getGripSpace();
  15083. };
  15084. this.getHand = function ( index ) {
  15085. let controller = controllers[ index ];
  15086. if ( controller === undefined ) {
  15087. controller = new WebXRController();
  15088. controllers[ index ] = controller;
  15089. }
  15090. return controller.getHandSpace();
  15091. };
  15092. //
  15093. function onSessionEvent( event ) {
  15094. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15095. if ( controllerIndex === - 1 ) {
  15096. return;
  15097. }
  15098. const controller = controllers[ controllerIndex ];
  15099. if ( controller !== undefined ) {
  15100. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15101. }
  15102. }
  15103. function onSessionEnd() {
  15104. session.removeEventListener( 'select', onSessionEvent );
  15105. session.removeEventListener( 'selectstart', onSessionEvent );
  15106. session.removeEventListener( 'selectend', onSessionEvent );
  15107. session.removeEventListener( 'squeeze', onSessionEvent );
  15108. session.removeEventListener( 'squeezestart', onSessionEvent );
  15109. session.removeEventListener( 'squeezeend', onSessionEvent );
  15110. session.removeEventListener( 'end', onSessionEnd );
  15111. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15112. for ( let i = 0; i < controllers.length; i ++ ) {
  15113. const inputSource = controllerInputSources[ i ];
  15114. if ( inputSource === null ) continue;
  15115. controllerInputSources[ i ] = null;
  15116. controllers[ i ].disconnect( inputSource );
  15117. }
  15118. _currentDepthNear = null;
  15119. _currentDepthFar = null;
  15120. // restore framebuffer/rendering state
  15121. renderer.setRenderTarget( initialRenderTarget );
  15122. glBaseLayer = null;
  15123. glProjLayer = null;
  15124. glBinding = null;
  15125. session = null;
  15126. newRenderTarget = null;
  15127. //
  15128. animation.stop();
  15129. scope.isPresenting = false;
  15130. scope.dispatchEvent( { type: 'sessionend' } );
  15131. }
  15132. this.setFramebufferScaleFactor = function ( value ) {
  15133. framebufferScaleFactor = value;
  15134. if ( scope.isPresenting === true ) {
  15135. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15136. }
  15137. };
  15138. this.setReferenceSpaceType = function ( value ) {
  15139. referenceSpaceType = value;
  15140. if ( scope.isPresenting === true ) {
  15141. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15142. }
  15143. };
  15144. this.getReferenceSpace = function () {
  15145. return customReferenceSpace || referenceSpace;
  15146. };
  15147. this.setReferenceSpace = function ( space ) {
  15148. customReferenceSpace = space;
  15149. };
  15150. this.getBaseLayer = function () {
  15151. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15152. };
  15153. this.getBinding = function () {
  15154. return glBinding;
  15155. };
  15156. this.getFrame = function () {
  15157. return xrFrame;
  15158. };
  15159. this.getSession = function () {
  15160. return session;
  15161. };
  15162. this.setSession = async function ( value ) {
  15163. session = value;
  15164. if ( session !== null ) {
  15165. initialRenderTarget = renderer.getRenderTarget();
  15166. session.addEventListener( 'select', onSessionEvent );
  15167. session.addEventListener( 'selectstart', onSessionEvent );
  15168. session.addEventListener( 'selectend', onSessionEvent );
  15169. session.addEventListener( 'squeeze', onSessionEvent );
  15170. session.addEventListener( 'squeezestart', onSessionEvent );
  15171. session.addEventListener( 'squeezeend', onSessionEvent );
  15172. session.addEventListener( 'end', onSessionEnd );
  15173. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15174. if ( attributes.xrCompatible !== true ) {
  15175. await gl.makeXRCompatible();
  15176. }
  15177. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15178. const layerInit = {
  15179. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15180. alpha: attributes.alpha,
  15181. depth: attributes.depth,
  15182. stencil: attributes.stencil,
  15183. framebufferScaleFactor: framebufferScaleFactor
  15184. };
  15185. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15186. session.updateRenderState( { baseLayer: glBaseLayer } );
  15187. newRenderTarget = new WebGLRenderTarget(
  15188. glBaseLayer.framebufferWidth,
  15189. glBaseLayer.framebufferHeight,
  15190. {
  15191. format: RGBAFormat,
  15192. type: UnsignedByteType,
  15193. encoding: renderer.outputEncoding,
  15194. stencilBuffer: attributes.stencil
  15195. }
  15196. );
  15197. } else {
  15198. let depthFormat = null;
  15199. let depthType = null;
  15200. let glDepthFormat = null;
  15201. if ( attributes.depth ) {
  15202. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15203. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15204. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15205. }
  15206. const projectionlayerInit = {
  15207. colorFormat: gl.RGBA8,
  15208. depthFormat: glDepthFormat,
  15209. scaleFactor: framebufferScaleFactor
  15210. };
  15211. glBinding = new XRWebGLBinding( session, gl );
  15212. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15213. session.updateRenderState( { layers: [ glProjLayer ] } );
  15214. newRenderTarget = new WebGLRenderTarget(
  15215. glProjLayer.textureWidth,
  15216. glProjLayer.textureHeight,
  15217. {
  15218. format: RGBAFormat,
  15219. type: UnsignedByteType,
  15220. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15221. stencilBuffer: attributes.stencil,
  15222. encoding: renderer.outputEncoding,
  15223. samples: attributes.antialias ? 4 : 0
  15224. } );
  15225. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15226. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15227. }
  15228. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15229. this.setFoveation( foveation );
  15230. customReferenceSpace = null;
  15231. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15232. animation.setContext( session );
  15233. animation.start();
  15234. scope.isPresenting = true;
  15235. scope.dispatchEvent( { type: 'sessionstart' } );
  15236. }
  15237. };
  15238. function onInputSourcesChange( event ) {
  15239. // Notify disconnected
  15240. for ( let i = 0; i < event.removed.length; i ++ ) {
  15241. const inputSource = event.removed[ i ];
  15242. const index = controllerInputSources.indexOf( inputSource );
  15243. if ( index >= 0 ) {
  15244. controllerInputSources[ index ] = null;
  15245. controllers[ index ].disconnect( inputSource );
  15246. }
  15247. }
  15248. // Notify connected
  15249. for ( let i = 0; i < event.added.length; i ++ ) {
  15250. const inputSource = event.added[ i ];
  15251. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15252. if ( controllerIndex === - 1 ) {
  15253. // Assign input source a controller that currently has no input source
  15254. for ( let i = 0; i < controllers.length; i ++ ) {
  15255. if ( i >= controllerInputSources.length ) {
  15256. controllerInputSources.push( inputSource );
  15257. controllerIndex = i;
  15258. break;
  15259. } else if ( controllerInputSources[ i ] === null ) {
  15260. controllerInputSources[ i ] = inputSource;
  15261. controllerIndex = i;
  15262. break;
  15263. }
  15264. }
  15265. // If all controllers do currently receive input we ignore new ones
  15266. if ( controllerIndex === - 1 ) break;
  15267. }
  15268. const controller = controllers[ controllerIndex ];
  15269. if ( controller ) {
  15270. controller.connect( inputSource );
  15271. }
  15272. }
  15273. }
  15274. //
  15275. const cameraLPos = new Vector3();
  15276. const cameraRPos = new Vector3();
  15277. /**
  15278. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15279. * the cameras' projection and world matrices have already been set.
  15280. * And that near and far planes are identical for both cameras.
  15281. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15282. */
  15283. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15284. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15285. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15286. const ipd = cameraLPos.distanceTo( cameraRPos );
  15287. const projL = cameraL.projectionMatrix.elements;
  15288. const projR = cameraR.projectionMatrix.elements;
  15289. // VR systems will have identical far and near planes, and
  15290. // most likely identical top and bottom frustum extents.
  15291. // Use the left camera for these values.
  15292. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15293. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15294. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15295. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15296. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15297. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15298. const left = near * leftFov;
  15299. const right = near * rightFov;
  15300. // Calculate the new camera's position offset from the
  15301. // left camera. xOffset should be roughly half `ipd`.
  15302. const zOffset = ipd / ( - leftFov + rightFov );
  15303. const xOffset = zOffset * - leftFov;
  15304. // TODO: Better way to apply this offset?
  15305. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15306. camera.translateX( xOffset );
  15307. camera.translateZ( zOffset );
  15308. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15309. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15310. // Find the union of the frustum values of the cameras and scale
  15311. // the values so that the near plane's position does not change in world space,
  15312. // although must now be relative to the new union camera.
  15313. const near2 = near + zOffset;
  15314. const far2 = far + zOffset;
  15315. const left2 = left - xOffset;
  15316. const right2 = right + ( ipd - xOffset );
  15317. const top2 = topFov * far / far2 * near2;
  15318. const bottom2 = bottomFov * far / far2 * near2;
  15319. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15320. }
  15321. function updateCamera( camera, parent ) {
  15322. if ( parent === null ) {
  15323. camera.matrixWorld.copy( camera.matrix );
  15324. } else {
  15325. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15326. }
  15327. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15328. }
  15329. this.updateCamera = function ( camera ) {
  15330. if ( session === null ) return;
  15331. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15332. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15333. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15334. // Note that the new renderState won't apply until the next frame. See #18320
  15335. session.updateRenderState( {
  15336. depthNear: cameraVR.near,
  15337. depthFar: cameraVR.far
  15338. } );
  15339. _currentDepthNear = cameraVR.near;
  15340. _currentDepthFar = cameraVR.far;
  15341. }
  15342. const parent = camera.parent;
  15343. const cameras = cameraVR.cameras;
  15344. updateCamera( cameraVR, parent );
  15345. for ( let i = 0; i < cameras.length; i ++ ) {
  15346. updateCamera( cameras[ i ], parent );
  15347. }
  15348. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15349. // update user camera and its children
  15350. camera.matrix.copy( cameraVR.matrix );
  15351. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15352. const children = camera.children;
  15353. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15354. children[ i ].updateMatrixWorld( true );
  15355. }
  15356. // update projection matrix for proper view frustum culling
  15357. if ( cameras.length === 2 ) {
  15358. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15359. } else {
  15360. // assume single camera setup (AR)
  15361. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15362. }
  15363. };
  15364. this.getCamera = function () {
  15365. return cameraVR;
  15366. };
  15367. this.getFoveation = function () {
  15368. if ( glProjLayer === null && glBaseLayer === null ) {
  15369. return undefined;
  15370. }
  15371. return foveation;
  15372. };
  15373. this.setFoveation = function ( value ) {
  15374. // 0 = no foveation = full resolution
  15375. // 1 = maximum foveation = the edges render at lower resolution
  15376. foveation = value;
  15377. if ( glProjLayer !== null ) {
  15378. glProjLayer.fixedFoveation = value;
  15379. }
  15380. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15381. glBaseLayer.fixedFoveation = value;
  15382. }
  15383. };
  15384. this.getPlanes = function () {
  15385. return planes;
  15386. };
  15387. // Animation Loop
  15388. let onAnimationFrameCallback = null;
  15389. function onAnimationFrame( time, frame ) {
  15390. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15391. xrFrame = frame;
  15392. if ( pose !== null ) {
  15393. const views = pose.views;
  15394. if ( glBaseLayer !== null ) {
  15395. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15396. renderer.setRenderTarget( newRenderTarget );
  15397. }
  15398. let cameraVRNeedsUpdate = false;
  15399. // check if it's necessary to rebuild cameraVR's camera list
  15400. if ( views.length !== cameraVR.cameras.length ) {
  15401. cameraVR.cameras.length = 0;
  15402. cameraVRNeedsUpdate = true;
  15403. }
  15404. for ( let i = 0; i < views.length; i ++ ) {
  15405. const view = views[ i ];
  15406. let viewport = null;
  15407. if ( glBaseLayer !== null ) {
  15408. viewport = glBaseLayer.getViewport( view );
  15409. } else {
  15410. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15411. viewport = glSubImage.viewport;
  15412. // For side-by-side projection, we only produce a single texture for both eyes.
  15413. if ( i === 0 ) {
  15414. renderer.setRenderTargetTextures(
  15415. newRenderTarget,
  15416. glSubImage.colorTexture,
  15417. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15418. renderer.setRenderTarget( newRenderTarget );
  15419. }
  15420. }
  15421. let camera = cameras[ i ];
  15422. if ( camera === undefined ) {
  15423. camera = new PerspectiveCamera();
  15424. camera.layers.enable( i );
  15425. camera.viewport = new Vector4();
  15426. cameras[ i ] = camera;
  15427. }
  15428. camera.matrix.fromArray( view.transform.matrix );
  15429. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15430. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15431. if ( i === 0 ) {
  15432. cameraVR.matrix.copy( camera.matrix );
  15433. }
  15434. if ( cameraVRNeedsUpdate === true ) {
  15435. cameraVR.cameras.push( camera );
  15436. }
  15437. }
  15438. }
  15439. //
  15440. for ( let i = 0; i < controllers.length; i ++ ) {
  15441. const inputSource = controllerInputSources[ i ];
  15442. const controller = controllers[ i ];
  15443. if ( inputSource !== null && controller !== undefined ) {
  15444. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15445. }
  15446. }
  15447. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15448. if ( frame.detectedPlanes ) {
  15449. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15450. let planesToRemove = null;
  15451. for ( const plane of planes ) {
  15452. if ( ! frame.detectedPlanes.has( plane ) ) {
  15453. if ( planesToRemove === null ) {
  15454. planesToRemove = [];
  15455. }
  15456. planesToRemove.push( plane );
  15457. }
  15458. }
  15459. if ( planesToRemove !== null ) {
  15460. for ( const plane of planesToRemove ) {
  15461. planes.delete( plane );
  15462. planesLastChangedTimes.delete( plane );
  15463. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15464. }
  15465. }
  15466. for ( const plane of frame.detectedPlanes ) {
  15467. if ( ! planes.has( plane ) ) {
  15468. planes.add( plane );
  15469. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15470. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15471. } else {
  15472. const lastKnownTime = planesLastChangedTimes.get( plane );
  15473. if ( plane.lastChangedTime > lastKnownTime ) {
  15474. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15475. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15476. }
  15477. }
  15478. }
  15479. }
  15480. xrFrame = null;
  15481. }
  15482. const animation = new WebGLAnimation();
  15483. animation.setAnimationLoop( onAnimationFrame );
  15484. this.setAnimationLoop = function ( callback ) {
  15485. onAnimationFrameCallback = callback;
  15486. };
  15487. this.dispose = function () {};
  15488. }
  15489. }
  15490. function WebGLMaterials( renderer, properties ) {
  15491. function refreshFogUniforms( uniforms, fog ) {
  15492. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15493. if ( fog.isFog ) {
  15494. uniforms.fogNear.value = fog.near;
  15495. uniforms.fogFar.value = fog.far;
  15496. } else if ( fog.isFogExp2 ) {
  15497. uniforms.fogDensity.value = fog.density;
  15498. }
  15499. }
  15500. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15501. if ( material.isMeshBasicMaterial ) {
  15502. refreshUniformsCommon( uniforms, material );
  15503. } else if ( material.isMeshLambertMaterial ) {
  15504. refreshUniformsCommon( uniforms, material );
  15505. } else if ( material.isMeshToonMaterial ) {
  15506. refreshUniformsCommon( uniforms, material );
  15507. refreshUniformsToon( uniforms, material );
  15508. } else if ( material.isMeshPhongMaterial ) {
  15509. refreshUniformsCommon( uniforms, material );
  15510. refreshUniformsPhong( uniforms, material );
  15511. } else if ( material.isMeshStandardMaterial ) {
  15512. refreshUniformsCommon( uniforms, material );
  15513. refreshUniformsStandard( uniforms, material );
  15514. if ( material.isMeshPhysicalMaterial ) {
  15515. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15516. }
  15517. } else if ( material.isMeshMatcapMaterial ) {
  15518. refreshUniformsCommon( uniforms, material );
  15519. refreshUniformsMatcap( uniforms, material );
  15520. } else if ( material.isMeshDepthMaterial ) {
  15521. refreshUniformsCommon( uniforms, material );
  15522. } else if ( material.isMeshDistanceMaterial ) {
  15523. refreshUniformsCommon( uniforms, material );
  15524. refreshUniformsDistance( uniforms, material );
  15525. } else if ( material.isMeshNormalMaterial ) {
  15526. refreshUniformsCommon( uniforms, material );
  15527. } else if ( material.isLineBasicMaterial ) {
  15528. refreshUniformsLine( uniforms, material );
  15529. if ( material.isLineDashedMaterial ) {
  15530. refreshUniformsDash( uniforms, material );
  15531. }
  15532. } else if ( material.isPointsMaterial ) {
  15533. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15534. } else if ( material.isSpriteMaterial ) {
  15535. refreshUniformsSprites( uniforms, material );
  15536. } else if ( material.isShadowMaterial ) {
  15537. uniforms.color.value.copy( material.color );
  15538. uniforms.opacity.value = material.opacity;
  15539. } else if ( material.isShaderMaterial ) {
  15540. material.uniformsNeedUpdate = false; // #15581
  15541. }
  15542. }
  15543. function refreshUniformsCommon( uniforms, material ) {
  15544. uniforms.opacity.value = material.opacity;
  15545. if ( material.color ) {
  15546. uniforms.diffuse.value.copy( material.color );
  15547. }
  15548. if ( material.emissive ) {
  15549. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15550. }
  15551. if ( material.map ) {
  15552. uniforms.map.value = material.map;
  15553. }
  15554. if ( material.alphaMap ) {
  15555. uniforms.alphaMap.value = material.alphaMap;
  15556. }
  15557. if ( material.bumpMap ) {
  15558. uniforms.bumpMap.value = material.bumpMap;
  15559. uniforms.bumpScale.value = material.bumpScale;
  15560. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15561. }
  15562. if ( material.displacementMap ) {
  15563. uniforms.displacementMap.value = material.displacementMap;
  15564. uniforms.displacementScale.value = material.displacementScale;
  15565. uniforms.displacementBias.value = material.displacementBias;
  15566. }
  15567. if ( material.emissiveMap ) {
  15568. uniforms.emissiveMap.value = material.emissiveMap;
  15569. }
  15570. if ( material.normalMap ) {
  15571. uniforms.normalMap.value = material.normalMap;
  15572. uniforms.normalScale.value.copy( material.normalScale );
  15573. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15574. }
  15575. if ( material.specularMap ) {
  15576. uniforms.specularMap.value = material.specularMap;
  15577. }
  15578. if ( material.alphaTest > 0 ) {
  15579. uniforms.alphaTest.value = material.alphaTest;
  15580. }
  15581. const envMap = properties.get( material ).envMap;
  15582. if ( envMap ) {
  15583. uniforms.envMap.value = envMap;
  15584. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15585. uniforms.reflectivity.value = material.reflectivity;
  15586. uniforms.ior.value = material.ior;
  15587. uniforms.refractionRatio.value = material.refractionRatio;
  15588. }
  15589. if ( material.lightMap ) {
  15590. uniforms.lightMap.value = material.lightMap;
  15591. // artist-friendly light intensity scaling factor
  15592. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15593. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15594. }
  15595. if ( material.aoMap ) {
  15596. uniforms.aoMap.value = material.aoMap;
  15597. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15598. }
  15599. // uv repeat and offset setting priorities
  15600. // 1. color map
  15601. // 2. specular map
  15602. // 3. displacementMap map
  15603. // 4. normal map
  15604. // 5. bump map
  15605. // 6. roughnessMap map
  15606. // 7. metalnessMap map
  15607. // 8. alphaMap map
  15608. // 9. emissiveMap map
  15609. // 10. clearcoat map
  15610. // 11. clearcoat normal map
  15611. // 12. clearcoat roughnessMap map
  15612. // 13. iridescence map
  15613. // 14. iridescence thickness map
  15614. // 15. specular intensity map
  15615. // 16. specular tint map
  15616. // 17. transmission map
  15617. // 18. thickness map
  15618. let uvScaleMap;
  15619. if ( material.map ) {
  15620. uvScaleMap = material.map;
  15621. } else if ( material.specularMap ) {
  15622. uvScaleMap = material.specularMap;
  15623. } else if ( material.displacementMap ) {
  15624. uvScaleMap = material.displacementMap;
  15625. } else if ( material.normalMap ) {
  15626. uvScaleMap = material.normalMap;
  15627. } else if ( material.bumpMap ) {
  15628. uvScaleMap = material.bumpMap;
  15629. } else if ( material.roughnessMap ) {
  15630. uvScaleMap = material.roughnessMap;
  15631. } else if ( material.metalnessMap ) {
  15632. uvScaleMap = material.metalnessMap;
  15633. } else if ( material.alphaMap ) {
  15634. uvScaleMap = material.alphaMap;
  15635. } else if ( material.emissiveMap ) {
  15636. uvScaleMap = material.emissiveMap;
  15637. } else if ( material.clearcoatMap ) {
  15638. uvScaleMap = material.clearcoatMap;
  15639. } else if ( material.clearcoatNormalMap ) {
  15640. uvScaleMap = material.clearcoatNormalMap;
  15641. } else if ( material.clearcoatRoughnessMap ) {
  15642. uvScaleMap = material.clearcoatRoughnessMap;
  15643. } else if ( material.iridescenceMap ) {
  15644. uvScaleMap = material.iridescenceMap;
  15645. } else if ( material.iridescenceThicknessMap ) {
  15646. uvScaleMap = material.iridescenceThicknessMap;
  15647. } else if ( material.specularIntensityMap ) {
  15648. uvScaleMap = material.specularIntensityMap;
  15649. } else if ( material.specularColorMap ) {
  15650. uvScaleMap = material.specularColorMap;
  15651. } else if ( material.transmissionMap ) {
  15652. uvScaleMap = material.transmissionMap;
  15653. } else if ( material.thicknessMap ) {
  15654. uvScaleMap = material.thicknessMap;
  15655. } else if ( material.sheenColorMap ) {
  15656. uvScaleMap = material.sheenColorMap;
  15657. } else if ( material.sheenRoughnessMap ) {
  15658. uvScaleMap = material.sheenRoughnessMap;
  15659. }
  15660. if ( uvScaleMap !== undefined ) {
  15661. // backwards compatibility
  15662. if ( uvScaleMap.isWebGLRenderTarget ) {
  15663. uvScaleMap = uvScaleMap.texture;
  15664. }
  15665. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15666. uvScaleMap.updateMatrix();
  15667. }
  15668. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15669. }
  15670. // uv repeat and offset setting priorities for uv2
  15671. // 1. ao map
  15672. // 2. light map
  15673. let uv2ScaleMap;
  15674. if ( material.aoMap ) {
  15675. uv2ScaleMap = material.aoMap;
  15676. } else if ( material.lightMap ) {
  15677. uv2ScaleMap = material.lightMap;
  15678. }
  15679. if ( uv2ScaleMap !== undefined ) {
  15680. // backwards compatibility
  15681. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15682. uv2ScaleMap = uv2ScaleMap.texture;
  15683. }
  15684. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15685. uv2ScaleMap.updateMatrix();
  15686. }
  15687. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15688. }
  15689. }
  15690. function refreshUniformsLine( uniforms, material ) {
  15691. uniforms.diffuse.value.copy( material.color );
  15692. uniforms.opacity.value = material.opacity;
  15693. }
  15694. function refreshUniformsDash( uniforms, material ) {
  15695. uniforms.dashSize.value = material.dashSize;
  15696. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15697. uniforms.scale.value = material.scale;
  15698. }
  15699. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15700. uniforms.diffuse.value.copy( material.color );
  15701. uniforms.opacity.value = material.opacity;
  15702. uniforms.size.value = material.size * pixelRatio;
  15703. uniforms.scale.value = height * 0.5;
  15704. if ( material.map ) {
  15705. uniforms.map.value = material.map;
  15706. }
  15707. if ( material.alphaMap ) {
  15708. uniforms.alphaMap.value = material.alphaMap;
  15709. }
  15710. if ( material.alphaTest > 0 ) {
  15711. uniforms.alphaTest.value = material.alphaTest;
  15712. }
  15713. // uv repeat and offset setting priorities
  15714. // 1. color map
  15715. // 2. alpha map
  15716. let uvScaleMap;
  15717. if ( material.map ) {
  15718. uvScaleMap = material.map;
  15719. } else if ( material.alphaMap ) {
  15720. uvScaleMap = material.alphaMap;
  15721. }
  15722. if ( uvScaleMap !== undefined ) {
  15723. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15724. uvScaleMap.updateMatrix();
  15725. }
  15726. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15727. }
  15728. }
  15729. function refreshUniformsSprites( uniforms, material ) {
  15730. uniforms.diffuse.value.copy( material.color );
  15731. uniforms.opacity.value = material.opacity;
  15732. uniforms.rotation.value = material.rotation;
  15733. if ( material.map ) {
  15734. uniforms.map.value = material.map;
  15735. }
  15736. if ( material.alphaMap ) {
  15737. uniforms.alphaMap.value = material.alphaMap;
  15738. }
  15739. if ( material.alphaTest > 0 ) {
  15740. uniforms.alphaTest.value = material.alphaTest;
  15741. }
  15742. // uv repeat and offset setting priorities
  15743. // 1. color map
  15744. // 2. alpha map
  15745. let uvScaleMap;
  15746. if ( material.map ) {
  15747. uvScaleMap = material.map;
  15748. } else if ( material.alphaMap ) {
  15749. uvScaleMap = material.alphaMap;
  15750. }
  15751. if ( uvScaleMap !== undefined ) {
  15752. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15753. uvScaleMap.updateMatrix();
  15754. }
  15755. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15756. }
  15757. }
  15758. function refreshUniformsPhong( uniforms, material ) {
  15759. uniforms.specular.value.copy( material.specular );
  15760. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15761. }
  15762. function refreshUniformsToon( uniforms, material ) {
  15763. if ( material.gradientMap ) {
  15764. uniforms.gradientMap.value = material.gradientMap;
  15765. }
  15766. }
  15767. function refreshUniformsStandard( uniforms, material ) {
  15768. uniforms.roughness.value = material.roughness;
  15769. uniforms.metalness.value = material.metalness;
  15770. if ( material.roughnessMap ) {
  15771. uniforms.roughnessMap.value = material.roughnessMap;
  15772. }
  15773. if ( material.metalnessMap ) {
  15774. uniforms.metalnessMap.value = material.metalnessMap;
  15775. }
  15776. const envMap = properties.get( material ).envMap;
  15777. if ( envMap ) {
  15778. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15779. uniforms.envMapIntensity.value = material.envMapIntensity;
  15780. }
  15781. }
  15782. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15783. uniforms.ior.value = material.ior; // also part of uniforms common
  15784. if ( material.sheen > 0 ) {
  15785. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15786. uniforms.sheenRoughness.value = material.sheenRoughness;
  15787. if ( material.sheenColorMap ) {
  15788. uniforms.sheenColorMap.value = material.sheenColorMap;
  15789. }
  15790. if ( material.sheenRoughnessMap ) {
  15791. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15792. }
  15793. }
  15794. if ( material.clearcoat > 0 ) {
  15795. uniforms.clearcoat.value = material.clearcoat;
  15796. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15797. if ( material.clearcoatMap ) {
  15798. uniforms.clearcoatMap.value = material.clearcoatMap;
  15799. }
  15800. if ( material.clearcoatRoughnessMap ) {
  15801. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15802. }
  15803. if ( material.clearcoatNormalMap ) {
  15804. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15805. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15806. if ( material.side === BackSide ) {
  15807. uniforms.clearcoatNormalScale.value.negate();
  15808. }
  15809. }
  15810. }
  15811. if ( material.iridescence > 0 ) {
  15812. uniforms.iridescence.value = material.iridescence;
  15813. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15814. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15815. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15816. if ( material.iridescenceMap ) {
  15817. uniforms.iridescenceMap.value = material.iridescenceMap;
  15818. }
  15819. if ( material.iridescenceThicknessMap ) {
  15820. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15821. }
  15822. }
  15823. if ( material.transmission > 0 ) {
  15824. uniforms.transmission.value = material.transmission;
  15825. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15826. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15827. if ( material.transmissionMap ) {
  15828. uniforms.transmissionMap.value = material.transmissionMap;
  15829. }
  15830. uniforms.thickness.value = material.thickness;
  15831. if ( material.thicknessMap ) {
  15832. uniforms.thicknessMap.value = material.thicknessMap;
  15833. }
  15834. uniforms.attenuationDistance.value = material.attenuationDistance;
  15835. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15836. }
  15837. uniforms.specularIntensity.value = material.specularIntensity;
  15838. uniforms.specularColor.value.copy( material.specularColor );
  15839. if ( material.specularIntensityMap ) {
  15840. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15841. }
  15842. if ( material.specularColorMap ) {
  15843. uniforms.specularColorMap.value = material.specularColorMap;
  15844. }
  15845. }
  15846. function refreshUniformsMatcap( uniforms, material ) {
  15847. if ( material.matcap ) {
  15848. uniforms.matcap.value = material.matcap;
  15849. }
  15850. }
  15851. function refreshUniformsDistance( uniforms, material ) {
  15852. uniforms.referencePosition.value.copy( material.referencePosition );
  15853. uniforms.nearDistance.value = material.nearDistance;
  15854. uniforms.farDistance.value = material.farDistance;
  15855. }
  15856. return {
  15857. refreshFogUniforms: refreshFogUniforms,
  15858. refreshMaterialUniforms: refreshMaterialUniforms
  15859. };
  15860. }
  15861. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15862. let buffers = {};
  15863. let updateList = {};
  15864. let allocatedBindingPoints = [];
  15865. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  15866. function bind( uniformsGroup, program ) {
  15867. const webglProgram = program.program;
  15868. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15869. }
  15870. function update( uniformsGroup, program ) {
  15871. let buffer = buffers[ uniformsGroup.id ];
  15872. if ( buffer === undefined ) {
  15873. prepareUniformsGroup( uniformsGroup );
  15874. buffer = createBuffer( uniformsGroup );
  15875. buffers[ uniformsGroup.id ] = buffer;
  15876. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15877. }
  15878. // ensure to update the binding points/block indices mapping for this program
  15879. const webglProgram = program.program;
  15880. state.updateUBOMapping( uniformsGroup, webglProgram );
  15881. // update UBO once per frame
  15882. const frame = info.render.frame;
  15883. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15884. updateBufferData( uniformsGroup );
  15885. updateList[ uniformsGroup.id ] = frame;
  15886. }
  15887. }
  15888. function createBuffer( uniformsGroup ) {
  15889. // the setup of an UBO is independent of a particular shader program but global
  15890. const bindingPointIndex = allocateBindingPointIndex();
  15891. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15892. const buffer = gl.createBuffer();
  15893. const size = uniformsGroup.__size;
  15894. const usage = uniformsGroup.usage;
  15895. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  15896. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  15897. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  15898. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  15899. return buffer;
  15900. }
  15901. function allocateBindingPointIndex() {
  15902. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15903. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15904. allocatedBindingPoints.push( i );
  15905. return i;
  15906. }
  15907. }
  15908. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15909. return 0;
  15910. }
  15911. function updateBufferData( uniformsGroup ) {
  15912. const buffer = buffers[ uniformsGroup.id ];
  15913. const uniforms = uniformsGroup.uniforms;
  15914. const cache = uniformsGroup.__cache;
  15915. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  15916. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15917. const uniform = uniforms[ i ];
  15918. // partly update the buffer if necessary
  15919. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15920. const offset = uniform.__offset;
  15921. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15922. let arrayOffset = 0;
  15923. for ( let i = 0; i < values.length; i ++ ) {
  15924. const value = values[ i ];
  15925. const info = getUniformSize( value );
  15926. if ( typeof value === 'number' ) {
  15927. uniform.__data[ 0 ] = value;
  15928. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  15929. } else if ( value.isMatrix3 ) {
  15930. // manually converting 3x3 to 3x4
  15931. uniform.__data[ 0 ] = value.elements[ 0 ];
  15932. uniform.__data[ 1 ] = value.elements[ 1 ];
  15933. uniform.__data[ 2 ] = value.elements[ 2 ];
  15934. uniform.__data[ 3 ] = value.elements[ 0 ];
  15935. uniform.__data[ 4 ] = value.elements[ 3 ];
  15936. uniform.__data[ 5 ] = value.elements[ 4 ];
  15937. uniform.__data[ 6 ] = value.elements[ 5 ];
  15938. uniform.__data[ 7 ] = value.elements[ 0 ];
  15939. uniform.__data[ 8 ] = value.elements[ 6 ];
  15940. uniform.__data[ 9 ] = value.elements[ 7 ];
  15941. uniform.__data[ 10 ] = value.elements[ 8 ];
  15942. uniform.__data[ 11 ] = value.elements[ 0 ];
  15943. } else {
  15944. value.toArray( uniform.__data, arrayOffset );
  15945. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  15946. }
  15947. }
  15948. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  15949. }
  15950. }
  15951. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  15952. }
  15953. function hasUniformChanged( uniform, index, cache ) {
  15954. const value = uniform.value;
  15955. if ( cache[ index ] === undefined ) {
  15956. // cache entry does not exist so far
  15957. if ( typeof value === 'number' ) {
  15958. cache[ index ] = value;
  15959. } else {
  15960. const values = Array.isArray( value ) ? value : [ value ];
  15961. const tempValues = [];
  15962. for ( let i = 0; i < values.length; i ++ ) {
  15963. tempValues.push( values[ i ].clone() );
  15964. }
  15965. cache[ index ] = tempValues;
  15966. }
  15967. return true;
  15968. } else {
  15969. // compare current value with cached entry
  15970. if ( typeof value === 'number' ) {
  15971. if ( cache[ index ] !== value ) {
  15972. cache[ index ] = value;
  15973. return true;
  15974. }
  15975. } else {
  15976. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  15977. const values = Array.isArray( value ) ? value : [ value ];
  15978. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  15979. const cachedObject = cachedObjects[ i ];
  15980. if ( cachedObject.equals( values[ i ] ) === false ) {
  15981. cachedObject.copy( values[ i ] );
  15982. return true;
  15983. }
  15984. }
  15985. }
  15986. }
  15987. return false;
  15988. }
  15989. function prepareUniformsGroup( uniformsGroup ) {
  15990. // determine total buffer size according to the STD140 layout
  15991. // Hint: STD140 is the only supported layout in WebGL 2
  15992. const uniforms = uniformsGroup.uniforms;
  15993. let offset = 0; // global buffer offset in bytes
  15994. const chunkSize = 16; // size of a chunk in bytes
  15995. let chunkOffset = 0; // offset within a single chunk in bytes
  15996. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  15997. const uniform = uniforms[ i ];
  15998. const infos = {
  15999. boundary: 0, // bytes
  16000. storage: 0 // bytes
  16001. };
  16002. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16003. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16004. const value = values[ j ];
  16005. const info = getUniformSize( value );
  16006. infos.boundary += info.boundary;
  16007. infos.storage += info.storage;
  16008. }
  16009. // the following two properties will be used for partial buffer updates
  16010. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16011. uniform.__offset = offset;
  16012. //
  16013. if ( i > 0 ) {
  16014. chunkOffset = offset % chunkSize;
  16015. const remainingSizeInChunk = chunkSize - chunkOffset;
  16016. // check for chunk overflow
  16017. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16018. // add padding and adjust offset
  16019. offset += ( chunkSize - chunkOffset );
  16020. uniform.__offset = offset;
  16021. }
  16022. }
  16023. offset += infos.storage;
  16024. }
  16025. // ensure correct final padding
  16026. chunkOffset = offset % chunkSize;
  16027. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16028. //
  16029. uniformsGroup.__size = offset;
  16030. uniformsGroup.__cache = {};
  16031. return this;
  16032. }
  16033. function getUniformSize( value ) {
  16034. const info = {
  16035. boundary: 0, // bytes
  16036. storage: 0 // bytes
  16037. };
  16038. // determine sizes according to STD140
  16039. if ( typeof value === 'number' ) {
  16040. // float/int
  16041. info.boundary = 4;
  16042. info.storage = 4;
  16043. } else if ( value.isVector2 ) {
  16044. // vec2
  16045. info.boundary = 8;
  16046. info.storage = 8;
  16047. } else if ( value.isVector3 || value.isColor ) {
  16048. // vec3
  16049. info.boundary = 16;
  16050. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16051. } else if ( value.isVector4 ) {
  16052. // vec4
  16053. info.boundary = 16;
  16054. info.storage = 16;
  16055. } else if ( value.isMatrix3 ) {
  16056. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16057. info.boundary = 48;
  16058. info.storage = 48;
  16059. } else if ( value.isMatrix4 ) {
  16060. // mat4
  16061. info.boundary = 64;
  16062. info.storage = 64;
  16063. } else if ( value.isTexture ) {
  16064. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16065. } else {
  16066. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16067. }
  16068. return info;
  16069. }
  16070. function onUniformsGroupsDispose( event ) {
  16071. const uniformsGroup = event.target;
  16072. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16073. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16074. allocatedBindingPoints.splice( index, 1 );
  16075. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16076. delete buffers[ uniformsGroup.id ];
  16077. delete updateList[ uniformsGroup.id ];
  16078. }
  16079. function dispose() {
  16080. for ( const id in buffers ) {
  16081. gl.deleteBuffer( buffers[ id ] );
  16082. }
  16083. allocatedBindingPoints = [];
  16084. buffers = {};
  16085. updateList = {};
  16086. }
  16087. return {
  16088. bind: bind,
  16089. update: update,
  16090. dispose: dispose
  16091. };
  16092. }
  16093. function createCanvasElement() {
  16094. const canvas = createElementNS( 'canvas' );
  16095. canvas.style.display = 'block';
  16096. return canvas;
  16097. }
  16098. function WebGLRenderer( parameters = {} ) {
  16099. this.isWebGLRenderer = true;
  16100. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16101. _context = parameters.context !== undefined ? parameters.context : null,
  16102. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16103. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16104. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16105. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16106. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16107. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16108. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16109. let _alpha;
  16110. if ( _context !== null ) {
  16111. _alpha = _context.getContextAttributes().alpha;
  16112. } else {
  16113. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16114. }
  16115. let currentRenderList = null;
  16116. let currentRenderState = null;
  16117. // render() can be called from within a callback triggered by another render.
  16118. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16119. const renderListStack = [];
  16120. const renderStateStack = [];
  16121. // public properties
  16122. this.domElement = _canvas;
  16123. // Debug configuration container
  16124. this.debug = {
  16125. /**
  16126. * Enables error checking and reporting when shader programs are being compiled
  16127. * @type {boolean}
  16128. */
  16129. checkShaderErrors: true
  16130. };
  16131. // clearing
  16132. this.autoClear = true;
  16133. this.autoClearColor = true;
  16134. this.autoClearDepth = true;
  16135. this.autoClearStencil = true;
  16136. // scene graph
  16137. this.sortObjects = true;
  16138. // user-defined clipping
  16139. this.clippingPlanes = [];
  16140. this.localClippingEnabled = false;
  16141. // physically based shading
  16142. this.outputEncoding = LinearEncoding;
  16143. // physical lights
  16144. this.physicallyCorrectLights = false;
  16145. // tone mapping
  16146. this.toneMapping = NoToneMapping;
  16147. this.toneMappingExposure = 1.0;
  16148. // internal properties
  16149. const _this = this;
  16150. let _isContextLost = false;
  16151. // internal state cache
  16152. let _currentActiveCubeFace = 0;
  16153. let _currentActiveMipmapLevel = 0;
  16154. let _currentRenderTarget = null;
  16155. let _currentMaterialId = - 1;
  16156. let _currentCamera = null;
  16157. const _currentViewport = new Vector4();
  16158. const _currentScissor = new Vector4();
  16159. let _currentScissorTest = null;
  16160. //
  16161. let _width = _canvas.width;
  16162. let _height = _canvas.height;
  16163. let _pixelRatio = 1;
  16164. let _opaqueSort = null;
  16165. let _transparentSort = null;
  16166. const _viewport = new Vector4( 0, 0, _width, _height );
  16167. const _scissor = new Vector4( 0, 0, _width, _height );
  16168. let _scissorTest = false;
  16169. // frustum
  16170. const _frustum = new Frustum();
  16171. // clipping
  16172. let _clippingEnabled = false;
  16173. let _localClippingEnabled = false;
  16174. // transmission
  16175. let _transmissionRenderTarget = null;
  16176. // camera matrices cache
  16177. const _projScreenMatrix = new Matrix4();
  16178. const _vector2 = new Vector2();
  16179. const _vector3 = new Vector3();
  16180. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16181. function getTargetPixelRatio() {
  16182. return _currentRenderTarget === null ? _pixelRatio : 1;
  16183. }
  16184. // initialize
  16185. let _gl = _context;
  16186. function getContext( contextNames, contextAttributes ) {
  16187. for ( let i = 0; i < contextNames.length; i ++ ) {
  16188. const contextName = contextNames[ i ];
  16189. const context = _canvas.getContext( contextName, contextAttributes );
  16190. if ( context !== null ) return context;
  16191. }
  16192. return null;
  16193. }
  16194. try {
  16195. const contextAttributes = {
  16196. alpha: true,
  16197. depth: _depth,
  16198. stencil: _stencil,
  16199. antialias: _antialias,
  16200. premultipliedAlpha: _premultipliedAlpha,
  16201. preserveDrawingBuffer: _preserveDrawingBuffer,
  16202. powerPreference: _powerPreference,
  16203. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16204. };
  16205. // OffscreenCanvas does not have setAttribute, see #22811
  16206. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16207. // event listeners must be registered before WebGL context is created, see #12753
  16208. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16209. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16210. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16211. if ( _gl === null ) {
  16212. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16213. if ( _this.isWebGL1Renderer === true ) {
  16214. contextNames.shift();
  16215. }
  16216. _gl = getContext( contextNames, contextAttributes );
  16217. if ( _gl === null ) {
  16218. if ( getContext( contextNames ) ) {
  16219. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16220. } else {
  16221. throw new Error( 'Error creating WebGL context.' );
  16222. }
  16223. }
  16224. }
  16225. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16226. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16227. _gl.getShaderPrecisionFormat = function () {
  16228. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16229. };
  16230. }
  16231. } catch ( error ) {
  16232. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16233. throw error;
  16234. }
  16235. let extensions, capabilities, state, info;
  16236. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16237. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16238. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16239. let utils, bindingStates, uniformsGroups;
  16240. function initGLContext() {
  16241. extensions = new WebGLExtensions( _gl );
  16242. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16243. extensions.init( capabilities );
  16244. utils = new WebGLUtils( _gl, extensions, capabilities );
  16245. state = new WebGLState( _gl, extensions, capabilities );
  16246. info = new WebGLInfo( _gl );
  16247. properties = new WebGLProperties();
  16248. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16249. cubemaps = new WebGLCubeMaps( _this );
  16250. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16251. attributes = new WebGLAttributes( _gl, capabilities );
  16252. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16253. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16254. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16255. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16256. clipping = new WebGLClipping( properties );
  16257. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16258. materials = new WebGLMaterials( _this, properties );
  16259. renderLists = new WebGLRenderLists();
  16260. renderStates = new WebGLRenderStates( extensions, capabilities );
  16261. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16262. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16263. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16264. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16265. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16266. info.programs = programCache.programs;
  16267. _this.capabilities = capabilities;
  16268. _this.extensions = extensions;
  16269. _this.properties = properties;
  16270. _this.renderLists = renderLists;
  16271. _this.shadowMap = shadowMap;
  16272. _this.state = state;
  16273. _this.info = info;
  16274. }
  16275. initGLContext();
  16276. // xr
  16277. const xr = new WebXRManager( _this, _gl );
  16278. this.xr = xr;
  16279. // API
  16280. this.getContext = function () {
  16281. return _gl;
  16282. };
  16283. this.getContextAttributes = function () {
  16284. return _gl.getContextAttributes();
  16285. };
  16286. this.forceContextLoss = function () {
  16287. const extension = extensions.get( 'WEBGL_lose_context' );
  16288. if ( extension ) extension.loseContext();
  16289. };
  16290. this.forceContextRestore = function () {
  16291. const extension = extensions.get( 'WEBGL_lose_context' );
  16292. if ( extension ) extension.restoreContext();
  16293. };
  16294. this.getPixelRatio = function () {
  16295. return _pixelRatio;
  16296. };
  16297. this.setPixelRatio = function ( value ) {
  16298. if ( value === undefined ) return;
  16299. _pixelRatio = value;
  16300. this.setSize( _width, _height, false );
  16301. };
  16302. this.getSize = function ( target ) {
  16303. return target.set( _width, _height );
  16304. };
  16305. this.setSize = function ( width, height, updateStyle ) {
  16306. if ( xr.isPresenting ) {
  16307. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16308. return;
  16309. }
  16310. _width = width;
  16311. _height = height;
  16312. _canvas.width = Math.floor( width * _pixelRatio );
  16313. _canvas.height = Math.floor( height * _pixelRatio );
  16314. if ( updateStyle !== false ) {
  16315. _canvas.style.width = width + 'px';
  16316. _canvas.style.height = height + 'px';
  16317. }
  16318. this.setViewport( 0, 0, width, height );
  16319. };
  16320. this.getDrawingBufferSize = function ( target ) {
  16321. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16322. };
  16323. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16324. _width = width;
  16325. _height = height;
  16326. _pixelRatio = pixelRatio;
  16327. _canvas.width = Math.floor( width * pixelRatio );
  16328. _canvas.height = Math.floor( height * pixelRatio );
  16329. this.setViewport( 0, 0, width, height );
  16330. };
  16331. this.getCurrentViewport = function ( target ) {
  16332. return target.copy( _currentViewport );
  16333. };
  16334. this.getViewport = function ( target ) {
  16335. return target.copy( _viewport );
  16336. };
  16337. this.setViewport = function ( x, y, width, height ) {
  16338. if ( x.isVector4 ) {
  16339. _viewport.set( x.x, x.y, x.z, x.w );
  16340. } else {
  16341. _viewport.set( x, y, width, height );
  16342. }
  16343. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16344. };
  16345. this.getScissor = function ( target ) {
  16346. return target.copy( _scissor );
  16347. };
  16348. this.setScissor = function ( x, y, width, height ) {
  16349. if ( x.isVector4 ) {
  16350. _scissor.set( x.x, x.y, x.z, x.w );
  16351. } else {
  16352. _scissor.set( x, y, width, height );
  16353. }
  16354. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16355. };
  16356. this.getScissorTest = function () {
  16357. return _scissorTest;
  16358. };
  16359. this.setScissorTest = function ( boolean ) {
  16360. state.setScissorTest( _scissorTest = boolean );
  16361. };
  16362. this.setOpaqueSort = function ( method ) {
  16363. _opaqueSort = method;
  16364. };
  16365. this.setTransparentSort = function ( method ) {
  16366. _transparentSort = method;
  16367. };
  16368. // Clearing
  16369. this.getClearColor = function ( target ) {
  16370. return target.copy( background.getClearColor() );
  16371. };
  16372. this.setClearColor = function () {
  16373. background.setClearColor.apply( background, arguments );
  16374. };
  16375. this.getClearAlpha = function () {
  16376. return background.getClearAlpha();
  16377. };
  16378. this.setClearAlpha = function () {
  16379. background.setClearAlpha.apply( background, arguments );
  16380. };
  16381. this.clear = function ( color = true, depth = true, stencil = true ) {
  16382. let bits = 0;
  16383. if ( color ) bits |= _gl.COLOR_BUFFER_BIT;
  16384. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16385. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16386. _gl.clear( bits );
  16387. };
  16388. this.clearColor = function () {
  16389. this.clear( true, false, false );
  16390. };
  16391. this.clearDepth = function () {
  16392. this.clear( false, true, false );
  16393. };
  16394. this.clearStencil = function () {
  16395. this.clear( false, false, true );
  16396. };
  16397. //
  16398. this.dispose = function () {
  16399. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16400. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16401. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16402. renderLists.dispose();
  16403. renderStates.dispose();
  16404. properties.dispose();
  16405. cubemaps.dispose();
  16406. cubeuvmaps.dispose();
  16407. objects.dispose();
  16408. bindingStates.dispose();
  16409. uniformsGroups.dispose();
  16410. programCache.dispose();
  16411. xr.dispose();
  16412. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16413. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16414. if ( _transmissionRenderTarget ) {
  16415. _transmissionRenderTarget.dispose();
  16416. _transmissionRenderTarget = null;
  16417. }
  16418. animation.stop();
  16419. };
  16420. // Events
  16421. function onContextLost( event ) {
  16422. event.preventDefault();
  16423. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16424. _isContextLost = true;
  16425. }
  16426. function onContextRestore( /* event */ ) {
  16427. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16428. _isContextLost = false;
  16429. const infoAutoReset = info.autoReset;
  16430. const shadowMapEnabled = shadowMap.enabled;
  16431. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16432. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16433. const shadowMapType = shadowMap.type;
  16434. initGLContext();
  16435. info.autoReset = infoAutoReset;
  16436. shadowMap.enabled = shadowMapEnabled;
  16437. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16438. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16439. shadowMap.type = shadowMapType;
  16440. }
  16441. function onContextCreationError( event ) {
  16442. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16443. }
  16444. function onMaterialDispose( event ) {
  16445. const material = event.target;
  16446. material.removeEventListener( 'dispose', onMaterialDispose );
  16447. deallocateMaterial( material );
  16448. }
  16449. // Buffer deallocation
  16450. function deallocateMaterial( material ) {
  16451. releaseMaterialProgramReferences( material );
  16452. properties.remove( material );
  16453. }
  16454. function releaseMaterialProgramReferences( material ) {
  16455. const programs = properties.get( material ).programs;
  16456. if ( programs !== undefined ) {
  16457. programs.forEach( function ( program ) {
  16458. programCache.releaseProgram( program );
  16459. } );
  16460. if ( material.isShaderMaterial ) {
  16461. programCache.releaseShaderCache( material );
  16462. }
  16463. }
  16464. }
  16465. // Buffer rendering
  16466. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16467. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16468. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16469. const program = setProgram( camera, scene, geometry, material, object );
  16470. state.setMaterial( material, frontFaceCW );
  16471. //
  16472. let index = geometry.index;
  16473. let rangeFactor = 1;
  16474. if ( material.wireframe === true ) {
  16475. index = geometries.getWireframeAttribute( geometry );
  16476. rangeFactor = 2;
  16477. }
  16478. //
  16479. const drawRange = geometry.drawRange;
  16480. const position = geometry.attributes.position;
  16481. let drawStart = drawRange.start * rangeFactor;
  16482. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16483. if ( group !== null ) {
  16484. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16485. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16486. }
  16487. if ( index !== null ) {
  16488. drawStart = Math.max( drawStart, 0 );
  16489. drawEnd = Math.min( drawEnd, index.count );
  16490. } else if ( position !== undefined && position !== null ) {
  16491. drawStart = Math.max( drawStart, 0 );
  16492. drawEnd = Math.min( drawEnd, position.count );
  16493. }
  16494. const drawCount = drawEnd - drawStart;
  16495. if ( drawCount < 0 || drawCount === Infinity ) return;
  16496. //
  16497. bindingStates.setup( object, material, program, geometry, index );
  16498. let attribute;
  16499. let renderer = bufferRenderer;
  16500. if ( index !== null ) {
  16501. attribute = attributes.get( index );
  16502. renderer = indexedBufferRenderer;
  16503. renderer.setIndex( attribute );
  16504. }
  16505. //
  16506. if ( object.isMesh ) {
  16507. if ( material.wireframe === true ) {
  16508. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16509. renderer.setMode( _gl.LINES );
  16510. } else {
  16511. renderer.setMode( _gl.TRIANGLES );
  16512. }
  16513. } else if ( object.isLine ) {
  16514. let lineWidth = material.linewidth;
  16515. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16516. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16517. if ( object.isLineSegments ) {
  16518. renderer.setMode( _gl.LINES );
  16519. } else if ( object.isLineLoop ) {
  16520. renderer.setMode( _gl.LINE_LOOP );
  16521. } else {
  16522. renderer.setMode( _gl.LINE_STRIP );
  16523. }
  16524. } else if ( object.isPoints ) {
  16525. renderer.setMode( _gl.POINTS );
  16526. } else if ( object.isSprite ) {
  16527. renderer.setMode( _gl.TRIANGLES );
  16528. }
  16529. if ( object.isInstancedMesh ) {
  16530. renderer.renderInstances( drawStart, drawCount, object.count );
  16531. } else if ( geometry.isInstancedBufferGeometry ) {
  16532. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16533. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16534. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16535. } else {
  16536. renderer.render( drawStart, drawCount );
  16537. }
  16538. };
  16539. // Compile
  16540. this.compile = function ( scene, camera ) {
  16541. function prepare( material, scene, object ) {
  16542. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16543. material.side = BackSide;
  16544. material.needsUpdate = true;
  16545. getProgram( material, scene, object );
  16546. material.side = FrontSide;
  16547. material.needsUpdate = true;
  16548. getProgram( material, scene, object );
  16549. material.side = DoubleSide;
  16550. } else {
  16551. getProgram( material, scene, object );
  16552. }
  16553. }
  16554. currentRenderState = renderStates.get( scene );
  16555. currentRenderState.init();
  16556. renderStateStack.push( currentRenderState );
  16557. scene.traverseVisible( function ( object ) {
  16558. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16559. currentRenderState.pushLight( object );
  16560. if ( object.castShadow ) {
  16561. currentRenderState.pushShadow( object );
  16562. }
  16563. }
  16564. } );
  16565. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16566. scene.traverse( function ( object ) {
  16567. const material = object.material;
  16568. if ( material ) {
  16569. if ( Array.isArray( material ) ) {
  16570. for ( let i = 0; i < material.length; i ++ ) {
  16571. const material2 = material[ i ];
  16572. prepare( material2, scene, object );
  16573. }
  16574. } else {
  16575. prepare( material, scene, object );
  16576. }
  16577. }
  16578. } );
  16579. renderStateStack.pop();
  16580. currentRenderState = null;
  16581. };
  16582. // Animation Loop
  16583. let onAnimationFrameCallback = null;
  16584. function onAnimationFrame( time ) {
  16585. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16586. }
  16587. function onXRSessionStart() {
  16588. animation.stop();
  16589. }
  16590. function onXRSessionEnd() {
  16591. animation.start();
  16592. }
  16593. const animation = new WebGLAnimation();
  16594. animation.setAnimationLoop( onAnimationFrame );
  16595. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16596. this.setAnimationLoop = function ( callback ) {
  16597. onAnimationFrameCallback = callback;
  16598. xr.setAnimationLoop( callback );
  16599. ( callback === null ) ? animation.stop() : animation.start();
  16600. };
  16601. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16602. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16603. // Rendering
  16604. this.render = function ( scene, camera ) {
  16605. if ( camera !== undefined && camera.isCamera !== true ) {
  16606. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16607. return;
  16608. }
  16609. if ( _isContextLost === true ) return;
  16610. // update scene graph
  16611. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16612. // update camera matrices and frustum
  16613. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16614. if ( xr.enabled === true && xr.isPresenting === true ) {
  16615. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16616. camera = xr.getCamera(); // use XR camera for rendering
  16617. }
  16618. //
  16619. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16620. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16621. currentRenderState.init();
  16622. renderStateStack.push( currentRenderState );
  16623. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16624. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16625. _localClippingEnabled = this.localClippingEnabled;
  16626. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16627. currentRenderList = renderLists.get( scene, renderListStack.length );
  16628. currentRenderList.init();
  16629. renderListStack.push( currentRenderList );
  16630. projectObject( scene, camera, 0, _this.sortObjects );
  16631. currentRenderList.finish();
  16632. if ( _this.sortObjects === true ) {
  16633. currentRenderList.sort( _opaqueSort, _transparentSort );
  16634. }
  16635. //
  16636. if ( _clippingEnabled === true ) clipping.beginShadows();
  16637. const shadowsArray = currentRenderState.state.shadowsArray;
  16638. shadowMap.render( shadowsArray, scene, camera );
  16639. if ( _clippingEnabled === true ) clipping.endShadows();
  16640. //
  16641. if ( this.info.autoReset === true ) this.info.reset();
  16642. //
  16643. background.render( currentRenderList, scene );
  16644. // render scene
  16645. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16646. if ( camera.isArrayCamera ) {
  16647. const cameras = camera.cameras;
  16648. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16649. const camera2 = cameras[ i ];
  16650. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16651. }
  16652. } else {
  16653. renderScene( currentRenderList, scene, camera );
  16654. }
  16655. //
  16656. if ( _currentRenderTarget !== null ) {
  16657. // resolve multisample renderbuffers to a single-sample texture if necessary
  16658. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16659. // Generate mipmap if we're using any kind of mipmap filtering
  16660. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16661. }
  16662. //
  16663. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16664. // _gl.finish();
  16665. bindingStates.resetDefaultState();
  16666. _currentMaterialId = - 1;
  16667. _currentCamera = null;
  16668. renderStateStack.pop();
  16669. if ( renderStateStack.length > 0 ) {
  16670. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16671. } else {
  16672. currentRenderState = null;
  16673. }
  16674. renderListStack.pop();
  16675. if ( renderListStack.length > 0 ) {
  16676. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16677. } else {
  16678. currentRenderList = null;
  16679. }
  16680. };
  16681. function projectObject( object, camera, groupOrder, sortObjects ) {
  16682. if ( object.visible === false ) return;
  16683. const visible = object.layers.test( camera.layers );
  16684. if ( visible ) {
  16685. if ( object.isGroup ) {
  16686. groupOrder = object.renderOrder;
  16687. } else if ( object.isLOD ) {
  16688. if ( object.autoUpdate === true ) object.update( camera );
  16689. } else if ( object.isLight ) {
  16690. currentRenderState.pushLight( object );
  16691. if ( object.castShadow ) {
  16692. currentRenderState.pushShadow( object );
  16693. }
  16694. } else if ( object.isSprite ) {
  16695. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16696. if ( sortObjects ) {
  16697. _vector3.setFromMatrixPosition( object.matrixWorld )
  16698. .applyMatrix4( _projScreenMatrix );
  16699. }
  16700. const geometry = objects.update( object );
  16701. const material = object.material;
  16702. if ( material.visible ) {
  16703. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16704. }
  16705. }
  16706. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16707. if ( object.isSkinnedMesh ) {
  16708. // update skeleton only once in a frame
  16709. if ( object.skeleton.frame !== info.render.frame ) {
  16710. object.skeleton.update();
  16711. object.skeleton.frame = info.render.frame;
  16712. }
  16713. }
  16714. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16715. if ( sortObjects ) {
  16716. _vector3.setFromMatrixPosition( object.matrixWorld )
  16717. .applyMatrix4( _projScreenMatrix );
  16718. }
  16719. const geometry = objects.update( object );
  16720. const material = object.material;
  16721. if ( Array.isArray( material ) ) {
  16722. const groups = geometry.groups;
  16723. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16724. const group = groups[ i ];
  16725. const groupMaterial = material[ group.materialIndex ];
  16726. if ( groupMaterial && groupMaterial.visible ) {
  16727. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16728. }
  16729. }
  16730. } else if ( material.visible ) {
  16731. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16732. }
  16733. }
  16734. }
  16735. }
  16736. const children = object.children;
  16737. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16738. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16739. }
  16740. }
  16741. function renderScene( currentRenderList, scene, camera, viewport ) {
  16742. const opaqueObjects = currentRenderList.opaque;
  16743. const transmissiveObjects = currentRenderList.transmissive;
  16744. const transparentObjects = currentRenderList.transparent;
  16745. currentRenderState.setupLightsView( camera );
  16746. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16747. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16748. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16749. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16750. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16751. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16752. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16753. state.buffers.depth.setTest( true );
  16754. state.buffers.depth.setMask( true );
  16755. state.buffers.color.setMask( true );
  16756. state.setPolygonOffset( false );
  16757. }
  16758. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16759. const isWebGL2 = capabilities.isWebGL2;
  16760. if ( _transmissionRenderTarget === null ) {
  16761. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16762. generateMipmaps: true,
  16763. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16764. minFilter: LinearMipmapLinearFilter,
  16765. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16766. } );
  16767. }
  16768. _this.getDrawingBufferSize( _vector2 );
  16769. if ( isWebGL2 ) {
  16770. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16771. } else {
  16772. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16773. }
  16774. //
  16775. const currentRenderTarget = _this.getRenderTarget();
  16776. _this.setRenderTarget( _transmissionRenderTarget );
  16777. _this.clear();
  16778. // Turn off the features which can affect the frag color for opaque objects pass.
  16779. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16780. const currentToneMapping = _this.toneMapping;
  16781. _this.toneMapping = NoToneMapping;
  16782. renderObjects( opaqueObjects, scene, camera );
  16783. _this.toneMapping = currentToneMapping;
  16784. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16785. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16786. _this.setRenderTarget( currentRenderTarget );
  16787. }
  16788. function renderObjects( renderList, scene, camera ) {
  16789. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16790. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16791. const renderItem = renderList[ i ];
  16792. const object = renderItem.object;
  16793. const geometry = renderItem.geometry;
  16794. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16795. const group = renderItem.group;
  16796. if ( object.layers.test( camera.layers ) ) {
  16797. renderObject( object, scene, camera, geometry, material, group );
  16798. }
  16799. }
  16800. }
  16801. function renderObject( object, scene, camera, geometry, material, group ) {
  16802. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16803. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16804. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16805. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16806. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16807. material.side = BackSide;
  16808. material.needsUpdate = true;
  16809. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16810. material.side = FrontSide;
  16811. material.needsUpdate = true;
  16812. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16813. material.side = DoubleSide;
  16814. } else {
  16815. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16816. }
  16817. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16818. }
  16819. function getProgram( material, scene, object ) {
  16820. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16821. const materialProperties = properties.get( material );
  16822. const lights = currentRenderState.state.lights;
  16823. const shadowsArray = currentRenderState.state.shadowsArray;
  16824. const lightsStateVersion = lights.state.version;
  16825. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16826. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16827. let programs = materialProperties.programs;
  16828. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16829. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16830. materialProperties.fog = scene.fog;
  16831. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16832. if ( programs === undefined ) {
  16833. // new material
  16834. material.addEventListener( 'dispose', onMaterialDispose );
  16835. programs = new Map();
  16836. materialProperties.programs = programs;
  16837. }
  16838. let program = programs.get( programCacheKey );
  16839. if ( program !== undefined ) {
  16840. // early out if program and light state is identical
  16841. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16842. updateCommonMaterialProperties( material, parameters );
  16843. return program;
  16844. }
  16845. } else {
  16846. parameters.uniforms = programCache.getUniforms( material );
  16847. material.onBuild( object, parameters, _this );
  16848. material.onBeforeCompile( parameters, _this );
  16849. program = programCache.acquireProgram( parameters, programCacheKey );
  16850. programs.set( programCacheKey, program );
  16851. materialProperties.uniforms = parameters.uniforms;
  16852. }
  16853. const uniforms = materialProperties.uniforms;
  16854. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16855. uniforms.clippingPlanes = clipping.uniform;
  16856. }
  16857. updateCommonMaterialProperties( material, parameters );
  16858. // store the light setup it was created for
  16859. materialProperties.needsLights = materialNeedsLights( material );
  16860. materialProperties.lightsStateVersion = lightsStateVersion;
  16861. if ( materialProperties.needsLights ) {
  16862. // wire up the material to this renderer's lighting state
  16863. uniforms.ambientLightColor.value = lights.state.ambient;
  16864. uniforms.lightProbe.value = lights.state.probe;
  16865. uniforms.directionalLights.value = lights.state.directional;
  16866. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16867. uniforms.spotLights.value = lights.state.spot;
  16868. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16869. uniforms.rectAreaLights.value = lights.state.rectArea;
  16870. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16871. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16872. uniforms.pointLights.value = lights.state.point;
  16873. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16874. uniforms.hemisphereLights.value = lights.state.hemi;
  16875. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16876. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16877. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16878. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16879. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16880. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16881. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16882. // TODO (abelnation): add area lights shadow info to uniforms
  16883. }
  16884. const progUniforms = program.getUniforms();
  16885. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16886. materialProperties.currentProgram = program;
  16887. materialProperties.uniformsList = uniformsList;
  16888. return program;
  16889. }
  16890. function updateCommonMaterialProperties( material, parameters ) {
  16891. const materialProperties = properties.get( material );
  16892. materialProperties.outputEncoding = parameters.outputEncoding;
  16893. materialProperties.instancing = parameters.instancing;
  16894. materialProperties.skinning = parameters.skinning;
  16895. materialProperties.morphTargets = parameters.morphTargets;
  16896. materialProperties.morphNormals = parameters.morphNormals;
  16897. materialProperties.morphColors = parameters.morphColors;
  16898. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16899. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16900. materialProperties.numIntersection = parameters.numClipIntersection;
  16901. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16902. materialProperties.vertexTangents = parameters.vertexTangents;
  16903. materialProperties.toneMapping = parameters.toneMapping;
  16904. }
  16905. function setProgram( camera, scene, geometry, material, object ) {
  16906. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16907. textures.resetTextureUnits();
  16908. const fog = scene.fog;
  16909. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16910. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16911. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16912. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16913. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16914. const morphTargets = !! geometry.morphAttributes.position;
  16915. const morphNormals = !! geometry.morphAttributes.normal;
  16916. const morphColors = !! geometry.morphAttributes.color;
  16917. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16918. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16919. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16920. const materialProperties = properties.get( material );
  16921. const lights = currentRenderState.state.lights;
  16922. if ( _clippingEnabled === true ) {
  16923. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16924. const useCache =
  16925. camera === _currentCamera &&
  16926. material.id === _currentMaterialId;
  16927. // we might want to call this function with some ClippingGroup
  16928. // object instead of the material, once it becomes feasible
  16929. // (#8465, #8379)
  16930. clipping.setState( material, camera, useCache );
  16931. }
  16932. }
  16933. //
  16934. let needsProgramChange = false;
  16935. if ( material.version === materialProperties.__version ) {
  16936. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16937. needsProgramChange = true;
  16938. } else if ( materialProperties.outputEncoding !== encoding ) {
  16939. needsProgramChange = true;
  16940. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16941. needsProgramChange = true;
  16942. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16943. needsProgramChange = true;
  16944. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16945. needsProgramChange = true;
  16946. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16947. needsProgramChange = true;
  16948. } else if ( materialProperties.envMap !== envMap ) {
  16949. needsProgramChange = true;
  16950. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16951. needsProgramChange = true;
  16952. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16953. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16954. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16955. needsProgramChange = true;
  16956. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16957. needsProgramChange = true;
  16958. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16959. needsProgramChange = true;
  16960. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16961. needsProgramChange = true;
  16962. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16963. needsProgramChange = true;
  16964. } else if ( materialProperties.morphColors !== morphColors ) {
  16965. needsProgramChange = true;
  16966. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16967. needsProgramChange = true;
  16968. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16969. needsProgramChange = true;
  16970. }
  16971. } else {
  16972. needsProgramChange = true;
  16973. materialProperties.__version = material.version;
  16974. }
  16975. //
  16976. let program = materialProperties.currentProgram;
  16977. if ( needsProgramChange === true ) {
  16978. program = getProgram( material, scene, object );
  16979. }
  16980. let refreshProgram = false;
  16981. let refreshMaterial = false;
  16982. let refreshLights = false;
  16983. const p_uniforms = program.getUniforms(),
  16984. m_uniforms = materialProperties.uniforms;
  16985. if ( state.useProgram( program.program ) ) {
  16986. refreshProgram = true;
  16987. refreshMaterial = true;
  16988. refreshLights = true;
  16989. }
  16990. if ( material.id !== _currentMaterialId ) {
  16991. _currentMaterialId = material.id;
  16992. refreshMaterial = true;
  16993. }
  16994. if ( refreshProgram || _currentCamera !== camera ) {
  16995. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16996. if ( capabilities.logarithmicDepthBuffer ) {
  16997. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16998. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16999. }
  17000. if ( _currentCamera !== camera ) {
  17001. _currentCamera = camera;
  17002. // lighting uniforms depend on the camera so enforce an update
  17003. // now, in case this material supports lights - or later, when
  17004. // the next material that does gets activated:
  17005. refreshMaterial = true; // set to true on material change
  17006. refreshLights = true; // remains set until update done
  17007. }
  17008. // load material specific uniforms
  17009. // (shader material also gets them for the sake of genericity)
  17010. if ( material.isShaderMaterial ||
  17011. material.isMeshPhongMaterial ||
  17012. material.isMeshToonMaterial ||
  17013. material.isMeshStandardMaterial ||
  17014. material.envMap ) {
  17015. const uCamPos = p_uniforms.map.cameraPosition;
  17016. if ( uCamPos !== undefined ) {
  17017. uCamPos.setValue( _gl,
  17018. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17019. }
  17020. }
  17021. if ( material.isMeshPhongMaterial ||
  17022. material.isMeshToonMaterial ||
  17023. material.isMeshLambertMaterial ||
  17024. material.isMeshBasicMaterial ||
  17025. material.isMeshStandardMaterial ||
  17026. material.isShaderMaterial ) {
  17027. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17028. }
  17029. if ( material.isMeshPhongMaterial ||
  17030. material.isMeshToonMaterial ||
  17031. material.isMeshLambertMaterial ||
  17032. material.isMeshBasicMaterial ||
  17033. material.isMeshStandardMaterial ||
  17034. material.isShaderMaterial ||
  17035. material.isShadowMaterial ||
  17036. object.isSkinnedMesh ) {
  17037. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17038. }
  17039. }
  17040. // skinning and morph target uniforms must be set even if material didn't change
  17041. // auto-setting of texture unit for bone and morph texture must go before other textures
  17042. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17043. if ( object.isSkinnedMesh ) {
  17044. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17045. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17046. const skeleton = object.skeleton;
  17047. if ( skeleton ) {
  17048. if ( capabilities.floatVertexTextures ) {
  17049. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17050. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17051. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17052. } else {
  17053. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17054. }
  17055. }
  17056. }
  17057. const morphAttributes = geometry.morphAttributes;
  17058. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17059. morphtargets.update( object, geometry, material, program );
  17060. }
  17061. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17062. materialProperties.receiveShadow = object.receiveShadow;
  17063. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17064. }
  17065. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17066. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17067. m_uniforms.envMap.value = envMap;
  17068. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17069. }
  17070. if ( refreshMaterial ) {
  17071. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17072. if ( materialProperties.needsLights ) {
  17073. // the current material requires lighting info
  17074. // note: all lighting uniforms are always set correctly
  17075. // they simply reference the renderer's state for their
  17076. // values
  17077. //
  17078. // use the current material's .needsUpdate flags to set
  17079. // the GL state when required
  17080. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17081. }
  17082. // refresh uniforms common to several materials
  17083. if ( fog && material.fog === true ) {
  17084. materials.refreshFogUniforms( m_uniforms, fog );
  17085. }
  17086. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17087. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17088. }
  17089. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17090. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17091. material.uniformsNeedUpdate = false;
  17092. }
  17093. if ( material.isSpriteMaterial ) {
  17094. p_uniforms.setValue( _gl, 'center', object.center );
  17095. }
  17096. // common matrices
  17097. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17098. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17099. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17100. // UBOs
  17101. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17102. const groups = material.uniformsGroups;
  17103. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17104. if ( capabilities.isWebGL2 ) {
  17105. const group = groups[ i ];
  17106. uniformsGroups.update( group, program );
  17107. uniformsGroups.bind( group, program );
  17108. } else {
  17109. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17110. }
  17111. }
  17112. }
  17113. return program;
  17114. }
  17115. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17116. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17117. uniforms.ambientLightColor.needsUpdate = value;
  17118. uniforms.lightProbe.needsUpdate = value;
  17119. uniforms.directionalLights.needsUpdate = value;
  17120. uniforms.directionalLightShadows.needsUpdate = value;
  17121. uniforms.pointLights.needsUpdate = value;
  17122. uniforms.pointLightShadows.needsUpdate = value;
  17123. uniforms.spotLights.needsUpdate = value;
  17124. uniforms.spotLightShadows.needsUpdate = value;
  17125. uniforms.rectAreaLights.needsUpdate = value;
  17126. uniforms.hemisphereLights.needsUpdate = value;
  17127. }
  17128. function materialNeedsLights( material ) {
  17129. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17130. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17131. ( material.isShaderMaterial && material.lights === true );
  17132. }
  17133. this.getActiveCubeFace = function () {
  17134. return _currentActiveCubeFace;
  17135. };
  17136. this.getActiveMipmapLevel = function () {
  17137. return _currentActiveMipmapLevel;
  17138. };
  17139. this.getRenderTarget = function () {
  17140. return _currentRenderTarget;
  17141. };
  17142. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17143. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17144. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17145. const renderTargetProperties = properties.get( renderTarget );
  17146. renderTargetProperties.__hasExternalTextures = true;
  17147. if ( renderTargetProperties.__hasExternalTextures ) {
  17148. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17149. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17150. // The multisample_render_to_texture extension doesn't work properly if there
  17151. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17152. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17153. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17154. renderTargetProperties.__useRenderToTexture = false;
  17155. }
  17156. }
  17157. }
  17158. };
  17159. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17160. const renderTargetProperties = properties.get( renderTarget );
  17161. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17162. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17163. };
  17164. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17165. _currentRenderTarget = renderTarget;
  17166. _currentActiveCubeFace = activeCubeFace;
  17167. _currentActiveMipmapLevel = activeMipmapLevel;
  17168. let useDefaultFramebuffer = true;
  17169. let framebuffer = null;
  17170. let isCube = false;
  17171. let isRenderTarget3D = false;
  17172. if ( renderTarget ) {
  17173. const renderTargetProperties = properties.get( renderTarget );
  17174. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17175. // We need to make sure to rebind the framebuffer.
  17176. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17177. useDefaultFramebuffer = false;
  17178. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17179. textures.setupRenderTarget( renderTarget );
  17180. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17181. // Color and depth texture must be rebound in order for the swapchain to update.
  17182. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17183. }
  17184. const texture = renderTarget.texture;
  17185. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17186. isRenderTarget3D = true;
  17187. }
  17188. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17189. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17190. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17191. isCube = true;
  17192. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17193. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17194. } else {
  17195. framebuffer = __webglFramebuffer;
  17196. }
  17197. _currentViewport.copy( renderTarget.viewport );
  17198. _currentScissor.copy( renderTarget.scissor );
  17199. _currentScissorTest = renderTarget.scissorTest;
  17200. } else {
  17201. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17202. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17203. _currentScissorTest = _scissorTest;
  17204. }
  17205. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17206. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17207. state.drawBuffers( renderTarget, framebuffer );
  17208. }
  17209. state.viewport( _currentViewport );
  17210. state.scissor( _currentScissor );
  17211. state.setScissorTest( _currentScissorTest );
  17212. if ( isCube ) {
  17213. const textureProperties = properties.get( renderTarget.texture );
  17214. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17215. } else if ( isRenderTarget3D ) {
  17216. const textureProperties = properties.get( renderTarget.texture );
  17217. const layer = activeCubeFace || 0;
  17218. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17219. }
  17220. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17221. };
  17222. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17223. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17224. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17225. return;
  17226. }
  17227. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17228. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17229. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17230. }
  17231. if ( framebuffer ) {
  17232. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17233. try {
  17234. const texture = renderTarget.texture;
  17235. const textureFormat = texture.format;
  17236. const textureType = texture.type;
  17237. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17238. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17239. return;
  17240. }
  17241. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17242. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17243. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17244. ! halfFloatSupportedByExt ) {
  17245. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17246. return;
  17247. }
  17248. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17249. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17250. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17251. }
  17252. } finally {
  17253. // restore framebuffer of current render target if necessary
  17254. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17255. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17256. }
  17257. }
  17258. };
  17259. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17260. const levelScale = Math.pow( 2, - level );
  17261. const width = Math.floor( texture.image.width * levelScale );
  17262. const height = Math.floor( texture.image.height * levelScale );
  17263. textures.setTexture2D( texture, 0 );
  17264. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17265. state.unbindTexture();
  17266. };
  17267. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17268. const width = srcTexture.image.width;
  17269. const height = srcTexture.image.height;
  17270. const glFormat = utils.convert( dstTexture.format );
  17271. const glType = utils.convert( dstTexture.type );
  17272. textures.setTexture2D( dstTexture, 0 );
  17273. // As another texture upload may have changed pixelStorei
  17274. // parameters, make sure they are correct for the dstTexture
  17275. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17276. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17277. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17278. if ( srcTexture.isDataTexture ) {
  17279. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17280. } else {
  17281. if ( srcTexture.isCompressedTexture ) {
  17282. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17283. } else {
  17284. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17285. }
  17286. }
  17287. // Generate mipmaps only when copying level 0
  17288. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17289. state.unbindTexture();
  17290. };
  17291. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17292. if ( _this.isWebGL1Renderer ) {
  17293. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17294. return;
  17295. }
  17296. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17297. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17298. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17299. const glFormat = utils.convert( dstTexture.format );
  17300. const glType = utils.convert( dstTexture.type );
  17301. let glTarget;
  17302. if ( dstTexture.isData3DTexture ) {
  17303. textures.setTexture3D( dstTexture, 0 );
  17304. glTarget = _gl.TEXTURE_3D;
  17305. } else if ( dstTexture.isDataArrayTexture ) {
  17306. textures.setTexture2DArray( dstTexture, 0 );
  17307. glTarget = _gl.TEXTURE_2D_ARRAY;
  17308. } else {
  17309. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17310. return;
  17311. }
  17312. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17313. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17314. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17315. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17316. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17317. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17318. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17319. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17320. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17321. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17322. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17323. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17324. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17325. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17326. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17327. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17328. } else {
  17329. if ( srcTexture.isCompressedArrayTexture ) {
  17330. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17331. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17332. } else {
  17333. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17334. }
  17335. }
  17336. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17337. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17338. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17339. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17340. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17341. // Generate mipmaps only when copying level 0
  17342. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17343. state.unbindTexture();
  17344. };
  17345. this.initTexture = function ( texture ) {
  17346. if ( texture.isCubeTexture ) {
  17347. textures.setTextureCube( texture, 0 );
  17348. } else if ( texture.isData3DTexture ) {
  17349. textures.setTexture3D( texture, 0 );
  17350. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17351. textures.setTexture2DArray( texture, 0 );
  17352. } else {
  17353. textures.setTexture2D( texture, 0 );
  17354. }
  17355. state.unbindTexture();
  17356. };
  17357. this.resetState = function () {
  17358. _currentActiveCubeFace = 0;
  17359. _currentActiveMipmapLevel = 0;
  17360. _currentRenderTarget = null;
  17361. state.reset();
  17362. bindingStates.reset();
  17363. };
  17364. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17365. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17366. }
  17367. }
  17368. class WebGL1Renderer extends WebGLRenderer {}
  17369. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17370. class FogExp2 {
  17371. constructor( color, density = 0.00025 ) {
  17372. this.isFogExp2 = true;
  17373. this.name = '';
  17374. this.color = new Color( color );
  17375. this.density = density;
  17376. }
  17377. clone() {
  17378. return new FogExp2( this.color, this.density );
  17379. }
  17380. toJSON( /* meta */ ) {
  17381. return {
  17382. type: 'FogExp2',
  17383. color: this.color.getHex(),
  17384. density: this.density
  17385. };
  17386. }
  17387. }
  17388. class Fog {
  17389. constructor( color, near = 1, far = 1000 ) {
  17390. this.isFog = true;
  17391. this.name = '';
  17392. this.color = new Color( color );
  17393. this.near = near;
  17394. this.far = far;
  17395. }
  17396. clone() {
  17397. return new Fog( this.color, this.near, this.far );
  17398. }
  17399. toJSON( /* meta */ ) {
  17400. return {
  17401. type: 'Fog',
  17402. color: this.color.getHex(),
  17403. near: this.near,
  17404. far: this.far
  17405. };
  17406. }
  17407. }
  17408. class Scene extends Object3D {
  17409. constructor() {
  17410. super();
  17411. this.isScene = true;
  17412. this.type = 'Scene';
  17413. this.background = null;
  17414. this.environment = null;
  17415. this.fog = null;
  17416. this.backgroundBlurriness = 0;
  17417. this.backgroundIntensity = 1;
  17418. this.overrideMaterial = null;
  17419. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17420. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17421. }
  17422. }
  17423. copy( source, recursive ) {
  17424. super.copy( source, recursive );
  17425. if ( source.background !== null ) this.background = source.background.clone();
  17426. if ( source.environment !== null ) this.environment = source.environment.clone();
  17427. if ( source.fog !== null ) this.fog = source.fog.clone();
  17428. this.backgroundBlurriness = source.backgroundBlurriness;
  17429. this.backgroundIntensity = source.backgroundIntensity;
  17430. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17431. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17432. return this;
  17433. }
  17434. toJSON( meta ) {
  17435. const data = super.toJSON( meta );
  17436. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17437. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17438. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17439. return data;
  17440. }
  17441. // @deprecated
  17442. get autoUpdate() {
  17443. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17444. return this.matrixWorldAutoUpdate;
  17445. }
  17446. set autoUpdate( value ) {
  17447. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17448. this.matrixWorldAutoUpdate = value;
  17449. }
  17450. }
  17451. class InterleavedBuffer {
  17452. constructor( array, stride ) {
  17453. this.isInterleavedBuffer = true;
  17454. this.array = array;
  17455. this.stride = stride;
  17456. this.count = array !== undefined ? array.length / stride : 0;
  17457. this.usage = StaticDrawUsage;
  17458. this.updateRange = { offset: 0, count: - 1 };
  17459. this.version = 0;
  17460. this.uuid = generateUUID();
  17461. }
  17462. onUploadCallback() {}
  17463. set needsUpdate( value ) {
  17464. if ( value === true ) this.version ++;
  17465. }
  17466. setUsage( value ) {
  17467. this.usage = value;
  17468. return this;
  17469. }
  17470. copy( source ) {
  17471. this.array = new source.array.constructor( source.array );
  17472. this.count = source.count;
  17473. this.stride = source.stride;
  17474. this.usage = source.usage;
  17475. return this;
  17476. }
  17477. copyAt( index1, attribute, index2 ) {
  17478. index1 *= this.stride;
  17479. index2 *= attribute.stride;
  17480. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17481. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17482. }
  17483. return this;
  17484. }
  17485. set( value, offset = 0 ) {
  17486. this.array.set( value, offset );
  17487. return this;
  17488. }
  17489. clone( data ) {
  17490. if ( data.arrayBuffers === undefined ) {
  17491. data.arrayBuffers = {};
  17492. }
  17493. if ( this.array.buffer._uuid === undefined ) {
  17494. this.array.buffer._uuid = generateUUID();
  17495. }
  17496. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17497. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17498. }
  17499. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17500. const ib = new this.constructor( array, this.stride );
  17501. ib.setUsage( this.usage );
  17502. return ib;
  17503. }
  17504. onUpload( callback ) {
  17505. this.onUploadCallback = callback;
  17506. return this;
  17507. }
  17508. toJSON( data ) {
  17509. if ( data.arrayBuffers === undefined ) {
  17510. data.arrayBuffers = {};
  17511. }
  17512. // generate UUID for array buffer if necessary
  17513. if ( this.array.buffer._uuid === undefined ) {
  17514. this.array.buffer._uuid = generateUUID();
  17515. }
  17516. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17517. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17518. }
  17519. //
  17520. return {
  17521. uuid: this.uuid,
  17522. buffer: this.array.buffer._uuid,
  17523. type: this.array.constructor.name,
  17524. stride: this.stride
  17525. };
  17526. }
  17527. }
  17528. const _vector$6 = /*@__PURE__*/ new Vector3();
  17529. class InterleavedBufferAttribute {
  17530. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17531. this.isInterleavedBufferAttribute = true;
  17532. this.name = '';
  17533. this.data = interleavedBuffer;
  17534. this.itemSize = itemSize;
  17535. this.offset = offset;
  17536. this.normalized = normalized;
  17537. }
  17538. get count() {
  17539. return this.data.count;
  17540. }
  17541. get array() {
  17542. return this.data.array;
  17543. }
  17544. set needsUpdate( value ) {
  17545. this.data.needsUpdate = value;
  17546. }
  17547. applyMatrix4( m ) {
  17548. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17549. _vector$6.fromBufferAttribute( this, i );
  17550. _vector$6.applyMatrix4( m );
  17551. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17552. }
  17553. return this;
  17554. }
  17555. applyNormalMatrix( m ) {
  17556. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17557. _vector$6.fromBufferAttribute( this, i );
  17558. _vector$6.applyNormalMatrix( m );
  17559. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17560. }
  17561. return this;
  17562. }
  17563. transformDirection( m ) {
  17564. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17565. _vector$6.fromBufferAttribute( this, i );
  17566. _vector$6.transformDirection( m );
  17567. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17568. }
  17569. return this;
  17570. }
  17571. setX( index, x ) {
  17572. if ( this.normalized ) x = normalize( x, this.array );
  17573. this.data.array[ index * this.data.stride + this.offset ] = x;
  17574. return this;
  17575. }
  17576. setY( index, y ) {
  17577. if ( this.normalized ) y = normalize( y, this.array );
  17578. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17579. return this;
  17580. }
  17581. setZ( index, z ) {
  17582. if ( this.normalized ) z = normalize( z, this.array );
  17583. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17584. return this;
  17585. }
  17586. setW( index, w ) {
  17587. if ( this.normalized ) w = normalize( w, this.array );
  17588. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17589. return this;
  17590. }
  17591. getX( index ) {
  17592. let x = this.data.array[ index * this.data.stride + this.offset ];
  17593. if ( this.normalized ) x = denormalize( x, this.array );
  17594. return x;
  17595. }
  17596. getY( index ) {
  17597. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17598. if ( this.normalized ) y = denormalize( y, this.array );
  17599. return y;
  17600. }
  17601. getZ( index ) {
  17602. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17603. if ( this.normalized ) z = denormalize( z, this.array );
  17604. return z;
  17605. }
  17606. getW( index ) {
  17607. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17608. if ( this.normalized ) w = denormalize( w, this.array );
  17609. return w;
  17610. }
  17611. setXY( index, x, y ) {
  17612. index = index * this.data.stride + this.offset;
  17613. if ( this.normalized ) {
  17614. x = normalize( x, this.array );
  17615. y = normalize( y, this.array );
  17616. }
  17617. this.data.array[ index + 0 ] = x;
  17618. this.data.array[ index + 1 ] = y;
  17619. return this;
  17620. }
  17621. setXYZ( index, x, y, z ) {
  17622. index = index * this.data.stride + this.offset;
  17623. if ( this.normalized ) {
  17624. x = normalize( x, this.array );
  17625. y = normalize( y, this.array );
  17626. z = normalize( z, this.array );
  17627. }
  17628. this.data.array[ index + 0 ] = x;
  17629. this.data.array[ index + 1 ] = y;
  17630. this.data.array[ index + 2 ] = z;
  17631. return this;
  17632. }
  17633. setXYZW( index, x, y, z, w ) {
  17634. index = index * this.data.stride + this.offset;
  17635. if ( this.normalized ) {
  17636. x = normalize( x, this.array );
  17637. y = normalize( y, this.array );
  17638. z = normalize( z, this.array );
  17639. w = normalize( w, this.array );
  17640. }
  17641. this.data.array[ index + 0 ] = x;
  17642. this.data.array[ index + 1 ] = y;
  17643. this.data.array[ index + 2 ] = z;
  17644. this.data.array[ index + 3 ] = w;
  17645. return this;
  17646. }
  17647. clone( data ) {
  17648. if ( data === undefined ) {
  17649. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17650. const array = [];
  17651. for ( let i = 0; i < this.count; i ++ ) {
  17652. const index = i * this.data.stride + this.offset;
  17653. for ( let j = 0; j < this.itemSize; j ++ ) {
  17654. array.push( this.data.array[ index + j ] );
  17655. }
  17656. }
  17657. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17658. } else {
  17659. if ( data.interleavedBuffers === undefined ) {
  17660. data.interleavedBuffers = {};
  17661. }
  17662. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17663. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17664. }
  17665. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17666. }
  17667. }
  17668. toJSON( data ) {
  17669. if ( data === undefined ) {
  17670. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17671. const array = [];
  17672. for ( let i = 0; i < this.count; i ++ ) {
  17673. const index = i * this.data.stride + this.offset;
  17674. for ( let j = 0; j < this.itemSize; j ++ ) {
  17675. array.push( this.data.array[ index + j ] );
  17676. }
  17677. }
  17678. // de-interleave data and save it as an ordinary buffer attribute for now
  17679. return {
  17680. itemSize: this.itemSize,
  17681. type: this.array.constructor.name,
  17682. array: array,
  17683. normalized: this.normalized
  17684. };
  17685. } else {
  17686. // save as true interleaved attribute
  17687. if ( data.interleavedBuffers === undefined ) {
  17688. data.interleavedBuffers = {};
  17689. }
  17690. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17691. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17692. }
  17693. return {
  17694. isInterleavedBufferAttribute: true,
  17695. itemSize: this.itemSize,
  17696. data: this.data.uuid,
  17697. offset: this.offset,
  17698. normalized: this.normalized
  17699. };
  17700. }
  17701. }
  17702. }
  17703. class SpriteMaterial extends Material {
  17704. constructor( parameters ) {
  17705. super();
  17706. this.isSpriteMaterial = true;
  17707. this.type = 'SpriteMaterial';
  17708. this.color = new Color( 0xffffff );
  17709. this.map = null;
  17710. this.alphaMap = null;
  17711. this.rotation = 0;
  17712. this.sizeAttenuation = true;
  17713. this.transparent = true;
  17714. this.fog = true;
  17715. this.setValues( parameters );
  17716. }
  17717. copy( source ) {
  17718. super.copy( source );
  17719. this.color.copy( source.color );
  17720. this.map = source.map;
  17721. this.alphaMap = source.alphaMap;
  17722. this.rotation = source.rotation;
  17723. this.sizeAttenuation = source.sizeAttenuation;
  17724. this.fog = source.fog;
  17725. return this;
  17726. }
  17727. }
  17728. let _geometry;
  17729. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17730. const _worldScale = /*@__PURE__*/ new Vector3();
  17731. const _mvPosition = /*@__PURE__*/ new Vector3();
  17732. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17733. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17734. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17735. const _vA = /*@__PURE__*/ new Vector3();
  17736. const _vB = /*@__PURE__*/ new Vector3();
  17737. const _vC = /*@__PURE__*/ new Vector3();
  17738. const _uvA = /*@__PURE__*/ new Vector2();
  17739. const _uvB = /*@__PURE__*/ new Vector2();
  17740. const _uvC = /*@__PURE__*/ new Vector2();
  17741. class Sprite extends Object3D {
  17742. constructor( material ) {
  17743. super();
  17744. this.isSprite = true;
  17745. this.type = 'Sprite';
  17746. if ( _geometry === undefined ) {
  17747. _geometry = new BufferGeometry();
  17748. const float32Array = new Float32Array( [
  17749. - 0.5, - 0.5, 0, 0, 0,
  17750. 0.5, - 0.5, 0, 1, 0,
  17751. 0.5, 0.5, 0, 1, 1,
  17752. - 0.5, 0.5, 0, 0, 1
  17753. ] );
  17754. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17755. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17756. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17757. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17758. }
  17759. this.geometry = _geometry;
  17760. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17761. this.center = new Vector2( 0.5, 0.5 );
  17762. }
  17763. raycast( raycaster, intersects ) {
  17764. if ( raycaster.camera === null ) {
  17765. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17766. }
  17767. _worldScale.setFromMatrixScale( this.matrixWorld );
  17768. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17769. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17770. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17771. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17772. _worldScale.multiplyScalar( - _mvPosition.z );
  17773. }
  17774. const rotation = this.material.rotation;
  17775. let sin, cos;
  17776. if ( rotation !== 0 ) {
  17777. cos = Math.cos( rotation );
  17778. sin = Math.sin( rotation );
  17779. }
  17780. const center = this.center;
  17781. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17782. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17783. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17784. _uvA.set( 0, 0 );
  17785. _uvB.set( 1, 0 );
  17786. _uvC.set( 1, 1 );
  17787. // check first triangle
  17788. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17789. if ( intersect === null ) {
  17790. // check second triangle
  17791. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17792. _uvB.set( 0, 1 );
  17793. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17794. if ( intersect === null ) {
  17795. return;
  17796. }
  17797. }
  17798. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17799. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17800. intersects.push( {
  17801. distance: distance,
  17802. point: _intersectPoint.clone(),
  17803. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17804. face: null,
  17805. object: this
  17806. } );
  17807. }
  17808. copy( source, recursive ) {
  17809. super.copy( source, recursive );
  17810. if ( source.center !== undefined ) this.center.copy( source.center );
  17811. this.material = source.material;
  17812. return this;
  17813. }
  17814. }
  17815. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17816. // compute position in camera space
  17817. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17818. // to check if rotation is not zero
  17819. if ( sin !== undefined ) {
  17820. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17821. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17822. } else {
  17823. _rotatedPosition.copy( _alignedPosition );
  17824. }
  17825. vertexPosition.copy( mvPosition );
  17826. vertexPosition.x += _rotatedPosition.x;
  17827. vertexPosition.y += _rotatedPosition.y;
  17828. // transform to world space
  17829. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17830. }
  17831. const _v1$2 = /*@__PURE__*/ new Vector3();
  17832. const _v2$1 = /*@__PURE__*/ new Vector3();
  17833. class LOD extends Object3D {
  17834. constructor() {
  17835. super();
  17836. this._currentLevel = 0;
  17837. this.type = 'LOD';
  17838. Object.defineProperties( this, {
  17839. levels: {
  17840. enumerable: true,
  17841. value: []
  17842. },
  17843. isLOD: {
  17844. value: true,
  17845. }
  17846. } );
  17847. this.autoUpdate = true;
  17848. }
  17849. copy( source ) {
  17850. super.copy( source, false );
  17851. const levels = source.levels;
  17852. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17853. const level = levels[ i ];
  17854. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17855. }
  17856. this.autoUpdate = source.autoUpdate;
  17857. return this;
  17858. }
  17859. addLevel( object, distance = 0, hysteresis = 0 ) {
  17860. distance = Math.abs( distance );
  17861. const levels = this.levels;
  17862. let l;
  17863. for ( l = 0; l < levels.length; l ++ ) {
  17864. if ( distance < levels[ l ].distance ) {
  17865. break;
  17866. }
  17867. }
  17868. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17869. this.add( object );
  17870. return this;
  17871. }
  17872. getCurrentLevel() {
  17873. return this._currentLevel;
  17874. }
  17875. getObjectForDistance( distance ) {
  17876. const levels = this.levels;
  17877. if ( levels.length > 0 ) {
  17878. let i, l;
  17879. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17880. let levelDistance = levels[ i ].distance;
  17881. if ( levels[ i ].object.visible ) {
  17882. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17883. }
  17884. if ( distance < levelDistance ) {
  17885. break;
  17886. }
  17887. }
  17888. return levels[ i - 1 ].object;
  17889. }
  17890. return null;
  17891. }
  17892. raycast( raycaster, intersects ) {
  17893. const levels = this.levels;
  17894. if ( levels.length > 0 ) {
  17895. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17896. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17897. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17898. }
  17899. }
  17900. update( camera ) {
  17901. const levels = this.levels;
  17902. if ( levels.length > 1 ) {
  17903. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17904. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17905. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17906. levels[ 0 ].object.visible = true;
  17907. let i, l;
  17908. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17909. let levelDistance = levels[ i ].distance;
  17910. if ( levels[ i ].object.visible ) {
  17911. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17912. }
  17913. if ( distance >= levelDistance ) {
  17914. levels[ i - 1 ].object.visible = false;
  17915. levels[ i ].object.visible = true;
  17916. } else {
  17917. break;
  17918. }
  17919. }
  17920. this._currentLevel = i - 1;
  17921. for ( ; i < l; i ++ ) {
  17922. levels[ i ].object.visible = false;
  17923. }
  17924. }
  17925. }
  17926. toJSON( meta ) {
  17927. const data = super.toJSON( meta );
  17928. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17929. data.object.levels = [];
  17930. const levels = this.levels;
  17931. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17932. const level = levels[ i ];
  17933. data.object.levels.push( {
  17934. object: level.object.uuid,
  17935. distance: level.distance,
  17936. hysteresis: level.hysteresis
  17937. } );
  17938. }
  17939. return data;
  17940. }
  17941. }
  17942. const _basePosition = /*@__PURE__*/ new Vector3();
  17943. const _skinIndex = /*@__PURE__*/ new Vector4();
  17944. const _skinWeight = /*@__PURE__*/ new Vector4();
  17945. const _vector$5 = /*@__PURE__*/ new Vector3();
  17946. const _matrix = /*@__PURE__*/ new Matrix4();
  17947. class SkinnedMesh extends Mesh {
  17948. constructor( geometry, material ) {
  17949. super( geometry, material );
  17950. this.isSkinnedMesh = true;
  17951. this.type = 'SkinnedMesh';
  17952. this.bindMode = 'attached';
  17953. this.bindMatrix = new Matrix4();
  17954. this.bindMatrixInverse = new Matrix4();
  17955. }
  17956. copy( source, recursive ) {
  17957. super.copy( source, recursive );
  17958. this.bindMode = source.bindMode;
  17959. this.bindMatrix.copy( source.bindMatrix );
  17960. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17961. this.skeleton = source.skeleton;
  17962. return this;
  17963. }
  17964. bind( skeleton, bindMatrix ) {
  17965. this.skeleton = skeleton;
  17966. if ( bindMatrix === undefined ) {
  17967. this.updateMatrixWorld( true );
  17968. this.skeleton.calculateInverses();
  17969. bindMatrix = this.matrixWorld;
  17970. }
  17971. this.bindMatrix.copy( bindMatrix );
  17972. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17973. }
  17974. pose() {
  17975. this.skeleton.pose();
  17976. }
  17977. normalizeSkinWeights() {
  17978. const vector = new Vector4();
  17979. const skinWeight = this.geometry.attributes.skinWeight;
  17980. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17981. vector.fromBufferAttribute( skinWeight, i );
  17982. const scale = 1.0 / vector.manhattanLength();
  17983. if ( scale !== Infinity ) {
  17984. vector.multiplyScalar( scale );
  17985. } else {
  17986. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17987. }
  17988. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17989. }
  17990. }
  17991. updateMatrixWorld( force ) {
  17992. super.updateMatrixWorld( force );
  17993. if ( this.bindMode === 'attached' ) {
  17994. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17995. } else if ( this.bindMode === 'detached' ) {
  17996. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17997. } else {
  17998. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17999. }
  18000. }
  18001. boneTransform( index, target ) {
  18002. const skeleton = this.skeleton;
  18003. const geometry = this.geometry;
  18004. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18005. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18006. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18007. target.set( 0, 0, 0 );
  18008. for ( let i = 0; i < 4; i ++ ) {
  18009. const weight = _skinWeight.getComponent( i );
  18010. if ( weight !== 0 ) {
  18011. const boneIndex = _skinIndex.getComponent( i );
  18012. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18013. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18014. }
  18015. }
  18016. return target.applyMatrix4( this.bindMatrixInverse );
  18017. }
  18018. }
  18019. class Bone extends Object3D {
  18020. constructor() {
  18021. super();
  18022. this.isBone = true;
  18023. this.type = 'Bone';
  18024. }
  18025. }
  18026. class DataTexture extends Texture {
  18027. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18028. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18029. this.isDataTexture = true;
  18030. this.image = { data: data, width: width, height: height };
  18031. this.generateMipmaps = false;
  18032. this.flipY = false;
  18033. this.unpackAlignment = 1;
  18034. }
  18035. }
  18036. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18037. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18038. class Skeleton {
  18039. constructor( bones = [], boneInverses = [] ) {
  18040. this.uuid = generateUUID();
  18041. this.bones = bones.slice( 0 );
  18042. this.boneInverses = boneInverses;
  18043. this.boneMatrices = null;
  18044. this.boneTexture = null;
  18045. this.boneTextureSize = 0;
  18046. this.frame = - 1;
  18047. this.init();
  18048. }
  18049. init() {
  18050. const bones = this.bones;
  18051. const boneInverses = this.boneInverses;
  18052. this.boneMatrices = new Float32Array( bones.length * 16 );
  18053. // calculate inverse bone matrices if necessary
  18054. if ( boneInverses.length === 0 ) {
  18055. this.calculateInverses();
  18056. } else {
  18057. // handle special case
  18058. if ( bones.length !== boneInverses.length ) {
  18059. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18060. this.boneInverses = [];
  18061. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18062. this.boneInverses.push( new Matrix4() );
  18063. }
  18064. }
  18065. }
  18066. }
  18067. calculateInverses() {
  18068. this.boneInverses.length = 0;
  18069. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18070. const inverse = new Matrix4();
  18071. if ( this.bones[ i ] ) {
  18072. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18073. }
  18074. this.boneInverses.push( inverse );
  18075. }
  18076. }
  18077. pose() {
  18078. // recover the bind-time world matrices
  18079. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18080. const bone = this.bones[ i ];
  18081. if ( bone ) {
  18082. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18083. }
  18084. }
  18085. // compute the local matrices, positions, rotations and scales
  18086. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18087. const bone = this.bones[ i ];
  18088. if ( bone ) {
  18089. if ( bone.parent && bone.parent.isBone ) {
  18090. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18091. bone.matrix.multiply( bone.matrixWorld );
  18092. } else {
  18093. bone.matrix.copy( bone.matrixWorld );
  18094. }
  18095. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18096. }
  18097. }
  18098. }
  18099. update() {
  18100. const bones = this.bones;
  18101. const boneInverses = this.boneInverses;
  18102. const boneMatrices = this.boneMatrices;
  18103. const boneTexture = this.boneTexture;
  18104. // flatten bone matrices to array
  18105. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18106. // compute the offset between the current and the original transform
  18107. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18108. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18109. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18110. }
  18111. if ( boneTexture !== null ) {
  18112. boneTexture.needsUpdate = true;
  18113. }
  18114. }
  18115. clone() {
  18116. return new Skeleton( this.bones, this.boneInverses );
  18117. }
  18118. computeBoneTexture() {
  18119. // layout (1 matrix = 4 pixels)
  18120. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18121. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18122. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18123. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18124. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18125. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18126. size = ceilPowerOfTwo( size );
  18127. size = Math.max( size, 4 );
  18128. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18129. boneMatrices.set( this.boneMatrices ); // copy current values
  18130. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18131. boneTexture.needsUpdate = true;
  18132. this.boneMatrices = boneMatrices;
  18133. this.boneTexture = boneTexture;
  18134. this.boneTextureSize = size;
  18135. return this;
  18136. }
  18137. getBoneByName( name ) {
  18138. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18139. const bone = this.bones[ i ];
  18140. if ( bone.name === name ) {
  18141. return bone;
  18142. }
  18143. }
  18144. return undefined;
  18145. }
  18146. dispose( ) {
  18147. if ( this.boneTexture !== null ) {
  18148. this.boneTexture.dispose();
  18149. this.boneTexture = null;
  18150. }
  18151. }
  18152. fromJSON( json, bones ) {
  18153. this.uuid = json.uuid;
  18154. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18155. const uuid = json.bones[ i ];
  18156. let bone = bones[ uuid ];
  18157. if ( bone === undefined ) {
  18158. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18159. bone = new Bone();
  18160. }
  18161. this.bones.push( bone );
  18162. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18163. }
  18164. this.init();
  18165. return this;
  18166. }
  18167. toJSON() {
  18168. const data = {
  18169. metadata: {
  18170. version: 4.5,
  18171. type: 'Skeleton',
  18172. generator: 'Skeleton.toJSON'
  18173. },
  18174. bones: [],
  18175. boneInverses: []
  18176. };
  18177. data.uuid = this.uuid;
  18178. const bones = this.bones;
  18179. const boneInverses = this.boneInverses;
  18180. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18181. const bone = bones[ i ];
  18182. data.bones.push( bone.uuid );
  18183. const boneInverse = boneInverses[ i ];
  18184. data.boneInverses.push( boneInverse.toArray() );
  18185. }
  18186. return data;
  18187. }
  18188. }
  18189. class InstancedBufferAttribute extends BufferAttribute {
  18190. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18191. super( array, itemSize, normalized );
  18192. this.isInstancedBufferAttribute = true;
  18193. this.meshPerAttribute = meshPerAttribute;
  18194. }
  18195. copy( source ) {
  18196. super.copy( source );
  18197. this.meshPerAttribute = source.meshPerAttribute;
  18198. return this;
  18199. }
  18200. toJSON() {
  18201. const data = super.toJSON();
  18202. data.meshPerAttribute = this.meshPerAttribute;
  18203. data.isInstancedBufferAttribute = true;
  18204. return data;
  18205. }
  18206. }
  18207. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18208. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18209. const _instanceIntersects = [];
  18210. const _identity = /*@__PURE__*/ new Matrix4();
  18211. const _mesh = /*@__PURE__*/ new Mesh();
  18212. class InstancedMesh extends Mesh {
  18213. constructor( geometry, material, count ) {
  18214. super( geometry, material );
  18215. this.isInstancedMesh = true;
  18216. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18217. this.instanceColor = null;
  18218. this.count = count;
  18219. this.frustumCulled = false;
  18220. for ( let i = 0; i < count; i ++ ) {
  18221. this.setMatrixAt( i, _identity );
  18222. }
  18223. }
  18224. copy( source, recursive ) {
  18225. super.copy( source, recursive );
  18226. this.instanceMatrix.copy( source.instanceMatrix );
  18227. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18228. this.count = source.count;
  18229. return this;
  18230. }
  18231. getColorAt( index, color ) {
  18232. color.fromArray( this.instanceColor.array, index * 3 );
  18233. }
  18234. getMatrixAt( index, matrix ) {
  18235. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18236. }
  18237. raycast( raycaster, intersects ) {
  18238. const matrixWorld = this.matrixWorld;
  18239. const raycastTimes = this.count;
  18240. _mesh.geometry = this.geometry;
  18241. _mesh.material = this.material;
  18242. if ( _mesh.material === undefined ) return;
  18243. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18244. // calculate the world matrix for each instance
  18245. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18246. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18247. // the mesh represents this single instance
  18248. _mesh.matrixWorld = _instanceWorldMatrix;
  18249. _mesh.raycast( raycaster, _instanceIntersects );
  18250. // process the result of raycast
  18251. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18252. const intersect = _instanceIntersects[ i ];
  18253. intersect.instanceId = instanceId;
  18254. intersect.object = this;
  18255. intersects.push( intersect );
  18256. }
  18257. _instanceIntersects.length = 0;
  18258. }
  18259. }
  18260. setColorAt( index, color ) {
  18261. if ( this.instanceColor === null ) {
  18262. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18263. }
  18264. color.toArray( this.instanceColor.array, index * 3 );
  18265. }
  18266. setMatrixAt( index, matrix ) {
  18267. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18268. }
  18269. updateMorphTargets() {
  18270. }
  18271. dispose() {
  18272. this.dispatchEvent( { type: 'dispose' } );
  18273. }
  18274. }
  18275. class LineBasicMaterial extends Material {
  18276. constructor( parameters ) {
  18277. super();
  18278. this.isLineBasicMaterial = true;
  18279. this.type = 'LineBasicMaterial';
  18280. this.color = new Color( 0xffffff );
  18281. this.linewidth = 1;
  18282. this.linecap = 'round';
  18283. this.linejoin = 'round';
  18284. this.fog = true;
  18285. this.setValues( parameters );
  18286. }
  18287. copy( source ) {
  18288. super.copy( source );
  18289. this.color.copy( source.color );
  18290. this.linewidth = source.linewidth;
  18291. this.linecap = source.linecap;
  18292. this.linejoin = source.linejoin;
  18293. this.fog = source.fog;
  18294. return this;
  18295. }
  18296. }
  18297. const _start$1 = /*@__PURE__*/ new Vector3();
  18298. const _end$1 = /*@__PURE__*/ new Vector3();
  18299. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18300. const _ray$1 = /*@__PURE__*/ new Ray();
  18301. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18302. class Line extends Object3D {
  18303. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18304. super();
  18305. this.isLine = true;
  18306. this.type = 'Line';
  18307. this.geometry = geometry;
  18308. this.material = material;
  18309. this.updateMorphTargets();
  18310. }
  18311. copy( source, recursive ) {
  18312. super.copy( source, recursive );
  18313. this.material = source.material;
  18314. this.geometry = source.geometry;
  18315. return this;
  18316. }
  18317. computeLineDistances() {
  18318. const geometry = this.geometry;
  18319. // we assume non-indexed geometry
  18320. if ( geometry.index === null ) {
  18321. const positionAttribute = geometry.attributes.position;
  18322. const lineDistances = [ 0 ];
  18323. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18324. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18325. _end$1.fromBufferAttribute( positionAttribute, i );
  18326. lineDistances[ i ] = lineDistances[ i - 1 ];
  18327. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18328. }
  18329. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18330. } else {
  18331. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18332. }
  18333. return this;
  18334. }
  18335. raycast( raycaster, intersects ) {
  18336. const geometry = this.geometry;
  18337. const matrixWorld = this.matrixWorld;
  18338. const threshold = raycaster.params.Line.threshold;
  18339. const drawRange = geometry.drawRange;
  18340. // Checking boundingSphere distance to ray
  18341. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18342. _sphere$1.copy( geometry.boundingSphere );
  18343. _sphere$1.applyMatrix4( matrixWorld );
  18344. _sphere$1.radius += threshold;
  18345. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18346. //
  18347. _inverseMatrix$1.copy( matrixWorld ).invert();
  18348. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18349. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18350. const localThresholdSq = localThreshold * localThreshold;
  18351. const vStart = new Vector3();
  18352. const vEnd = new Vector3();
  18353. const interSegment = new Vector3();
  18354. const interRay = new Vector3();
  18355. const step = this.isLineSegments ? 2 : 1;
  18356. const index = geometry.index;
  18357. const attributes = geometry.attributes;
  18358. const positionAttribute = attributes.position;
  18359. if ( index !== null ) {
  18360. const start = Math.max( 0, drawRange.start );
  18361. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18362. for ( let i = start, l = end - 1; i < l; i += step ) {
  18363. const a = index.getX( i );
  18364. const b = index.getX( i + 1 );
  18365. vStart.fromBufferAttribute( positionAttribute, a );
  18366. vEnd.fromBufferAttribute( positionAttribute, b );
  18367. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18368. if ( distSq > localThresholdSq ) continue;
  18369. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18370. const distance = raycaster.ray.origin.distanceTo( interRay );
  18371. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18372. intersects.push( {
  18373. distance: distance,
  18374. // What do we want? intersection point on the ray or on the segment??
  18375. // point: raycaster.ray.at( distance ),
  18376. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18377. index: i,
  18378. face: null,
  18379. faceIndex: null,
  18380. object: this
  18381. } );
  18382. }
  18383. } else {
  18384. const start = Math.max( 0, drawRange.start );
  18385. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18386. for ( let i = start, l = end - 1; i < l; i += step ) {
  18387. vStart.fromBufferAttribute( positionAttribute, i );
  18388. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18389. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18390. if ( distSq > localThresholdSq ) continue;
  18391. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18392. const distance = raycaster.ray.origin.distanceTo( interRay );
  18393. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18394. intersects.push( {
  18395. distance: distance,
  18396. // What do we want? intersection point on the ray or on the segment??
  18397. // point: raycaster.ray.at( distance ),
  18398. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18399. index: i,
  18400. face: null,
  18401. faceIndex: null,
  18402. object: this
  18403. } );
  18404. }
  18405. }
  18406. }
  18407. updateMorphTargets() {
  18408. const geometry = this.geometry;
  18409. const morphAttributes = geometry.morphAttributes;
  18410. const keys = Object.keys( morphAttributes );
  18411. if ( keys.length > 0 ) {
  18412. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18413. if ( morphAttribute !== undefined ) {
  18414. this.morphTargetInfluences = [];
  18415. this.morphTargetDictionary = {};
  18416. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18417. const name = morphAttribute[ m ].name || String( m );
  18418. this.morphTargetInfluences.push( 0 );
  18419. this.morphTargetDictionary[ name ] = m;
  18420. }
  18421. }
  18422. }
  18423. }
  18424. }
  18425. const _start = /*@__PURE__*/ new Vector3();
  18426. const _end = /*@__PURE__*/ new Vector3();
  18427. class LineSegments extends Line {
  18428. constructor( geometry, material ) {
  18429. super( geometry, material );
  18430. this.isLineSegments = true;
  18431. this.type = 'LineSegments';
  18432. }
  18433. computeLineDistances() {
  18434. const geometry = this.geometry;
  18435. // we assume non-indexed geometry
  18436. if ( geometry.index === null ) {
  18437. const positionAttribute = geometry.attributes.position;
  18438. const lineDistances = [];
  18439. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18440. _start.fromBufferAttribute( positionAttribute, i );
  18441. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18442. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18443. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18444. }
  18445. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18446. } else {
  18447. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18448. }
  18449. return this;
  18450. }
  18451. }
  18452. class LineLoop extends Line {
  18453. constructor( geometry, material ) {
  18454. super( geometry, material );
  18455. this.isLineLoop = true;
  18456. this.type = 'LineLoop';
  18457. }
  18458. }
  18459. class PointsMaterial extends Material {
  18460. constructor( parameters ) {
  18461. super();
  18462. this.isPointsMaterial = true;
  18463. this.type = 'PointsMaterial';
  18464. this.color = new Color( 0xffffff );
  18465. this.map = null;
  18466. this.alphaMap = null;
  18467. this.size = 1;
  18468. this.sizeAttenuation = true;
  18469. this.fog = true;
  18470. this.setValues( parameters );
  18471. }
  18472. copy( source ) {
  18473. super.copy( source );
  18474. this.color.copy( source.color );
  18475. this.map = source.map;
  18476. this.alphaMap = source.alphaMap;
  18477. this.size = source.size;
  18478. this.sizeAttenuation = source.sizeAttenuation;
  18479. this.fog = source.fog;
  18480. return this;
  18481. }
  18482. }
  18483. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18484. const _ray = /*@__PURE__*/ new Ray();
  18485. const _sphere = /*@__PURE__*/ new Sphere();
  18486. const _position$2 = /*@__PURE__*/ new Vector3();
  18487. class Points extends Object3D {
  18488. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18489. super();
  18490. this.isPoints = true;
  18491. this.type = 'Points';
  18492. this.geometry = geometry;
  18493. this.material = material;
  18494. this.updateMorphTargets();
  18495. }
  18496. copy( source, recursive ) {
  18497. super.copy( source, recursive );
  18498. this.material = source.material;
  18499. this.geometry = source.geometry;
  18500. return this;
  18501. }
  18502. raycast( raycaster, intersects ) {
  18503. const geometry = this.geometry;
  18504. const matrixWorld = this.matrixWorld;
  18505. const threshold = raycaster.params.Points.threshold;
  18506. const drawRange = geometry.drawRange;
  18507. // Checking boundingSphere distance to ray
  18508. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18509. _sphere.copy( geometry.boundingSphere );
  18510. _sphere.applyMatrix4( matrixWorld );
  18511. _sphere.radius += threshold;
  18512. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18513. //
  18514. _inverseMatrix.copy( matrixWorld ).invert();
  18515. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18516. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18517. const localThresholdSq = localThreshold * localThreshold;
  18518. const index = geometry.index;
  18519. const attributes = geometry.attributes;
  18520. const positionAttribute = attributes.position;
  18521. if ( index !== null ) {
  18522. const start = Math.max( 0, drawRange.start );
  18523. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18524. for ( let i = start, il = end; i < il; i ++ ) {
  18525. const a = index.getX( i );
  18526. _position$2.fromBufferAttribute( positionAttribute, a );
  18527. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18528. }
  18529. } else {
  18530. const start = Math.max( 0, drawRange.start );
  18531. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18532. for ( let i = start, l = end; i < l; i ++ ) {
  18533. _position$2.fromBufferAttribute( positionAttribute, i );
  18534. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18535. }
  18536. }
  18537. }
  18538. updateMorphTargets() {
  18539. const geometry = this.geometry;
  18540. const morphAttributes = geometry.morphAttributes;
  18541. const keys = Object.keys( morphAttributes );
  18542. if ( keys.length > 0 ) {
  18543. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18544. if ( morphAttribute !== undefined ) {
  18545. this.morphTargetInfluences = [];
  18546. this.morphTargetDictionary = {};
  18547. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18548. const name = morphAttribute[ m ].name || String( m );
  18549. this.morphTargetInfluences.push( 0 );
  18550. this.morphTargetDictionary[ name ] = m;
  18551. }
  18552. }
  18553. }
  18554. }
  18555. }
  18556. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18557. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18558. if ( rayPointDistanceSq < localThresholdSq ) {
  18559. const intersectPoint = new Vector3();
  18560. _ray.closestPointToPoint( point, intersectPoint );
  18561. intersectPoint.applyMatrix4( matrixWorld );
  18562. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18563. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18564. intersects.push( {
  18565. distance: distance,
  18566. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18567. point: intersectPoint,
  18568. index: index,
  18569. face: null,
  18570. object: object
  18571. } );
  18572. }
  18573. }
  18574. class VideoTexture extends Texture {
  18575. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18576. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18577. this.isVideoTexture = true;
  18578. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18579. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18580. this.generateMipmaps = false;
  18581. const scope = this;
  18582. function updateVideo() {
  18583. scope.needsUpdate = true;
  18584. video.requestVideoFrameCallback( updateVideo );
  18585. }
  18586. if ( 'requestVideoFrameCallback' in video ) {
  18587. video.requestVideoFrameCallback( updateVideo );
  18588. }
  18589. }
  18590. clone() {
  18591. return new this.constructor( this.image ).copy( this );
  18592. }
  18593. update() {
  18594. const video = this.image;
  18595. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18596. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18597. this.needsUpdate = true;
  18598. }
  18599. }
  18600. }
  18601. class FramebufferTexture extends Texture {
  18602. constructor( width, height, format ) {
  18603. super( { width, height } );
  18604. this.isFramebufferTexture = true;
  18605. this.format = format;
  18606. this.magFilter = NearestFilter;
  18607. this.minFilter = NearestFilter;
  18608. this.generateMipmaps = false;
  18609. this.needsUpdate = true;
  18610. }
  18611. }
  18612. class CompressedTexture extends Texture {
  18613. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18614. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18615. this.isCompressedTexture = true;
  18616. this.image = { width: width, height: height };
  18617. this.mipmaps = mipmaps;
  18618. // no flipping for cube textures
  18619. // (also flipping doesn't work for compressed textures )
  18620. this.flipY = false;
  18621. // can't generate mipmaps for compressed textures
  18622. // mips must be embedded in DDS files
  18623. this.generateMipmaps = false;
  18624. }
  18625. }
  18626. class CompressedArrayTexture extends CompressedTexture {
  18627. constructor( mipmaps, width, height, depth, format, type ) {
  18628. super( mipmaps, width, height, format, type );
  18629. this.isCompressedArrayTexture = true;
  18630. this.image.depth = depth;
  18631. this.wrapR = ClampToEdgeWrapping;
  18632. }
  18633. }
  18634. class CanvasTexture extends Texture {
  18635. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18636. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18637. this.isCanvasTexture = true;
  18638. this.needsUpdate = true;
  18639. }
  18640. }
  18641. /**
  18642. * Extensible curve object.
  18643. *
  18644. * Some common of curve methods:
  18645. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18646. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18647. * .getPoints(), .getSpacedPoints()
  18648. * .getLength()
  18649. * .updateArcLengths()
  18650. *
  18651. * This following curves inherit from THREE.Curve:
  18652. *
  18653. * -- 2D curves --
  18654. * THREE.ArcCurve
  18655. * THREE.CubicBezierCurve
  18656. * THREE.EllipseCurve
  18657. * THREE.LineCurve
  18658. * THREE.QuadraticBezierCurve
  18659. * THREE.SplineCurve
  18660. *
  18661. * -- 3D curves --
  18662. * THREE.CatmullRomCurve3
  18663. * THREE.CubicBezierCurve3
  18664. * THREE.LineCurve3
  18665. * THREE.QuadraticBezierCurve3
  18666. *
  18667. * A series of curves can be represented as a THREE.CurvePath.
  18668. *
  18669. **/
  18670. class Curve {
  18671. constructor() {
  18672. this.type = 'Curve';
  18673. this.arcLengthDivisions = 200;
  18674. }
  18675. // Virtual base class method to overwrite and implement in subclasses
  18676. // - t [0 .. 1]
  18677. getPoint( /* t, optionalTarget */ ) {
  18678. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18679. return null;
  18680. }
  18681. // Get point at relative position in curve according to arc length
  18682. // - u [0 .. 1]
  18683. getPointAt( u, optionalTarget ) {
  18684. const t = this.getUtoTmapping( u );
  18685. return this.getPoint( t, optionalTarget );
  18686. }
  18687. // Get sequence of points using getPoint( t )
  18688. getPoints( divisions = 5 ) {
  18689. const points = [];
  18690. for ( let d = 0; d <= divisions; d ++ ) {
  18691. points.push( this.getPoint( d / divisions ) );
  18692. }
  18693. return points;
  18694. }
  18695. // Get sequence of points using getPointAt( u )
  18696. getSpacedPoints( divisions = 5 ) {
  18697. const points = [];
  18698. for ( let d = 0; d <= divisions; d ++ ) {
  18699. points.push( this.getPointAt( d / divisions ) );
  18700. }
  18701. return points;
  18702. }
  18703. // Get total curve arc length
  18704. getLength() {
  18705. const lengths = this.getLengths();
  18706. return lengths[ lengths.length - 1 ];
  18707. }
  18708. // Get list of cumulative segment lengths
  18709. getLengths( divisions = this.arcLengthDivisions ) {
  18710. if ( this.cacheArcLengths &&
  18711. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18712. ! this.needsUpdate ) {
  18713. return this.cacheArcLengths;
  18714. }
  18715. this.needsUpdate = false;
  18716. const cache = [];
  18717. let current, last = this.getPoint( 0 );
  18718. let sum = 0;
  18719. cache.push( 0 );
  18720. for ( let p = 1; p <= divisions; p ++ ) {
  18721. current = this.getPoint( p / divisions );
  18722. sum += current.distanceTo( last );
  18723. cache.push( sum );
  18724. last = current;
  18725. }
  18726. this.cacheArcLengths = cache;
  18727. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18728. }
  18729. updateArcLengths() {
  18730. this.needsUpdate = true;
  18731. this.getLengths();
  18732. }
  18733. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18734. getUtoTmapping( u, distance ) {
  18735. const arcLengths = this.getLengths();
  18736. let i = 0;
  18737. const il = arcLengths.length;
  18738. let targetArcLength; // The targeted u distance value to get
  18739. if ( distance ) {
  18740. targetArcLength = distance;
  18741. } else {
  18742. targetArcLength = u * arcLengths[ il - 1 ];
  18743. }
  18744. // binary search for the index with largest value smaller than target u distance
  18745. let low = 0, high = il - 1, comparison;
  18746. while ( low <= high ) {
  18747. 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
  18748. comparison = arcLengths[ i ] - targetArcLength;
  18749. if ( comparison < 0 ) {
  18750. low = i + 1;
  18751. } else if ( comparison > 0 ) {
  18752. high = i - 1;
  18753. } else {
  18754. high = i;
  18755. break;
  18756. // DONE
  18757. }
  18758. }
  18759. i = high;
  18760. if ( arcLengths[ i ] === targetArcLength ) {
  18761. return i / ( il - 1 );
  18762. }
  18763. // we could get finer grain at lengths, or use simple interpolation between two points
  18764. const lengthBefore = arcLengths[ i ];
  18765. const lengthAfter = arcLengths[ i + 1 ];
  18766. const segmentLength = lengthAfter - lengthBefore;
  18767. // determine where we are between the 'before' and 'after' points
  18768. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18769. // add that fractional amount to t
  18770. const t = ( i + segmentFraction ) / ( il - 1 );
  18771. return t;
  18772. }
  18773. // Returns a unit vector tangent at t
  18774. // In case any sub curve does not implement its tangent derivation,
  18775. // 2 points a small delta apart will be used to find its gradient
  18776. // which seems to give a reasonable approximation
  18777. getTangent( t, optionalTarget ) {
  18778. const delta = 0.0001;
  18779. let t1 = t - delta;
  18780. let t2 = t + delta;
  18781. // Capping in case of danger
  18782. if ( t1 < 0 ) t1 = 0;
  18783. if ( t2 > 1 ) t2 = 1;
  18784. const pt1 = this.getPoint( t1 );
  18785. const pt2 = this.getPoint( t2 );
  18786. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18787. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18788. return tangent;
  18789. }
  18790. getTangentAt( u, optionalTarget ) {
  18791. const t = this.getUtoTmapping( u );
  18792. return this.getTangent( t, optionalTarget );
  18793. }
  18794. computeFrenetFrames( segments, closed ) {
  18795. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18796. const normal = new Vector3();
  18797. const tangents = [];
  18798. const normals = [];
  18799. const binormals = [];
  18800. const vec = new Vector3();
  18801. const mat = new Matrix4();
  18802. // compute the tangent vectors for each segment on the curve
  18803. for ( let i = 0; i <= segments; i ++ ) {
  18804. const u = i / segments;
  18805. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18806. }
  18807. // select an initial normal vector perpendicular to the first tangent vector,
  18808. // and in the direction of the minimum tangent xyz component
  18809. normals[ 0 ] = new Vector3();
  18810. binormals[ 0 ] = new Vector3();
  18811. let min = Number.MAX_VALUE;
  18812. const tx = Math.abs( tangents[ 0 ].x );
  18813. const ty = Math.abs( tangents[ 0 ].y );
  18814. const tz = Math.abs( tangents[ 0 ].z );
  18815. if ( tx <= min ) {
  18816. min = tx;
  18817. normal.set( 1, 0, 0 );
  18818. }
  18819. if ( ty <= min ) {
  18820. min = ty;
  18821. normal.set( 0, 1, 0 );
  18822. }
  18823. if ( tz <= min ) {
  18824. normal.set( 0, 0, 1 );
  18825. }
  18826. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18827. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18828. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18829. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18830. for ( let i = 1; i <= segments; i ++ ) {
  18831. normals[ i ] = normals[ i - 1 ].clone();
  18832. binormals[ i ] = binormals[ i - 1 ].clone();
  18833. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18834. if ( vec.length() > Number.EPSILON ) {
  18835. vec.normalize();
  18836. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18837. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18838. }
  18839. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18840. }
  18841. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18842. if ( closed === true ) {
  18843. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18844. theta /= segments;
  18845. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18846. theta = - theta;
  18847. }
  18848. for ( let i = 1; i <= segments; i ++ ) {
  18849. // twist a little...
  18850. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18851. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18852. }
  18853. }
  18854. return {
  18855. tangents: tangents,
  18856. normals: normals,
  18857. binormals: binormals
  18858. };
  18859. }
  18860. clone() {
  18861. return new this.constructor().copy( this );
  18862. }
  18863. copy( source ) {
  18864. this.arcLengthDivisions = source.arcLengthDivisions;
  18865. return this;
  18866. }
  18867. toJSON() {
  18868. const data = {
  18869. metadata: {
  18870. version: 4.5,
  18871. type: 'Curve',
  18872. generator: 'Curve.toJSON'
  18873. }
  18874. };
  18875. data.arcLengthDivisions = this.arcLengthDivisions;
  18876. data.type = this.type;
  18877. return data;
  18878. }
  18879. fromJSON( json ) {
  18880. this.arcLengthDivisions = json.arcLengthDivisions;
  18881. return this;
  18882. }
  18883. }
  18884. class EllipseCurve extends Curve {
  18885. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18886. super();
  18887. this.isEllipseCurve = true;
  18888. this.type = 'EllipseCurve';
  18889. this.aX = aX;
  18890. this.aY = aY;
  18891. this.xRadius = xRadius;
  18892. this.yRadius = yRadius;
  18893. this.aStartAngle = aStartAngle;
  18894. this.aEndAngle = aEndAngle;
  18895. this.aClockwise = aClockwise;
  18896. this.aRotation = aRotation;
  18897. }
  18898. getPoint( t, optionalTarget ) {
  18899. const point = optionalTarget || new Vector2();
  18900. const twoPi = Math.PI * 2;
  18901. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18902. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18903. // ensures that deltaAngle is 0 .. 2 PI
  18904. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18905. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18906. if ( deltaAngle < Number.EPSILON ) {
  18907. if ( samePoints ) {
  18908. deltaAngle = 0;
  18909. } else {
  18910. deltaAngle = twoPi;
  18911. }
  18912. }
  18913. if ( this.aClockwise === true && ! samePoints ) {
  18914. if ( deltaAngle === twoPi ) {
  18915. deltaAngle = - twoPi;
  18916. } else {
  18917. deltaAngle = deltaAngle - twoPi;
  18918. }
  18919. }
  18920. const angle = this.aStartAngle + t * deltaAngle;
  18921. let x = this.aX + this.xRadius * Math.cos( angle );
  18922. let y = this.aY + this.yRadius * Math.sin( angle );
  18923. if ( this.aRotation !== 0 ) {
  18924. const cos = Math.cos( this.aRotation );
  18925. const sin = Math.sin( this.aRotation );
  18926. const tx = x - this.aX;
  18927. const ty = y - this.aY;
  18928. // Rotate the point about the center of the ellipse.
  18929. x = tx * cos - ty * sin + this.aX;
  18930. y = tx * sin + ty * cos + this.aY;
  18931. }
  18932. return point.set( x, y );
  18933. }
  18934. copy( source ) {
  18935. super.copy( source );
  18936. this.aX = source.aX;
  18937. this.aY = source.aY;
  18938. this.xRadius = source.xRadius;
  18939. this.yRadius = source.yRadius;
  18940. this.aStartAngle = source.aStartAngle;
  18941. this.aEndAngle = source.aEndAngle;
  18942. this.aClockwise = source.aClockwise;
  18943. this.aRotation = source.aRotation;
  18944. return this;
  18945. }
  18946. toJSON() {
  18947. const data = super.toJSON();
  18948. data.aX = this.aX;
  18949. data.aY = this.aY;
  18950. data.xRadius = this.xRadius;
  18951. data.yRadius = this.yRadius;
  18952. data.aStartAngle = this.aStartAngle;
  18953. data.aEndAngle = this.aEndAngle;
  18954. data.aClockwise = this.aClockwise;
  18955. data.aRotation = this.aRotation;
  18956. return data;
  18957. }
  18958. fromJSON( json ) {
  18959. super.fromJSON( json );
  18960. this.aX = json.aX;
  18961. this.aY = json.aY;
  18962. this.xRadius = json.xRadius;
  18963. this.yRadius = json.yRadius;
  18964. this.aStartAngle = json.aStartAngle;
  18965. this.aEndAngle = json.aEndAngle;
  18966. this.aClockwise = json.aClockwise;
  18967. this.aRotation = json.aRotation;
  18968. return this;
  18969. }
  18970. }
  18971. class ArcCurve extends EllipseCurve {
  18972. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18973. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18974. this.isArcCurve = true;
  18975. this.type = 'ArcCurve';
  18976. }
  18977. }
  18978. /**
  18979. * Centripetal CatmullRom Curve - which is useful for avoiding
  18980. * cusps and self-intersections in non-uniform catmull rom curves.
  18981. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18982. *
  18983. * curve.type accepts centripetal(default), chordal and catmullrom
  18984. * curve.tension is used for catmullrom which defaults to 0.5
  18985. */
  18986. /*
  18987. Based on an optimized c++ solution in
  18988. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18989. - http://ideone.com/NoEbVM
  18990. This CubicPoly class could be used for reusing some variables and calculations,
  18991. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18992. which can be placed in CurveUtils.
  18993. */
  18994. function CubicPoly() {
  18995. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18996. /*
  18997. * Compute coefficients for a cubic polynomial
  18998. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18999. * such that
  19000. * p(0) = x0, p(1) = x1
  19001. * and
  19002. * p'(0) = t0, p'(1) = t1.
  19003. */
  19004. function init( x0, x1, t0, t1 ) {
  19005. c0 = x0;
  19006. c1 = t0;
  19007. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19008. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19009. }
  19010. return {
  19011. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19012. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19013. },
  19014. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19015. // compute tangents when parameterized in [t1,t2]
  19016. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19017. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19018. // rescale tangents for parametrization in [0,1]
  19019. t1 *= dt1;
  19020. t2 *= dt1;
  19021. init( x1, x2, t1, t2 );
  19022. },
  19023. calc: function ( t ) {
  19024. const t2 = t * t;
  19025. const t3 = t2 * t;
  19026. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19027. }
  19028. };
  19029. }
  19030. //
  19031. const tmp = /*@__PURE__*/ new Vector3();
  19032. const px = /*@__PURE__*/ new CubicPoly();
  19033. const py = /*@__PURE__*/ new CubicPoly();
  19034. const pz = /*@__PURE__*/ new CubicPoly();
  19035. class CatmullRomCurve3 extends Curve {
  19036. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19037. super();
  19038. this.isCatmullRomCurve3 = true;
  19039. this.type = 'CatmullRomCurve3';
  19040. this.points = points;
  19041. this.closed = closed;
  19042. this.curveType = curveType;
  19043. this.tension = tension;
  19044. }
  19045. getPoint( t, optionalTarget = new Vector3() ) {
  19046. const point = optionalTarget;
  19047. const points = this.points;
  19048. const l = points.length;
  19049. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19050. let intPoint = Math.floor( p );
  19051. let weight = p - intPoint;
  19052. if ( this.closed ) {
  19053. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19054. } else if ( weight === 0 && intPoint === l - 1 ) {
  19055. intPoint = l - 2;
  19056. weight = 1;
  19057. }
  19058. let p0, p3; // 4 points (p1 & p2 defined below)
  19059. if ( this.closed || intPoint > 0 ) {
  19060. p0 = points[ ( intPoint - 1 ) % l ];
  19061. } else {
  19062. // extrapolate first point
  19063. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19064. p0 = tmp;
  19065. }
  19066. const p1 = points[ intPoint % l ];
  19067. const p2 = points[ ( intPoint + 1 ) % l ];
  19068. if ( this.closed || intPoint + 2 < l ) {
  19069. p3 = points[ ( intPoint + 2 ) % l ];
  19070. } else {
  19071. // extrapolate last point
  19072. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19073. p3 = tmp;
  19074. }
  19075. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19076. // init Centripetal / Chordal Catmull-Rom
  19077. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19078. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19079. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19080. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19081. // safety check for repeated points
  19082. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19083. if ( dt0 < 1e-4 ) dt0 = dt1;
  19084. if ( dt2 < 1e-4 ) dt2 = dt1;
  19085. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19086. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19087. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19088. } else if ( this.curveType === 'catmullrom' ) {
  19089. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19090. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19091. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19092. }
  19093. point.set(
  19094. px.calc( weight ),
  19095. py.calc( weight ),
  19096. pz.calc( weight )
  19097. );
  19098. return point;
  19099. }
  19100. copy( source ) {
  19101. super.copy( source );
  19102. this.points = [];
  19103. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19104. const point = source.points[ i ];
  19105. this.points.push( point.clone() );
  19106. }
  19107. this.closed = source.closed;
  19108. this.curveType = source.curveType;
  19109. this.tension = source.tension;
  19110. return this;
  19111. }
  19112. toJSON() {
  19113. const data = super.toJSON();
  19114. data.points = [];
  19115. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19116. const point = this.points[ i ];
  19117. data.points.push( point.toArray() );
  19118. }
  19119. data.closed = this.closed;
  19120. data.curveType = this.curveType;
  19121. data.tension = this.tension;
  19122. return data;
  19123. }
  19124. fromJSON( json ) {
  19125. super.fromJSON( json );
  19126. this.points = [];
  19127. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19128. const point = json.points[ i ];
  19129. this.points.push( new Vector3().fromArray( point ) );
  19130. }
  19131. this.closed = json.closed;
  19132. this.curveType = json.curveType;
  19133. this.tension = json.tension;
  19134. return this;
  19135. }
  19136. }
  19137. /**
  19138. * Bezier Curves formulas obtained from
  19139. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19140. */
  19141. function CatmullRom( t, p0, p1, p2, p3 ) {
  19142. const v0 = ( p2 - p0 ) * 0.5;
  19143. const v1 = ( p3 - p1 ) * 0.5;
  19144. const t2 = t * t;
  19145. const t3 = t * t2;
  19146. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19147. }
  19148. //
  19149. function QuadraticBezierP0( t, p ) {
  19150. const k = 1 - t;
  19151. return k * k * p;
  19152. }
  19153. function QuadraticBezierP1( t, p ) {
  19154. return 2 * ( 1 - t ) * t * p;
  19155. }
  19156. function QuadraticBezierP2( t, p ) {
  19157. return t * t * p;
  19158. }
  19159. function QuadraticBezier( t, p0, p1, p2 ) {
  19160. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19161. QuadraticBezierP2( t, p2 );
  19162. }
  19163. //
  19164. function CubicBezierP0( t, p ) {
  19165. const k = 1 - t;
  19166. return k * k * k * p;
  19167. }
  19168. function CubicBezierP1( t, p ) {
  19169. const k = 1 - t;
  19170. return 3 * k * k * t * p;
  19171. }
  19172. function CubicBezierP2( t, p ) {
  19173. return 3 * ( 1 - t ) * t * t * p;
  19174. }
  19175. function CubicBezierP3( t, p ) {
  19176. return t * t * t * p;
  19177. }
  19178. function CubicBezier( t, p0, p1, p2, p3 ) {
  19179. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19180. CubicBezierP3( t, p3 );
  19181. }
  19182. class CubicBezierCurve extends Curve {
  19183. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19184. super();
  19185. this.isCubicBezierCurve = true;
  19186. this.type = 'CubicBezierCurve';
  19187. this.v0 = v0;
  19188. this.v1 = v1;
  19189. this.v2 = v2;
  19190. this.v3 = v3;
  19191. }
  19192. getPoint( t, optionalTarget = new Vector2() ) {
  19193. const point = optionalTarget;
  19194. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19195. point.set(
  19196. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19197. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19198. );
  19199. return point;
  19200. }
  19201. copy( source ) {
  19202. super.copy( source );
  19203. this.v0.copy( source.v0 );
  19204. this.v1.copy( source.v1 );
  19205. this.v2.copy( source.v2 );
  19206. this.v3.copy( source.v3 );
  19207. return this;
  19208. }
  19209. toJSON() {
  19210. const data = super.toJSON();
  19211. data.v0 = this.v0.toArray();
  19212. data.v1 = this.v1.toArray();
  19213. data.v2 = this.v2.toArray();
  19214. data.v3 = this.v3.toArray();
  19215. return data;
  19216. }
  19217. fromJSON( json ) {
  19218. super.fromJSON( json );
  19219. this.v0.fromArray( json.v0 );
  19220. this.v1.fromArray( json.v1 );
  19221. this.v2.fromArray( json.v2 );
  19222. this.v3.fromArray( json.v3 );
  19223. return this;
  19224. }
  19225. }
  19226. class CubicBezierCurve3 extends Curve {
  19227. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19228. super();
  19229. this.isCubicBezierCurve3 = true;
  19230. this.type = 'CubicBezierCurve3';
  19231. this.v0 = v0;
  19232. this.v1 = v1;
  19233. this.v2 = v2;
  19234. this.v3 = v3;
  19235. }
  19236. getPoint( t, optionalTarget = new Vector3() ) {
  19237. const point = optionalTarget;
  19238. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19239. point.set(
  19240. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19241. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19242. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19243. );
  19244. return point;
  19245. }
  19246. copy( source ) {
  19247. super.copy( source );
  19248. this.v0.copy( source.v0 );
  19249. this.v1.copy( source.v1 );
  19250. this.v2.copy( source.v2 );
  19251. this.v3.copy( source.v3 );
  19252. return this;
  19253. }
  19254. toJSON() {
  19255. const data = super.toJSON();
  19256. data.v0 = this.v0.toArray();
  19257. data.v1 = this.v1.toArray();
  19258. data.v2 = this.v2.toArray();
  19259. data.v3 = this.v3.toArray();
  19260. return data;
  19261. }
  19262. fromJSON( json ) {
  19263. super.fromJSON( json );
  19264. this.v0.fromArray( json.v0 );
  19265. this.v1.fromArray( json.v1 );
  19266. this.v2.fromArray( json.v2 );
  19267. this.v3.fromArray( json.v3 );
  19268. return this;
  19269. }
  19270. }
  19271. class LineCurve extends Curve {
  19272. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19273. super();
  19274. this.isLineCurve = true;
  19275. this.type = 'LineCurve';
  19276. this.v1 = v1;
  19277. this.v2 = v2;
  19278. }
  19279. getPoint( t, optionalTarget = new Vector2() ) {
  19280. const point = optionalTarget;
  19281. if ( t === 1 ) {
  19282. point.copy( this.v2 );
  19283. } else {
  19284. point.copy( this.v2 ).sub( this.v1 );
  19285. point.multiplyScalar( t ).add( this.v1 );
  19286. }
  19287. return point;
  19288. }
  19289. // Line curve is linear, so we can overwrite default getPointAt
  19290. getPointAt( u, optionalTarget ) {
  19291. return this.getPoint( u, optionalTarget );
  19292. }
  19293. getTangent( t, optionalTarget ) {
  19294. const tangent = optionalTarget || new Vector2();
  19295. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19296. return tangent;
  19297. }
  19298. copy( source ) {
  19299. super.copy( source );
  19300. this.v1.copy( source.v1 );
  19301. this.v2.copy( source.v2 );
  19302. return this;
  19303. }
  19304. toJSON() {
  19305. const data = super.toJSON();
  19306. data.v1 = this.v1.toArray();
  19307. data.v2 = this.v2.toArray();
  19308. return data;
  19309. }
  19310. fromJSON( json ) {
  19311. super.fromJSON( json );
  19312. this.v1.fromArray( json.v1 );
  19313. this.v2.fromArray( json.v2 );
  19314. return this;
  19315. }
  19316. }
  19317. class LineCurve3 extends Curve {
  19318. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19319. super();
  19320. this.isLineCurve3 = true;
  19321. this.type = 'LineCurve3';
  19322. this.v1 = v1;
  19323. this.v2 = v2;
  19324. }
  19325. getPoint( t, optionalTarget = new Vector3() ) {
  19326. const point = optionalTarget;
  19327. if ( t === 1 ) {
  19328. point.copy( this.v2 );
  19329. } else {
  19330. point.copy( this.v2 ).sub( this.v1 );
  19331. point.multiplyScalar( t ).add( this.v1 );
  19332. }
  19333. return point;
  19334. }
  19335. // Line curve is linear, so we can overwrite default getPointAt
  19336. getPointAt( u, optionalTarget ) {
  19337. return this.getPoint( u, optionalTarget );
  19338. }
  19339. copy( source ) {
  19340. super.copy( source );
  19341. this.v1.copy( source.v1 );
  19342. this.v2.copy( source.v2 );
  19343. return this;
  19344. }
  19345. toJSON() {
  19346. const data = super.toJSON();
  19347. data.v1 = this.v1.toArray();
  19348. data.v2 = this.v2.toArray();
  19349. return data;
  19350. }
  19351. fromJSON( json ) {
  19352. super.fromJSON( json );
  19353. this.v1.fromArray( json.v1 );
  19354. this.v2.fromArray( json.v2 );
  19355. return this;
  19356. }
  19357. }
  19358. class QuadraticBezierCurve extends Curve {
  19359. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19360. super();
  19361. this.isQuadraticBezierCurve = true;
  19362. this.type = 'QuadraticBezierCurve';
  19363. this.v0 = v0;
  19364. this.v1 = v1;
  19365. this.v2 = v2;
  19366. }
  19367. getPoint( t, optionalTarget = new Vector2() ) {
  19368. const point = optionalTarget;
  19369. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19370. point.set(
  19371. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19372. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19373. );
  19374. return point;
  19375. }
  19376. copy( source ) {
  19377. super.copy( source );
  19378. this.v0.copy( source.v0 );
  19379. this.v1.copy( source.v1 );
  19380. this.v2.copy( source.v2 );
  19381. return this;
  19382. }
  19383. toJSON() {
  19384. const data = super.toJSON();
  19385. data.v0 = this.v0.toArray();
  19386. data.v1 = this.v1.toArray();
  19387. data.v2 = this.v2.toArray();
  19388. return data;
  19389. }
  19390. fromJSON( json ) {
  19391. super.fromJSON( json );
  19392. this.v0.fromArray( json.v0 );
  19393. this.v1.fromArray( json.v1 );
  19394. this.v2.fromArray( json.v2 );
  19395. return this;
  19396. }
  19397. }
  19398. class QuadraticBezierCurve3 extends Curve {
  19399. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19400. super();
  19401. this.isQuadraticBezierCurve3 = true;
  19402. this.type = 'QuadraticBezierCurve3';
  19403. this.v0 = v0;
  19404. this.v1 = v1;
  19405. this.v2 = v2;
  19406. }
  19407. getPoint( t, optionalTarget = new Vector3() ) {
  19408. const point = optionalTarget;
  19409. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19410. point.set(
  19411. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19412. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19413. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19414. );
  19415. return point;
  19416. }
  19417. copy( source ) {
  19418. super.copy( source );
  19419. this.v0.copy( source.v0 );
  19420. this.v1.copy( source.v1 );
  19421. this.v2.copy( source.v2 );
  19422. return this;
  19423. }
  19424. toJSON() {
  19425. const data = super.toJSON();
  19426. data.v0 = this.v0.toArray();
  19427. data.v1 = this.v1.toArray();
  19428. data.v2 = this.v2.toArray();
  19429. return data;
  19430. }
  19431. fromJSON( json ) {
  19432. super.fromJSON( json );
  19433. this.v0.fromArray( json.v0 );
  19434. this.v1.fromArray( json.v1 );
  19435. this.v2.fromArray( json.v2 );
  19436. return this;
  19437. }
  19438. }
  19439. class SplineCurve extends Curve {
  19440. constructor( points = [] ) {
  19441. super();
  19442. this.isSplineCurve = true;
  19443. this.type = 'SplineCurve';
  19444. this.points = points;
  19445. }
  19446. getPoint( t, optionalTarget = new Vector2() ) {
  19447. const point = optionalTarget;
  19448. const points = this.points;
  19449. const p = ( points.length - 1 ) * t;
  19450. const intPoint = Math.floor( p );
  19451. const weight = p - intPoint;
  19452. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19453. const p1 = points[ intPoint ];
  19454. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19455. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19456. point.set(
  19457. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19458. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19459. );
  19460. return point;
  19461. }
  19462. copy( source ) {
  19463. super.copy( source );
  19464. this.points = [];
  19465. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19466. const point = source.points[ i ];
  19467. this.points.push( point.clone() );
  19468. }
  19469. return this;
  19470. }
  19471. toJSON() {
  19472. const data = super.toJSON();
  19473. data.points = [];
  19474. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19475. const point = this.points[ i ];
  19476. data.points.push( point.toArray() );
  19477. }
  19478. return data;
  19479. }
  19480. fromJSON( json ) {
  19481. super.fromJSON( json );
  19482. this.points = [];
  19483. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19484. const point = json.points[ i ];
  19485. this.points.push( new Vector2().fromArray( point ) );
  19486. }
  19487. return this;
  19488. }
  19489. }
  19490. var Curves = /*#__PURE__*/Object.freeze({
  19491. __proto__: null,
  19492. ArcCurve: ArcCurve,
  19493. CatmullRomCurve3: CatmullRomCurve3,
  19494. CubicBezierCurve: CubicBezierCurve,
  19495. CubicBezierCurve3: CubicBezierCurve3,
  19496. EllipseCurve: EllipseCurve,
  19497. LineCurve: LineCurve,
  19498. LineCurve3: LineCurve3,
  19499. QuadraticBezierCurve: QuadraticBezierCurve,
  19500. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19501. SplineCurve: SplineCurve
  19502. });
  19503. /**************************************************************
  19504. * Curved Path - a curve path is simply a array of connected
  19505. * curves, but retains the api of a curve
  19506. **************************************************************/
  19507. class CurvePath extends Curve {
  19508. constructor() {
  19509. super();
  19510. this.type = 'CurvePath';
  19511. this.curves = [];
  19512. this.autoClose = false; // Automatically closes the path
  19513. }
  19514. add( curve ) {
  19515. this.curves.push( curve );
  19516. }
  19517. closePath() {
  19518. // Add a line curve if start and end of lines are not connected
  19519. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19520. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19521. if ( ! startPoint.equals( endPoint ) ) {
  19522. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19523. }
  19524. }
  19525. // To get accurate point with reference to
  19526. // entire path distance at time t,
  19527. // following has to be done:
  19528. // 1. Length of each sub path have to be known
  19529. // 2. Locate and identify type of curve
  19530. // 3. Get t for the curve
  19531. // 4. Return curve.getPointAt(t')
  19532. getPoint( t, optionalTarget ) {
  19533. const d = t * this.getLength();
  19534. const curveLengths = this.getCurveLengths();
  19535. let i = 0;
  19536. // To think about boundaries points.
  19537. while ( i < curveLengths.length ) {
  19538. if ( curveLengths[ i ] >= d ) {
  19539. const diff = curveLengths[ i ] - d;
  19540. const curve = this.curves[ i ];
  19541. const segmentLength = curve.getLength();
  19542. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19543. return curve.getPointAt( u, optionalTarget );
  19544. }
  19545. i ++;
  19546. }
  19547. return null;
  19548. // loop where sum != 0, sum > d , sum+1 <d
  19549. }
  19550. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19551. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19552. // getPoint() depends on getLength
  19553. getLength() {
  19554. const lens = this.getCurveLengths();
  19555. return lens[ lens.length - 1 ];
  19556. }
  19557. // cacheLengths must be recalculated.
  19558. updateArcLengths() {
  19559. this.needsUpdate = true;
  19560. this.cacheLengths = null;
  19561. this.getCurveLengths();
  19562. }
  19563. // Compute lengths and cache them
  19564. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19565. getCurveLengths() {
  19566. // We use cache values if curves and cache array are same length
  19567. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19568. return this.cacheLengths;
  19569. }
  19570. // Get length of sub-curve
  19571. // Push sums into cached array
  19572. const lengths = [];
  19573. let sums = 0;
  19574. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19575. sums += this.curves[ i ].getLength();
  19576. lengths.push( sums );
  19577. }
  19578. this.cacheLengths = lengths;
  19579. return lengths;
  19580. }
  19581. getSpacedPoints( divisions = 40 ) {
  19582. const points = [];
  19583. for ( let i = 0; i <= divisions; i ++ ) {
  19584. points.push( this.getPoint( i / divisions ) );
  19585. }
  19586. if ( this.autoClose ) {
  19587. points.push( points[ 0 ] );
  19588. }
  19589. return points;
  19590. }
  19591. getPoints( divisions = 12 ) {
  19592. const points = [];
  19593. let last;
  19594. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19595. const curve = curves[ i ];
  19596. const resolution = curve.isEllipseCurve ? divisions * 2
  19597. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19598. : curve.isSplineCurve ? divisions * curve.points.length
  19599. : divisions;
  19600. const pts = curve.getPoints( resolution );
  19601. for ( let j = 0; j < pts.length; j ++ ) {
  19602. const point = pts[ j ];
  19603. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19604. points.push( point );
  19605. last = point;
  19606. }
  19607. }
  19608. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19609. points.push( points[ 0 ] );
  19610. }
  19611. return points;
  19612. }
  19613. copy( source ) {
  19614. super.copy( source );
  19615. this.curves = [];
  19616. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19617. const curve = source.curves[ i ];
  19618. this.curves.push( curve.clone() );
  19619. }
  19620. this.autoClose = source.autoClose;
  19621. return this;
  19622. }
  19623. toJSON() {
  19624. const data = super.toJSON();
  19625. data.autoClose = this.autoClose;
  19626. data.curves = [];
  19627. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19628. const curve = this.curves[ i ];
  19629. data.curves.push( curve.toJSON() );
  19630. }
  19631. return data;
  19632. }
  19633. fromJSON( json ) {
  19634. super.fromJSON( json );
  19635. this.autoClose = json.autoClose;
  19636. this.curves = [];
  19637. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19638. const curve = json.curves[ i ];
  19639. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19640. }
  19641. return this;
  19642. }
  19643. }
  19644. class Path extends CurvePath {
  19645. constructor( points ) {
  19646. super();
  19647. this.type = 'Path';
  19648. this.currentPoint = new Vector2();
  19649. if ( points ) {
  19650. this.setFromPoints( points );
  19651. }
  19652. }
  19653. setFromPoints( points ) {
  19654. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19655. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19656. this.lineTo( points[ i ].x, points[ i ].y );
  19657. }
  19658. return this;
  19659. }
  19660. moveTo( x, y ) {
  19661. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19662. return this;
  19663. }
  19664. lineTo( x, y ) {
  19665. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19666. this.curves.push( curve );
  19667. this.currentPoint.set( x, y );
  19668. return this;
  19669. }
  19670. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19671. const curve = new QuadraticBezierCurve(
  19672. this.currentPoint.clone(),
  19673. new Vector2( aCPx, aCPy ),
  19674. new Vector2( aX, aY )
  19675. );
  19676. this.curves.push( curve );
  19677. this.currentPoint.set( aX, aY );
  19678. return this;
  19679. }
  19680. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19681. const curve = new CubicBezierCurve(
  19682. this.currentPoint.clone(),
  19683. new Vector2( aCP1x, aCP1y ),
  19684. new Vector2( aCP2x, aCP2y ),
  19685. new Vector2( aX, aY )
  19686. );
  19687. this.curves.push( curve );
  19688. this.currentPoint.set( aX, aY );
  19689. return this;
  19690. }
  19691. splineThru( pts /*Array of Vector*/ ) {
  19692. const npts = [ this.currentPoint.clone() ].concat( pts );
  19693. const curve = new SplineCurve( npts );
  19694. this.curves.push( curve );
  19695. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19696. return this;
  19697. }
  19698. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19699. const x0 = this.currentPoint.x;
  19700. const y0 = this.currentPoint.y;
  19701. this.absarc( aX + x0, aY + y0, aRadius,
  19702. aStartAngle, aEndAngle, aClockwise );
  19703. return this;
  19704. }
  19705. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19706. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19707. return this;
  19708. }
  19709. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19710. const x0 = this.currentPoint.x;
  19711. const y0 = this.currentPoint.y;
  19712. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19713. return this;
  19714. }
  19715. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19716. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19717. if ( this.curves.length > 0 ) {
  19718. // if a previous curve is present, attempt to join
  19719. const firstPoint = curve.getPoint( 0 );
  19720. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19721. this.lineTo( firstPoint.x, firstPoint.y );
  19722. }
  19723. }
  19724. this.curves.push( curve );
  19725. const lastPoint = curve.getPoint( 1 );
  19726. this.currentPoint.copy( lastPoint );
  19727. return this;
  19728. }
  19729. copy( source ) {
  19730. super.copy( source );
  19731. this.currentPoint.copy( source.currentPoint );
  19732. return this;
  19733. }
  19734. toJSON() {
  19735. const data = super.toJSON();
  19736. data.currentPoint = this.currentPoint.toArray();
  19737. return data;
  19738. }
  19739. fromJSON( json ) {
  19740. super.fromJSON( json );
  19741. this.currentPoint.fromArray( json.currentPoint );
  19742. return this;
  19743. }
  19744. }
  19745. class LatheGeometry extends BufferGeometry {
  19746. 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 ) {
  19747. super();
  19748. this.type = 'LatheGeometry';
  19749. this.parameters = {
  19750. points: points,
  19751. segments: segments,
  19752. phiStart: phiStart,
  19753. phiLength: phiLength
  19754. };
  19755. segments = Math.floor( segments );
  19756. // clamp phiLength so it's in range of [ 0, 2PI ]
  19757. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19758. // buffers
  19759. const indices = [];
  19760. const vertices = [];
  19761. const uvs = [];
  19762. const initNormals = [];
  19763. const normals = [];
  19764. // helper variables
  19765. const inverseSegments = 1.0 / segments;
  19766. const vertex = new Vector3();
  19767. const uv = new Vector2();
  19768. const normal = new Vector3();
  19769. const curNormal = new Vector3();
  19770. const prevNormal = new Vector3();
  19771. let dx = 0;
  19772. let dy = 0;
  19773. // pre-compute normals for initial "meridian"
  19774. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19775. switch ( j ) {
  19776. case 0: // special handling for 1st vertex on path
  19777. dx = points[ j + 1 ].x - points[ j ].x;
  19778. dy = points[ j + 1 ].y - points[ j ].y;
  19779. normal.x = dy * 1.0;
  19780. normal.y = - dx;
  19781. normal.z = dy * 0.0;
  19782. prevNormal.copy( normal );
  19783. normal.normalize();
  19784. initNormals.push( normal.x, normal.y, normal.z );
  19785. break;
  19786. case ( points.length - 1 ): // special handling for last Vertex on path
  19787. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19788. break;
  19789. default: // default handling for all vertices in between
  19790. dx = points[ j + 1 ].x - points[ j ].x;
  19791. dy = points[ j + 1 ].y - points[ j ].y;
  19792. normal.x = dy * 1.0;
  19793. normal.y = - dx;
  19794. normal.z = dy * 0.0;
  19795. curNormal.copy( normal );
  19796. normal.x += prevNormal.x;
  19797. normal.y += prevNormal.y;
  19798. normal.z += prevNormal.z;
  19799. normal.normalize();
  19800. initNormals.push( normal.x, normal.y, normal.z );
  19801. prevNormal.copy( curNormal );
  19802. }
  19803. }
  19804. // generate vertices, uvs and normals
  19805. for ( let i = 0; i <= segments; i ++ ) {
  19806. const phi = phiStart + i * inverseSegments * phiLength;
  19807. const sin = Math.sin( phi );
  19808. const cos = Math.cos( phi );
  19809. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19810. // vertex
  19811. vertex.x = points[ j ].x * sin;
  19812. vertex.y = points[ j ].y;
  19813. vertex.z = points[ j ].x * cos;
  19814. vertices.push( vertex.x, vertex.y, vertex.z );
  19815. // uv
  19816. uv.x = i / segments;
  19817. uv.y = j / ( points.length - 1 );
  19818. uvs.push( uv.x, uv.y );
  19819. // normal
  19820. const x = initNormals[ 3 * j + 0 ] * sin;
  19821. const y = initNormals[ 3 * j + 1 ];
  19822. const z = initNormals[ 3 * j + 0 ] * cos;
  19823. normals.push( x, y, z );
  19824. }
  19825. }
  19826. // indices
  19827. for ( let i = 0; i < segments; i ++ ) {
  19828. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19829. const base = j + i * points.length;
  19830. const a = base;
  19831. const b = base + points.length;
  19832. const c = base + points.length + 1;
  19833. const d = base + 1;
  19834. // faces
  19835. indices.push( a, b, d );
  19836. indices.push( c, d, b );
  19837. }
  19838. }
  19839. // build geometry
  19840. this.setIndex( indices );
  19841. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19842. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19843. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19844. }
  19845. static fromJSON( data ) {
  19846. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19847. }
  19848. }
  19849. class CapsuleGeometry extends LatheGeometry {
  19850. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19851. const path = new Path();
  19852. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19853. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19854. super( path.getPoints( capSegments ), radialSegments );
  19855. this.type = 'CapsuleGeometry';
  19856. this.parameters = {
  19857. radius: radius,
  19858. height: length,
  19859. capSegments: capSegments,
  19860. radialSegments: radialSegments,
  19861. };
  19862. }
  19863. static fromJSON( data ) {
  19864. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19865. }
  19866. }
  19867. class CircleGeometry extends BufferGeometry {
  19868. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19869. super();
  19870. this.type = 'CircleGeometry';
  19871. this.parameters = {
  19872. radius: radius,
  19873. segments: segments,
  19874. thetaStart: thetaStart,
  19875. thetaLength: thetaLength
  19876. };
  19877. segments = Math.max( 3, segments );
  19878. // buffers
  19879. const indices = [];
  19880. const vertices = [];
  19881. const normals = [];
  19882. const uvs = [];
  19883. // helper variables
  19884. const vertex = new Vector3();
  19885. const uv = new Vector2();
  19886. // center point
  19887. vertices.push( 0, 0, 0 );
  19888. normals.push( 0, 0, 1 );
  19889. uvs.push( 0.5, 0.5 );
  19890. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19891. const segment = thetaStart + s / segments * thetaLength;
  19892. // vertex
  19893. vertex.x = radius * Math.cos( segment );
  19894. vertex.y = radius * Math.sin( segment );
  19895. vertices.push( vertex.x, vertex.y, vertex.z );
  19896. // normal
  19897. normals.push( 0, 0, 1 );
  19898. // uvs
  19899. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19900. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19901. uvs.push( uv.x, uv.y );
  19902. }
  19903. // indices
  19904. for ( let i = 1; i <= segments; i ++ ) {
  19905. indices.push( i, i + 1, 0 );
  19906. }
  19907. // build geometry
  19908. this.setIndex( indices );
  19909. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19910. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19911. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19912. }
  19913. static fromJSON( data ) {
  19914. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19915. }
  19916. }
  19917. class CylinderGeometry extends BufferGeometry {
  19918. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19919. super();
  19920. this.type = 'CylinderGeometry';
  19921. this.parameters = {
  19922. radiusTop: radiusTop,
  19923. radiusBottom: radiusBottom,
  19924. height: height,
  19925. radialSegments: radialSegments,
  19926. heightSegments: heightSegments,
  19927. openEnded: openEnded,
  19928. thetaStart: thetaStart,
  19929. thetaLength: thetaLength
  19930. };
  19931. const scope = this;
  19932. radialSegments = Math.floor( radialSegments );
  19933. heightSegments = Math.floor( heightSegments );
  19934. // buffers
  19935. const indices = [];
  19936. const vertices = [];
  19937. const normals = [];
  19938. const uvs = [];
  19939. // helper variables
  19940. let index = 0;
  19941. const indexArray = [];
  19942. const halfHeight = height / 2;
  19943. let groupStart = 0;
  19944. // generate geometry
  19945. generateTorso();
  19946. if ( openEnded === false ) {
  19947. if ( radiusTop > 0 ) generateCap( true );
  19948. if ( radiusBottom > 0 ) generateCap( false );
  19949. }
  19950. // build geometry
  19951. this.setIndex( indices );
  19952. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19953. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19954. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19955. function generateTorso() {
  19956. const normal = new Vector3();
  19957. const vertex = new Vector3();
  19958. let groupCount = 0;
  19959. // this will be used to calculate the normal
  19960. const slope = ( radiusBottom - radiusTop ) / height;
  19961. // generate vertices, normals and uvs
  19962. for ( let y = 0; y <= heightSegments; y ++ ) {
  19963. const indexRow = [];
  19964. const v = y / heightSegments;
  19965. // calculate the radius of the current row
  19966. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19967. for ( let x = 0; x <= radialSegments; x ++ ) {
  19968. const u = x / radialSegments;
  19969. const theta = u * thetaLength + thetaStart;
  19970. const sinTheta = Math.sin( theta );
  19971. const cosTheta = Math.cos( theta );
  19972. // vertex
  19973. vertex.x = radius * sinTheta;
  19974. vertex.y = - v * height + halfHeight;
  19975. vertex.z = radius * cosTheta;
  19976. vertices.push( vertex.x, vertex.y, vertex.z );
  19977. // normal
  19978. normal.set( sinTheta, slope, cosTheta ).normalize();
  19979. normals.push( normal.x, normal.y, normal.z );
  19980. // uv
  19981. uvs.push( u, 1 - v );
  19982. // save index of vertex in respective row
  19983. indexRow.push( index ++ );
  19984. }
  19985. // now save vertices of the row in our index array
  19986. indexArray.push( indexRow );
  19987. }
  19988. // generate indices
  19989. for ( let x = 0; x < radialSegments; x ++ ) {
  19990. for ( let y = 0; y < heightSegments; y ++ ) {
  19991. // we use the index array to access the correct indices
  19992. const a = indexArray[ y ][ x ];
  19993. const b = indexArray[ y + 1 ][ x ];
  19994. const c = indexArray[ y + 1 ][ x + 1 ];
  19995. const d = indexArray[ y ][ x + 1 ];
  19996. // faces
  19997. indices.push( a, b, d );
  19998. indices.push( b, c, d );
  19999. // update group counter
  20000. groupCount += 6;
  20001. }
  20002. }
  20003. // add a group to the geometry. this will ensure multi material support
  20004. scope.addGroup( groupStart, groupCount, 0 );
  20005. // calculate new start value for groups
  20006. groupStart += groupCount;
  20007. }
  20008. function generateCap( top ) {
  20009. // save the index of the first center vertex
  20010. const centerIndexStart = index;
  20011. const uv = new Vector2();
  20012. const vertex = new Vector3();
  20013. let groupCount = 0;
  20014. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20015. const sign = ( top === true ) ? 1 : - 1;
  20016. // first we generate the center vertex data of the cap.
  20017. // because the geometry needs one set of uvs per face,
  20018. // we must generate a center vertex per face/segment
  20019. for ( let x = 1; x <= radialSegments; x ++ ) {
  20020. // vertex
  20021. vertices.push( 0, halfHeight * sign, 0 );
  20022. // normal
  20023. normals.push( 0, sign, 0 );
  20024. // uv
  20025. uvs.push( 0.5, 0.5 );
  20026. // increase index
  20027. index ++;
  20028. }
  20029. // save the index of the last center vertex
  20030. const centerIndexEnd = index;
  20031. // now we generate the surrounding vertices, normals and uvs
  20032. for ( let x = 0; x <= radialSegments; x ++ ) {
  20033. const u = x / radialSegments;
  20034. const theta = u * thetaLength + thetaStart;
  20035. const cosTheta = Math.cos( theta );
  20036. const sinTheta = Math.sin( theta );
  20037. // vertex
  20038. vertex.x = radius * sinTheta;
  20039. vertex.y = halfHeight * sign;
  20040. vertex.z = radius * cosTheta;
  20041. vertices.push( vertex.x, vertex.y, vertex.z );
  20042. // normal
  20043. normals.push( 0, sign, 0 );
  20044. // uv
  20045. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20046. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20047. uvs.push( uv.x, uv.y );
  20048. // increase index
  20049. index ++;
  20050. }
  20051. // generate indices
  20052. for ( let x = 0; x < radialSegments; x ++ ) {
  20053. const c = centerIndexStart + x;
  20054. const i = centerIndexEnd + x;
  20055. if ( top === true ) {
  20056. // face top
  20057. indices.push( i, i + 1, c );
  20058. } else {
  20059. // face bottom
  20060. indices.push( i + 1, i, c );
  20061. }
  20062. groupCount += 3;
  20063. }
  20064. // add a group to the geometry. this will ensure multi material support
  20065. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20066. // calculate new start value for groups
  20067. groupStart += groupCount;
  20068. }
  20069. }
  20070. static fromJSON( data ) {
  20071. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20072. }
  20073. }
  20074. class ConeGeometry extends CylinderGeometry {
  20075. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20076. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20077. this.type = 'ConeGeometry';
  20078. this.parameters = {
  20079. radius: radius,
  20080. height: height,
  20081. radialSegments: radialSegments,
  20082. heightSegments: heightSegments,
  20083. openEnded: openEnded,
  20084. thetaStart: thetaStart,
  20085. thetaLength: thetaLength
  20086. };
  20087. }
  20088. static fromJSON( data ) {
  20089. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20090. }
  20091. }
  20092. class PolyhedronGeometry extends BufferGeometry {
  20093. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20094. super();
  20095. this.type = 'PolyhedronGeometry';
  20096. this.parameters = {
  20097. vertices: vertices,
  20098. indices: indices,
  20099. radius: radius,
  20100. detail: detail
  20101. };
  20102. // default buffer data
  20103. const vertexBuffer = [];
  20104. const uvBuffer = [];
  20105. // the subdivision creates the vertex buffer data
  20106. subdivide( detail );
  20107. // all vertices should lie on a conceptual sphere with a given radius
  20108. applyRadius( radius );
  20109. // finally, create the uv data
  20110. generateUVs();
  20111. // build non-indexed geometry
  20112. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20113. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20114. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20115. if ( detail === 0 ) {
  20116. this.computeVertexNormals(); // flat normals
  20117. } else {
  20118. this.normalizeNormals(); // smooth normals
  20119. }
  20120. // helper functions
  20121. function subdivide( detail ) {
  20122. const a = new Vector3();
  20123. const b = new Vector3();
  20124. const c = new Vector3();
  20125. // iterate over all faces and apply a subdivision with the given detail value
  20126. for ( let i = 0; i < indices.length; i += 3 ) {
  20127. // get the vertices of the face
  20128. getVertexByIndex( indices[ i + 0 ], a );
  20129. getVertexByIndex( indices[ i + 1 ], b );
  20130. getVertexByIndex( indices[ i + 2 ], c );
  20131. // perform subdivision
  20132. subdivideFace( a, b, c, detail );
  20133. }
  20134. }
  20135. function subdivideFace( a, b, c, detail ) {
  20136. const cols = detail + 1;
  20137. // we use this multidimensional array as a data structure for creating the subdivision
  20138. const v = [];
  20139. // construct all of the vertices for this subdivision
  20140. for ( let i = 0; i <= cols; i ++ ) {
  20141. v[ i ] = [];
  20142. const aj = a.clone().lerp( c, i / cols );
  20143. const bj = b.clone().lerp( c, i / cols );
  20144. const rows = cols - i;
  20145. for ( let j = 0; j <= rows; j ++ ) {
  20146. if ( j === 0 && i === cols ) {
  20147. v[ i ][ j ] = aj;
  20148. } else {
  20149. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20150. }
  20151. }
  20152. }
  20153. // construct all of the faces
  20154. for ( let i = 0; i < cols; i ++ ) {
  20155. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20156. const k = Math.floor( j / 2 );
  20157. if ( j % 2 === 0 ) {
  20158. pushVertex( v[ i ][ k + 1 ] );
  20159. pushVertex( v[ i + 1 ][ k ] );
  20160. pushVertex( v[ i ][ k ] );
  20161. } else {
  20162. pushVertex( v[ i ][ k + 1 ] );
  20163. pushVertex( v[ i + 1 ][ k + 1 ] );
  20164. pushVertex( v[ i + 1 ][ k ] );
  20165. }
  20166. }
  20167. }
  20168. }
  20169. function applyRadius( radius ) {
  20170. const vertex = new Vector3();
  20171. // iterate over the entire buffer and apply the radius to each vertex
  20172. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20173. vertex.x = vertexBuffer[ i + 0 ];
  20174. vertex.y = vertexBuffer[ i + 1 ];
  20175. vertex.z = vertexBuffer[ i + 2 ];
  20176. vertex.normalize().multiplyScalar( radius );
  20177. vertexBuffer[ i + 0 ] = vertex.x;
  20178. vertexBuffer[ i + 1 ] = vertex.y;
  20179. vertexBuffer[ i + 2 ] = vertex.z;
  20180. }
  20181. }
  20182. function generateUVs() {
  20183. const vertex = new Vector3();
  20184. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20185. vertex.x = vertexBuffer[ i + 0 ];
  20186. vertex.y = vertexBuffer[ i + 1 ];
  20187. vertex.z = vertexBuffer[ i + 2 ];
  20188. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20189. const v = inclination( vertex ) / Math.PI + 0.5;
  20190. uvBuffer.push( u, 1 - v );
  20191. }
  20192. correctUVs();
  20193. correctSeam();
  20194. }
  20195. function correctSeam() {
  20196. // handle case when face straddles the seam, see #3269
  20197. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20198. // uv data of a single face
  20199. const x0 = uvBuffer[ i + 0 ];
  20200. const x1 = uvBuffer[ i + 2 ];
  20201. const x2 = uvBuffer[ i + 4 ];
  20202. const max = Math.max( x0, x1, x2 );
  20203. const min = Math.min( x0, x1, x2 );
  20204. // 0.9 is somewhat arbitrary
  20205. if ( max > 0.9 && min < 0.1 ) {
  20206. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20207. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20208. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20209. }
  20210. }
  20211. }
  20212. function pushVertex( vertex ) {
  20213. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20214. }
  20215. function getVertexByIndex( index, vertex ) {
  20216. const stride = index * 3;
  20217. vertex.x = vertices[ stride + 0 ];
  20218. vertex.y = vertices[ stride + 1 ];
  20219. vertex.z = vertices[ stride + 2 ];
  20220. }
  20221. function correctUVs() {
  20222. const a = new Vector3();
  20223. const b = new Vector3();
  20224. const c = new Vector3();
  20225. const centroid = new Vector3();
  20226. const uvA = new Vector2();
  20227. const uvB = new Vector2();
  20228. const uvC = new Vector2();
  20229. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20230. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20231. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20232. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20233. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20234. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20235. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20236. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20237. const azi = azimuth( centroid );
  20238. correctUV( uvA, j + 0, a, azi );
  20239. correctUV( uvB, j + 2, b, azi );
  20240. correctUV( uvC, j + 4, c, azi );
  20241. }
  20242. }
  20243. function correctUV( uv, stride, vector, azimuth ) {
  20244. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20245. uvBuffer[ stride ] = uv.x - 1;
  20246. }
  20247. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20248. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20249. }
  20250. }
  20251. // Angle around the Y axis, counter-clockwise when looking from above.
  20252. function azimuth( vector ) {
  20253. return Math.atan2( vector.z, - vector.x );
  20254. }
  20255. // Angle above the XZ plane.
  20256. function inclination( vector ) {
  20257. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20258. }
  20259. }
  20260. static fromJSON( data ) {
  20261. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20262. }
  20263. }
  20264. class DodecahedronGeometry extends PolyhedronGeometry {
  20265. constructor( radius = 1, detail = 0 ) {
  20266. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20267. const r = 1 / t;
  20268. const vertices = [
  20269. // (±1, ±1, ±1)
  20270. - 1, - 1, - 1, - 1, - 1, 1,
  20271. - 1, 1, - 1, - 1, 1, 1,
  20272. 1, - 1, - 1, 1, - 1, 1,
  20273. 1, 1, - 1, 1, 1, 1,
  20274. // (0, ±1/φ, ±φ)
  20275. 0, - r, - t, 0, - r, t,
  20276. 0, r, - t, 0, r, t,
  20277. // (±1/φ, ±φ, 0)
  20278. - r, - t, 0, - r, t, 0,
  20279. r, - t, 0, r, t, 0,
  20280. // (±φ, 0, ±1/φ)
  20281. - t, 0, - r, t, 0, - r,
  20282. - t, 0, r, t, 0, r
  20283. ];
  20284. const indices = [
  20285. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20286. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20287. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20288. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20289. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20290. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20291. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20292. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20293. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20294. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20295. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20296. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20297. ];
  20298. super( vertices, indices, radius, detail );
  20299. this.type = 'DodecahedronGeometry';
  20300. this.parameters = {
  20301. radius: radius,
  20302. detail: detail
  20303. };
  20304. }
  20305. static fromJSON( data ) {
  20306. return new DodecahedronGeometry( data.radius, data.detail );
  20307. }
  20308. }
  20309. const _v0 = /*@__PURE__*/ new Vector3();
  20310. const _v1$1 = /*@__PURE__*/ new Vector3();
  20311. const _normal = /*@__PURE__*/ new Vector3();
  20312. const _triangle = /*@__PURE__*/ new Triangle();
  20313. class EdgesGeometry extends BufferGeometry {
  20314. constructor( geometry = null, thresholdAngle = 1 ) {
  20315. super();
  20316. this.type = 'EdgesGeometry';
  20317. this.parameters = {
  20318. geometry: geometry,
  20319. thresholdAngle: thresholdAngle
  20320. };
  20321. if ( geometry !== null ) {
  20322. const precisionPoints = 4;
  20323. const precision = Math.pow( 10, precisionPoints );
  20324. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20325. const indexAttr = geometry.getIndex();
  20326. const positionAttr = geometry.getAttribute( 'position' );
  20327. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20328. const indexArr = [ 0, 0, 0 ];
  20329. const vertKeys = [ 'a', 'b', 'c' ];
  20330. const hashes = new Array( 3 );
  20331. const edgeData = {};
  20332. const vertices = [];
  20333. for ( let i = 0; i < indexCount; i += 3 ) {
  20334. if ( indexAttr ) {
  20335. indexArr[ 0 ] = indexAttr.getX( i );
  20336. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20337. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20338. } else {
  20339. indexArr[ 0 ] = i;
  20340. indexArr[ 1 ] = i + 1;
  20341. indexArr[ 2 ] = i + 2;
  20342. }
  20343. const { a, b, c } = _triangle;
  20344. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20345. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20346. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20347. _triangle.getNormal( _normal );
  20348. // create hashes for the edge from the vertices
  20349. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20350. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20351. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20352. // skip degenerate triangles
  20353. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20354. continue;
  20355. }
  20356. // iterate over every edge
  20357. for ( let j = 0; j < 3; j ++ ) {
  20358. // get the first and next vertex making up the edge
  20359. const jNext = ( j + 1 ) % 3;
  20360. const vecHash0 = hashes[ j ];
  20361. const vecHash1 = hashes[ jNext ];
  20362. const v0 = _triangle[ vertKeys[ j ] ];
  20363. const v1 = _triangle[ vertKeys[ jNext ] ];
  20364. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20365. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20366. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20367. // if we found a sibling edge add it into the vertex array if
  20368. // it meets the angle threshold and delete the edge from the map.
  20369. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20370. vertices.push( v0.x, v0.y, v0.z );
  20371. vertices.push( v1.x, v1.y, v1.z );
  20372. }
  20373. edgeData[ reverseHash ] = null;
  20374. } else if ( ! ( hash in edgeData ) ) {
  20375. // if we've already got an edge here then skip adding a new one
  20376. edgeData[ hash ] = {
  20377. index0: indexArr[ j ],
  20378. index1: indexArr[ jNext ],
  20379. normal: _normal.clone(),
  20380. };
  20381. }
  20382. }
  20383. }
  20384. // iterate over all remaining, unmatched edges and add them to the vertex array
  20385. for ( const key in edgeData ) {
  20386. if ( edgeData[ key ] ) {
  20387. const { index0, index1 } = edgeData[ key ];
  20388. _v0.fromBufferAttribute( positionAttr, index0 );
  20389. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20390. vertices.push( _v0.x, _v0.y, _v0.z );
  20391. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20392. }
  20393. }
  20394. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20395. }
  20396. }
  20397. }
  20398. class Shape extends Path {
  20399. constructor( points ) {
  20400. super( points );
  20401. this.uuid = generateUUID();
  20402. this.type = 'Shape';
  20403. this.holes = [];
  20404. }
  20405. getPointsHoles( divisions ) {
  20406. const holesPts = [];
  20407. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20408. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20409. }
  20410. return holesPts;
  20411. }
  20412. // get points of shape and holes (keypoints based on segments parameter)
  20413. extractPoints( divisions ) {
  20414. return {
  20415. shape: this.getPoints( divisions ),
  20416. holes: this.getPointsHoles( divisions )
  20417. };
  20418. }
  20419. copy( source ) {
  20420. super.copy( source );
  20421. this.holes = [];
  20422. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20423. const hole = source.holes[ i ];
  20424. this.holes.push( hole.clone() );
  20425. }
  20426. return this;
  20427. }
  20428. toJSON() {
  20429. const data = super.toJSON();
  20430. data.uuid = this.uuid;
  20431. data.holes = [];
  20432. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20433. const hole = this.holes[ i ];
  20434. data.holes.push( hole.toJSON() );
  20435. }
  20436. return data;
  20437. }
  20438. fromJSON( json ) {
  20439. super.fromJSON( json );
  20440. this.uuid = json.uuid;
  20441. this.holes = [];
  20442. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20443. const hole = json.holes[ i ];
  20444. this.holes.push( new Path().fromJSON( hole ) );
  20445. }
  20446. return this;
  20447. }
  20448. }
  20449. /**
  20450. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20451. */
  20452. const Earcut = {
  20453. triangulate: function ( data, holeIndices, dim = 2 ) {
  20454. const hasHoles = holeIndices && holeIndices.length;
  20455. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20456. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20457. const triangles = [];
  20458. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20459. let minX, minY, maxX, maxY, x, y, invSize;
  20460. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20461. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20462. if ( data.length > 80 * dim ) {
  20463. minX = maxX = data[ 0 ];
  20464. minY = maxY = data[ 1 ];
  20465. for ( let i = dim; i < outerLen; i += dim ) {
  20466. x = data[ i ];
  20467. y = data[ i + 1 ];
  20468. if ( x < minX ) minX = x;
  20469. if ( y < minY ) minY = y;
  20470. if ( x > maxX ) maxX = x;
  20471. if ( y > maxY ) maxY = y;
  20472. }
  20473. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20474. invSize = Math.max( maxX - minX, maxY - minY );
  20475. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20476. }
  20477. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20478. return triangles;
  20479. }
  20480. };
  20481. // create a circular doubly linked list from polygon points in the specified winding order
  20482. function linkedList( data, start, end, dim, clockwise ) {
  20483. let i, last;
  20484. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20485. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20486. } else {
  20487. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20488. }
  20489. if ( last && equals( last, last.next ) ) {
  20490. removeNode( last );
  20491. last = last.next;
  20492. }
  20493. return last;
  20494. }
  20495. // eliminate colinear or duplicate points
  20496. function filterPoints( start, end ) {
  20497. if ( ! start ) return start;
  20498. if ( ! end ) end = start;
  20499. let p = start,
  20500. again;
  20501. do {
  20502. again = false;
  20503. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20504. removeNode( p );
  20505. p = end = p.prev;
  20506. if ( p === p.next ) break;
  20507. again = true;
  20508. } else {
  20509. p = p.next;
  20510. }
  20511. } while ( again || p !== end );
  20512. return end;
  20513. }
  20514. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20515. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20516. if ( ! ear ) return;
  20517. // interlink polygon nodes in z-order
  20518. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20519. let stop = ear,
  20520. prev, next;
  20521. // iterate through ears, slicing them one by one
  20522. while ( ear.prev !== ear.next ) {
  20523. prev = ear.prev;
  20524. next = ear.next;
  20525. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20526. // cut off the triangle
  20527. triangles.push( prev.i / dim | 0 );
  20528. triangles.push( ear.i / dim | 0 );
  20529. triangles.push( next.i / dim | 0 );
  20530. removeNode( ear );
  20531. // skipping the next vertex leads to less sliver triangles
  20532. ear = next.next;
  20533. stop = next.next;
  20534. continue;
  20535. }
  20536. ear = next;
  20537. // if we looped through the whole remaining polygon and can't find any more ears
  20538. if ( ear === stop ) {
  20539. // try filtering points and slicing again
  20540. if ( ! pass ) {
  20541. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20542. // if this didn't work, try curing all small self-intersections locally
  20543. } else if ( pass === 1 ) {
  20544. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20545. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20546. // as a last resort, try splitting the remaining polygon into two
  20547. } else if ( pass === 2 ) {
  20548. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20549. }
  20550. break;
  20551. }
  20552. }
  20553. }
  20554. // check whether a polygon node forms a valid ear with adjacent nodes
  20555. function isEar( ear ) {
  20556. const a = ear.prev,
  20557. b = ear,
  20558. c = ear.next;
  20559. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20560. // now make sure we don't have other points inside the potential ear
  20561. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20562. // triangle bbox; min & max are calculated like this for speed
  20563. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20564. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20565. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20566. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20567. let p = c.next;
  20568. while ( p !== a ) {
  20569. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20570. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20571. area( p.prev, p, p.next ) >= 0 ) return false;
  20572. p = p.next;
  20573. }
  20574. return true;
  20575. }
  20576. function isEarHashed( ear, minX, minY, invSize ) {
  20577. const a = ear.prev,
  20578. b = ear,
  20579. c = ear.next;
  20580. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20581. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20582. // triangle bbox; min & max are calculated like this for speed
  20583. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20584. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20585. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20586. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20587. // z-order range for the current triangle bbox;
  20588. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20589. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20590. let p = ear.prevZ,
  20591. n = ear.nextZ;
  20592. // look for points inside the triangle in both directions
  20593. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20594. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20595. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20596. p = p.prevZ;
  20597. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20598. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20599. n = n.nextZ;
  20600. }
  20601. // look for remaining points in decreasing z-order
  20602. while ( p && p.z >= minZ ) {
  20603. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20604. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20605. p = p.prevZ;
  20606. }
  20607. // look for remaining points in increasing z-order
  20608. while ( n && n.z <= maxZ ) {
  20609. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20610. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20611. n = n.nextZ;
  20612. }
  20613. return true;
  20614. }
  20615. // go through all polygon nodes and cure small local self-intersections
  20616. function cureLocalIntersections( start, triangles, dim ) {
  20617. let p = start;
  20618. do {
  20619. const a = p.prev,
  20620. b = p.next.next;
  20621. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20622. triangles.push( a.i / dim | 0 );
  20623. triangles.push( p.i / dim | 0 );
  20624. triangles.push( b.i / dim | 0 );
  20625. // remove two nodes involved
  20626. removeNode( p );
  20627. removeNode( p.next );
  20628. p = start = b;
  20629. }
  20630. p = p.next;
  20631. } while ( p !== start );
  20632. return filterPoints( p );
  20633. }
  20634. // try splitting polygon into two and triangulate them independently
  20635. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20636. // look for a valid diagonal that divides the polygon into two
  20637. let a = start;
  20638. do {
  20639. let b = a.next.next;
  20640. while ( b !== a.prev ) {
  20641. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20642. // split the polygon in two by the diagonal
  20643. let c = splitPolygon( a, b );
  20644. // filter colinear points around the cuts
  20645. a = filterPoints( a, a.next );
  20646. c = filterPoints( c, c.next );
  20647. // run earcut on each half
  20648. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20649. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20650. return;
  20651. }
  20652. b = b.next;
  20653. }
  20654. a = a.next;
  20655. } while ( a !== start );
  20656. }
  20657. // link every hole into the outer loop, producing a single-ring polygon without holes
  20658. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20659. const queue = [];
  20660. let i, len, start, end, list;
  20661. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20662. start = holeIndices[ i ] * dim;
  20663. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20664. list = linkedList( data, start, end, dim, false );
  20665. if ( list === list.next ) list.steiner = true;
  20666. queue.push( getLeftmost( list ) );
  20667. }
  20668. queue.sort( compareX );
  20669. // process holes from left to right
  20670. for ( i = 0; i < queue.length; i ++ ) {
  20671. outerNode = eliminateHole( queue[ i ], outerNode );
  20672. }
  20673. return outerNode;
  20674. }
  20675. function compareX( a, b ) {
  20676. return a.x - b.x;
  20677. }
  20678. // find a bridge between vertices that connects hole with an outer ring and link it
  20679. function eliminateHole( hole, outerNode ) {
  20680. const bridge = findHoleBridge( hole, outerNode );
  20681. if ( ! bridge ) {
  20682. return outerNode;
  20683. }
  20684. const bridgeReverse = splitPolygon( bridge, hole );
  20685. // filter collinear points around the cuts
  20686. filterPoints( bridgeReverse, bridgeReverse.next );
  20687. return filterPoints( bridge, bridge.next );
  20688. }
  20689. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20690. function findHoleBridge( hole, outerNode ) {
  20691. let p = outerNode,
  20692. qx = - Infinity,
  20693. m;
  20694. const hx = hole.x, hy = hole.y;
  20695. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20696. // segment's endpoint with lesser x will be potential connection point
  20697. do {
  20698. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20699. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20700. if ( x <= hx && x > qx ) {
  20701. qx = x;
  20702. m = p.x < p.next.x ? p : p.next;
  20703. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20704. }
  20705. }
  20706. p = p.next;
  20707. } while ( p !== outerNode );
  20708. if ( ! m ) return null;
  20709. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20710. // if there are no points found, we have a valid connection;
  20711. // otherwise choose the point of the minimum angle with the ray as connection point
  20712. const stop = m,
  20713. mx = m.x,
  20714. my = m.y;
  20715. let tanMin = Infinity, tan;
  20716. p = m;
  20717. do {
  20718. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20719. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20720. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20721. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20722. m = p;
  20723. tanMin = tan;
  20724. }
  20725. }
  20726. p = p.next;
  20727. } while ( p !== stop );
  20728. return m;
  20729. }
  20730. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20731. function sectorContainsSector( m, p ) {
  20732. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20733. }
  20734. // interlink polygon nodes in z-order
  20735. function indexCurve( start, minX, minY, invSize ) {
  20736. let p = start;
  20737. do {
  20738. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20739. p.prevZ = p.prev;
  20740. p.nextZ = p.next;
  20741. p = p.next;
  20742. } while ( p !== start );
  20743. p.prevZ.nextZ = null;
  20744. p.prevZ = null;
  20745. sortLinked( p );
  20746. }
  20747. // Simon Tatham's linked list merge sort algorithm
  20748. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20749. function sortLinked( list ) {
  20750. let i, p, q, e, tail, numMerges, pSize, qSize,
  20751. inSize = 1;
  20752. do {
  20753. p = list;
  20754. list = null;
  20755. tail = null;
  20756. numMerges = 0;
  20757. while ( p ) {
  20758. numMerges ++;
  20759. q = p;
  20760. pSize = 0;
  20761. for ( i = 0; i < inSize; i ++ ) {
  20762. pSize ++;
  20763. q = q.nextZ;
  20764. if ( ! q ) break;
  20765. }
  20766. qSize = inSize;
  20767. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20768. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20769. e = p;
  20770. p = p.nextZ;
  20771. pSize --;
  20772. } else {
  20773. e = q;
  20774. q = q.nextZ;
  20775. qSize --;
  20776. }
  20777. if ( tail ) tail.nextZ = e;
  20778. else list = e;
  20779. e.prevZ = tail;
  20780. tail = e;
  20781. }
  20782. p = q;
  20783. }
  20784. tail.nextZ = null;
  20785. inSize *= 2;
  20786. } while ( numMerges > 1 );
  20787. return list;
  20788. }
  20789. // z-order of a point given coords and inverse of the longer side of data bbox
  20790. function zOrder( x, y, minX, minY, invSize ) {
  20791. // coords are transformed into non-negative 15-bit integer range
  20792. x = ( x - minX ) * invSize | 0;
  20793. y = ( y - minY ) * invSize | 0;
  20794. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20795. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20796. x = ( x | ( x << 2 ) ) & 0x33333333;
  20797. x = ( x | ( x << 1 ) ) & 0x55555555;
  20798. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20799. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20800. y = ( y | ( y << 2 ) ) & 0x33333333;
  20801. y = ( y | ( y << 1 ) ) & 0x55555555;
  20802. return x | ( y << 1 );
  20803. }
  20804. // find the leftmost node of a polygon ring
  20805. function getLeftmost( start ) {
  20806. let p = start,
  20807. leftmost = start;
  20808. do {
  20809. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20810. p = p.next;
  20811. } while ( p !== start );
  20812. return leftmost;
  20813. }
  20814. // check if a point lies within a convex triangle
  20815. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20816. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20817. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20818. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20819. }
  20820. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20821. function isValidDiagonal( a, b ) {
  20822. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20823. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20824. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20825. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20826. }
  20827. // signed area of a triangle
  20828. function area( p, q, r ) {
  20829. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20830. }
  20831. // check if two points are equal
  20832. function equals( p1, p2 ) {
  20833. return p1.x === p2.x && p1.y === p2.y;
  20834. }
  20835. // check if two segments intersect
  20836. function intersects( p1, q1, p2, q2 ) {
  20837. const o1 = sign( area( p1, q1, p2 ) );
  20838. const o2 = sign( area( p1, q1, q2 ) );
  20839. const o3 = sign( area( p2, q2, p1 ) );
  20840. const o4 = sign( area( p2, q2, q1 ) );
  20841. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20842. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20843. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20844. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20845. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20846. return false;
  20847. }
  20848. // for collinear points p, q, r, check if point q lies on segment pr
  20849. function onSegment( p, q, r ) {
  20850. 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 );
  20851. }
  20852. function sign( num ) {
  20853. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20854. }
  20855. // check if a polygon diagonal intersects any polygon segments
  20856. function intersectsPolygon( a, b ) {
  20857. let p = a;
  20858. do {
  20859. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20860. intersects( p, p.next, a, b ) ) return true;
  20861. p = p.next;
  20862. } while ( p !== a );
  20863. return false;
  20864. }
  20865. // check if a polygon diagonal is locally inside the polygon
  20866. function locallyInside( a, b ) {
  20867. return area( a.prev, a, a.next ) < 0 ?
  20868. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20869. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20870. }
  20871. // check if the middle point of a polygon diagonal is inside the polygon
  20872. function middleInside( a, b ) {
  20873. let p = a,
  20874. inside = false;
  20875. const px = ( a.x + b.x ) / 2,
  20876. py = ( a.y + b.y ) / 2;
  20877. do {
  20878. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20879. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20880. inside = ! inside;
  20881. p = p.next;
  20882. } while ( p !== a );
  20883. return inside;
  20884. }
  20885. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20886. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20887. function splitPolygon( a, b ) {
  20888. const a2 = new Node( a.i, a.x, a.y ),
  20889. b2 = new Node( b.i, b.x, b.y ),
  20890. an = a.next,
  20891. bp = b.prev;
  20892. a.next = b;
  20893. b.prev = a;
  20894. a2.next = an;
  20895. an.prev = a2;
  20896. b2.next = a2;
  20897. a2.prev = b2;
  20898. bp.next = b2;
  20899. b2.prev = bp;
  20900. return b2;
  20901. }
  20902. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20903. function insertNode( i, x, y, last ) {
  20904. const p = new Node( i, x, y );
  20905. if ( ! last ) {
  20906. p.prev = p;
  20907. p.next = p;
  20908. } else {
  20909. p.next = last.next;
  20910. p.prev = last;
  20911. last.next.prev = p;
  20912. last.next = p;
  20913. }
  20914. return p;
  20915. }
  20916. function removeNode( p ) {
  20917. p.next.prev = p.prev;
  20918. p.prev.next = p.next;
  20919. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20920. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20921. }
  20922. function Node( i, x, y ) {
  20923. // vertex index in coordinates array
  20924. this.i = i;
  20925. // vertex coordinates
  20926. this.x = x;
  20927. this.y = y;
  20928. // previous and next vertex nodes in a polygon ring
  20929. this.prev = null;
  20930. this.next = null;
  20931. // z-order curve value
  20932. this.z = 0;
  20933. // previous and next nodes in z-order
  20934. this.prevZ = null;
  20935. this.nextZ = null;
  20936. // indicates whether this is a steiner point
  20937. this.steiner = false;
  20938. }
  20939. function signedArea( data, start, end, dim ) {
  20940. let sum = 0;
  20941. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20942. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20943. j = i;
  20944. }
  20945. return sum;
  20946. }
  20947. class ShapeUtils {
  20948. // calculate area of the contour polygon
  20949. static area( contour ) {
  20950. const n = contour.length;
  20951. let a = 0.0;
  20952. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20953. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20954. }
  20955. return a * 0.5;
  20956. }
  20957. static isClockWise( pts ) {
  20958. return ShapeUtils.area( pts ) < 0;
  20959. }
  20960. static triangulateShape( contour, holes ) {
  20961. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20962. const holeIndices = []; // array of hole indices
  20963. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20964. removeDupEndPts( contour );
  20965. addContour( vertices, contour );
  20966. //
  20967. let holeIndex = contour.length;
  20968. holes.forEach( removeDupEndPts );
  20969. for ( let i = 0; i < holes.length; i ++ ) {
  20970. holeIndices.push( holeIndex );
  20971. holeIndex += holes[ i ].length;
  20972. addContour( vertices, holes[ i ] );
  20973. }
  20974. //
  20975. const triangles = Earcut.triangulate( vertices, holeIndices );
  20976. //
  20977. for ( let i = 0; i < triangles.length; i += 3 ) {
  20978. faces.push( triangles.slice( i, i + 3 ) );
  20979. }
  20980. return faces;
  20981. }
  20982. }
  20983. function removeDupEndPts( points ) {
  20984. const l = points.length;
  20985. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20986. points.pop();
  20987. }
  20988. }
  20989. function addContour( vertices, contour ) {
  20990. for ( let i = 0; i < contour.length; i ++ ) {
  20991. vertices.push( contour[ i ].x );
  20992. vertices.push( contour[ i ].y );
  20993. }
  20994. }
  20995. /**
  20996. * Creates extruded geometry from a path shape.
  20997. *
  20998. * parameters = {
  20999. *
  21000. * curveSegments: <int>, // number of points on the curves
  21001. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21002. * depth: <float>, // Depth to extrude the shape
  21003. *
  21004. * bevelEnabled: <bool>, // turn on bevel
  21005. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21006. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21007. * bevelOffset: <float>, // how far from shape outline does bevel start
  21008. * bevelSegments: <int>, // number of bevel layers
  21009. *
  21010. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21011. *
  21012. * UVGenerator: <Object> // object that provides UV generator functions
  21013. *
  21014. * }
  21015. */
  21016. class ExtrudeGeometry extends BufferGeometry {
  21017. 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 = {} ) {
  21018. super();
  21019. this.type = 'ExtrudeGeometry';
  21020. this.parameters = {
  21021. shapes: shapes,
  21022. options: options
  21023. };
  21024. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21025. const scope = this;
  21026. const verticesArray = [];
  21027. const uvArray = [];
  21028. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21029. const shape = shapes[ i ];
  21030. addShape( shape );
  21031. }
  21032. // build geometry
  21033. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21034. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21035. this.computeVertexNormals();
  21036. // functions
  21037. function addShape( shape ) {
  21038. const placeholder = [];
  21039. // options
  21040. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21041. const steps = options.steps !== undefined ? options.steps : 1;
  21042. const depth = options.depth !== undefined ? options.depth : 1;
  21043. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21044. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21045. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21046. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21047. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21048. const extrudePath = options.extrudePath;
  21049. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21050. //
  21051. let extrudePts, extrudeByPath = false;
  21052. let splineTube, binormal, normal, position2;
  21053. if ( extrudePath ) {
  21054. extrudePts = extrudePath.getSpacedPoints( steps );
  21055. extrudeByPath = true;
  21056. bevelEnabled = false; // bevels not supported for path extrusion
  21057. // SETUP TNB variables
  21058. // TODO1 - have a .isClosed in spline?
  21059. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21060. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21061. binormal = new Vector3();
  21062. normal = new Vector3();
  21063. position2 = new Vector3();
  21064. }
  21065. // Safeguards if bevels are not enabled
  21066. if ( ! bevelEnabled ) {
  21067. bevelSegments = 0;
  21068. bevelThickness = 0;
  21069. bevelSize = 0;
  21070. bevelOffset = 0;
  21071. }
  21072. // Variables initialization
  21073. const shapePoints = shape.extractPoints( curveSegments );
  21074. let vertices = shapePoints.shape;
  21075. const holes = shapePoints.holes;
  21076. const reverse = ! ShapeUtils.isClockWise( vertices );
  21077. if ( reverse ) {
  21078. vertices = vertices.reverse();
  21079. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21080. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21081. const ahole = holes[ h ];
  21082. if ( ShapeUtils.isClockWise( ahole ) ) {
  21083. holes[ h ] = ahole.reverse();
  21084. }
  21085. }
  21086. }
  21087. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21088. /* Vertices */
  21089. const contour = vertices; // vertices has all points but contour has only points of circumference
  21090. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21091. const ahole = holes[ h ];
  21092. vertices = vertices.concat( ahole );
  21093. }
  21094. function scalePt2( pt, vec, size ) {
  21095. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21096. return vec.clone().multiplyScalar( size ).add( pt );
  21097. }
  21098. const vlen = vertices.length, flen = faces.length;
  21099. // Find directions for point movement
  21100. function getBevelVec( inPt, inPrev, inNext ) {
  21101. // computes for inPt the corresponding point inPt' on a new contour
  21102. // shifted by 1 unit (length of normalized vector) to the left
  21103. // if we walk along contour clockwise, this new contour is outside the old one
  21104. //
  21105. // inPt' is the intersection of the two lines parallel to the two
  21106. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21107. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21108. // good reading for geometry algorithms (here: line-line intersection)
  21109. // http://geomalgorithms.com/a05-_intersect-1.html
  21110. const v_prev_x = inPt.x - inPrev.x,
  21111. v_prev_y = inPt.y - inPrev.y;
  21112. const v_next_x = inNext.x - inPt.x,
  21113. v_next_y = inNext.y - inPt.y;
  21114. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21115. // check for collinear edges
  21116. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21117. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21118. // not collinear
  21119. // length of vectors for normalizing
  21120. const v_prev_len = Math.sqrt( v_prev_lensq );
  21121. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21122. // shift adjacent points by unit vectors to the left
  21123. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21124. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21125. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21126. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21127. // scaling factor for v_prev to intersection point
  21128. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21129. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21130. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21131. // vector from inPt to intersection point
  21132. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21133. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21134. // Don't normalize!, otherwise sharp corners become ugly
  21135. // but prevent crazy spikes
  21136. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21137. if ( v_trans_lensq <= 2 ) {
  21138. return new Vector2( v_trans_x, v_trans_y );
  21139. } else {
  21140. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21141. }
  21142. } else {
  21143. // handle special case of collinear edges
  21144. let direction_eq = false; // assumes: opposite
  21145. if ( v_prev_x > Number.EPSILON ) {
  21146. if ( v_next_x > Number.EPSILON ) {
  21147. direction_eq = true;
  21148. }
  21149. } else {
  21150. if ( v_prev_x < - Number.EPSILON ) {
  21151. if ( v_next_x < - Number.EPSILON ) {
  21152. direction_eq = true;
  21153. }
  21154. } else {
  21155. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21156. direction_eq = true;
  21157. }
  21158. }
  21159. }
  21160. if ( direction_eq ) {
  21161. // console.log("Warning: lines are a straight sequence");
  21162. v_trans_x = - v_prev_y;
  21163. v_trans_y = v_prev_x;
  21164. shrink_by = Math.sqrt( v_prev_lensq );
  21165. } else {
  21166. // console.log("Warning: lines are a straight spike");
  21167. v_trans_x = v_prev_x;
  21168. v_trans_y = v_prev_y;
  21169. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21170. }
  21171. }
  21172. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21173. }
  21174. const contourMovements = [];
  21175. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21176. if ( j === il ) j = 0;
  21177. if ( k === il ) k = 0;
  21178. // (j)---(i)---(k)
  21179. // console.log('i,j,k', i, j , k)
  21180. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21181. }
  21182. const holesMovements = [];
  21183. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21184. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21185. const ahole = holes[ h ];
  21186. oneHoleMovements = [];
  21187. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21188. if ( j === il ) j = 0;
  21189. if ( k === il ) k = 0;
  21190. // (j)---(i)---(k)
  21191. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21192. }
  21193. holesMovements.push( oneHoleMovements );
  21194. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21195. }
  21196. // Loop bevelSegments, 1 for the front, 1 for the back
  21197. for ( let b = 0; b < bevelSegments; b ++ ) {
  21198. //for ( b = bevelSegments; b > 0; b -- ) {
  21199. const t = b / bevelSegments;
  21200. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21201. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21202. // contract shape
  21203. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21204. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21205. v( vert.x, vert.y, - z );
  21206. }
  21207. // expand holes
  21208. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21209. const ahole = holes[ h ];
  21210. oneHoleMovements = holesMovements[ h ];
  21211. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21212. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21213. v( vert.x, vert.y, - z );
  21214. }
  21215. }
  21216. }
  21217. const bs = bevelSize + bevelOffset;
  21218. // Back facing vertices
  21219. for ( let i = 0; i < vlen; i ++ ) {
  21220. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21221. if ( ! extrudeByPath ) {
  21222. v( vert.x, vert.y, 0 );
  21223. } else {
  21224. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21225. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21226. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21227. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21228. v( position2.x, position2.y, position2.z );
  21229. }
  21230. }
  21231. // Add stepped vertices...
  21232. // Including front facing vertices
  21233. for ( let s = 1; s <= steps; s ++ ) {
  21234. for ( let i = 0; i < vlen; i ++ ) {
  21235. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21236. if ( ! extrudeByPath ) {
  21237. v( vert.x, vert.y, depth / steps * s );
  21238. } else {
  21239. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21240. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21241. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21242. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21243. v( position2.x, position2.y, position2.z );
  21244. }
  21245. }
  21246. }
  21247. // Add bevel segments planes
  21248. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21249. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21250. const t = b / bevelSegments;
  21251. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21252. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21253. // contract shape
  21254. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21255. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21256. v( vert.x, vert.y, depth + z );
  21257. }
  21258. // expand holes
  21259. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21260. const ahole = holes[ h ];
  21261. oneHoleMovements = holesMovements[ h ];
  21262. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21263. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21264. if ( ! extrudeByPath ) {
  21265. v( vert.x, vert.y, depth + z );
  21266. } else {
  21267. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21268. }
  21269. }
  21270. }
  21271. }
  21272. /* Faces */
  21273. // Top and bottom faces
  21274. buildLidFaces();
  21275. // Sides faces
  21276. buildSideFaces();
  21277. ///// Internal functions
  21278. function buildLidFaces() {
  21279. const start = verticesArray.length / 3;
  21280. if ( bevelEnabled ) {
  21281. let layer = 0; // steps + 1
  21282. let offset = vlen * layer;
  21283. // Bottom faces
  21284. for ( let i = 0; i < flen; i ++ ) {
  21285. const face = faces[ i ];
  21286. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21287. }
  21288. layer = steps + bevelSegments * 2;
  21289. offset = vlen * layer;
  21290. // Top faces
  21291. for ( let i = 0; i < flen; i ++ ) {
  21292. const face = faces[ i ];
  21293. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21294. }
  21295. } else {
  21296. // Bottom faces
  21297. for ( let i = 0; i < flen; i ++ ) {
  21298. const face = faces[ i ];
  21299. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21300. }
  21301. // Top faces
  21302. for ( let i = 0; i < flen; i ++ ) {
  21303. const face = faces[ i ];
  21304. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21305. }
  21306. }
  21307. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21308. }
  21309. // Create faces for the z-sides of the shape
  21310. function buildSideFaces() {
  21311. const start = verticesArray.length / 3;
  21312. let layeroffset = 0;
  21313. sidewalls( contour, layeroffset );
  21314. layeroffset += contour.length;
  21315. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21316. const ahole = holes[ h ];
  21317. sidewalls( ahole, layeroffset );
  21318. //, true
  21319. layeroffset += ahole.length;
  21320. }
  21321. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21322. }
  21323. function sidewalls( contour, layeroffset ) {
  21324. let i = contour.length;
  21325. while ( -- i >= 0 ) {
  21326. const j = i;
  21327. let k = i - 1;
  21328. if ( k < 0 ) k = contour.length - 1;
  21329. //console.log('b', i,j, i-1, k,vertices.length);
  21330. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21331. const slen1 = vlen * s;
  21332. const slen2 = vlen * ( s + 1 );
  21333. const a = layeroffset + j + slen1,
  21334. b = layeroffset + k + slen1,
  21335. c = layeroffset + k + slen2,
  21336. d = layeroffset + j + slen2;
  21337. f4( a, b, c, d );
  21338. }
  21339. }
  21340. }
  21341. function v( x, y, z ) {
  21342. placeholder.push( x );
  21343. placeholder.push( y );
  21344. placeholder.push( z );
  21345. }
  21346. function f3( a, b, c ) {
  21347. addVertex( a );
  21348. addVertex( b );
  21349. addVertex( c );
  21350. const nextIndex = verticesArray.length / 3;
  21351. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21352. addUV( uvs[ 0 ] );
  21353. addUV( uvs[ 1 ] );
  21354. addUV( uvs[ 2 ] );
  21355. }
  21356. function f4( a, b, c, d ) {
  21357. addVertex( a );
  21358. addVertex( b );
  21359. addVertex( d );
  21360. addVertex( b );
  21361. addVertex( c );
  21362. addVertex( d );
  21363. const nextIndex = verticesArray.length / 3;
  21364. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21365. addUV( uvs[ 0 ] );
  21366. addUV( uvs[ 1 ] );
  21367. addUV( uvs[ 3 ] );
  21368. addUV( uvs[ 1 ] );
  21369. addUV( uvs[ 2 ] );
  21370. addUV( uvs[ 3 ] );
  21371. }
  21372. function addVertex( index ) {
  21373. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21374. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21375. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21376. }
  21377. function addUV( vector2 ) {
  21378. uvArray.push( vector2.x );
  21379. uvArray.push( vector2.y );
  21380. }
  21381. }
  21382. }
  21383. toJSON() {
  21384. const data = super.toJSON();
  21385. const shapes = this.parameters.shapes;
  21386. const options = this.parameters.options;
  21387. return toJSON$1( shapes, options, data );
  21388. }
  21389. static fromJSON( data, shapes ) {
  21390. const geometryShapes = [];
  21391. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21392. const shape = shapes[ data.shapes[ j ] ];
  21393. geometryShapes.push( shape );
  21394. }
  21395. const extrudePath = data.options.extrudePath;
  21396. if ( extrudePath !== undefined ) {
  21397. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21398. }
  21399. return new ExtrudeGeometry( geometryShapes, data.options );
  21400. }
  21401. }
  21402. const WorldUVGenerator = {
  21403. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21404. const a_x = vertices[ indexA * 3 ];
  21405. const a_y = vertices[ indexA * 3 + 1 ];
  21406. const b_x = vertices[ indexB * 3 ];
  21407. const b_y = vertices[ indexB * 3 + 1 ];
  21408. const c_x = vertices[ indexC * 3 ];
  21409. const c_y = vertices[ indexC * 3 + 1 ];
  21410. return [
  21411. new Vector2( a_x, a_y ),
  21412. new Vector2( b_x, b_y ),
  21413. new Vector2( c_x, c_y )
  21414. ];
  21415. },
  21416. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21417. const a_x = vertices[ indexA * 3 ];
  21418. const a_y = vertices[ indexA * 3 + 1 ];
  21419. const a_z = vertices[ indexA * 3 + 2 ];
  21420. const b_x = vertices[ indexB * 3 ];
  21421. const b_y = vertices[ indexB * 3 + 1 ];
  21422. const b_z = vertices[ indexB * 3 + 2 ];
  21423. const c_x = vertices[ indexC * 3 ];
  21424. const c_y = vertices[ indexC * 3 + 1 ];
  21425. const c_z = vertices[ indexC * 3 + 2 ];
  21426. const d_x = vertices[ indexD * 3 ];
  21427. const d_y = vertices[ indexD * 3 + 1 ];
  21428. const d_z = vertices[ indexD * 3 + 2 ];
  21429. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21430. return [
  21431. new Vector2( a_x, 1 - a_z ),
  21432. new Vector2( b_x, 1 - b_z ),
  21433. new Vector2( c_x, 1 - c_z ),
  21434. new Vector2( d_x, 1 - d_z )
  21435. ];
  21436. } else {
  21437. return [
  21438. new Vector2( a_y, 1 - a_z ),
  21439. new Vector2( b_y, 1 - b_z ),
  21440. new Vector2( c_y, 1 - c_z ),
  21441. new Vector2( d_y, 1 - d_z )
  21442. ];
  21443. }
  21444. }
  21445. };
  21446. function toJSON$1( shapes, options, data ) {
  21447. data.shapes = [];
  21448. if ( Array.isArray( shapes ) ) {
  21449. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21450. const shape = shapes[ i ];
  21451. data.shapes.push( shape.uuid );
  21452. }
  21453. } else {
  21454. data.shapes.push( shapes.uuid );
  21455. }
  21456. data.options = Object.assign( {}, options );
  21457. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21458. return data;
  21459. }
  21460. class IcosahedronGeometry extends PolyhedronGeometry {
  21461. constructor( radius = 1, detail = 0 ) {
  21462. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21463. const vertices = [
  21464. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21465. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21466. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21467. ];
  21468. const indices = [
  21469. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21470. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21471. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21472. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21473. ];
  21474. super( vertices, indices, radius, detail );
  21475. this.type = 'IcosahedronGeometry';
  21476. this.parameters = {
  21477. radius: radius,
  21478. detail: detail
  21479. };
  21480. }
  21481. static fromJSON( data ) {
  21482. return new IcosahedronGeometry( data.radius, data.detail );
  21483. }
  21484. }
  21485. class OctahedronGeometry extends PolyhedronGeometry {
  21486. constructor( radius = 1, detail = 0 ) {
  21487. const vertices = [
  21488. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21489. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21490. ];
  21491. const indices = [
  21492. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21493. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21494. 1, 3, 4, 1, 4, 2
  21495. ];
  21496. super( vertices, indices, radius, detail );
  21497. this.type = 'OctahedronGeometry';
  21498. this.parameters = {
  21499. radius: radius,
  21500. detail: detail
  21501. };
  21502. }
  21503. static fromJSON( data ) {
  21504. return new OctahedronGeometry( data.radius, data.detail );
  21505. }
  21506. }
  21507. class RingGeometry extends BufferGeometry {
  21508. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21509. super();
  21510. this.type = 'RingGeometry';
  21511. this.parameters = {
  21512. innerRadius: innerRadius,
  21513. outerRadius: outerRadius,
  21514. thetaSegments: thetaSegments,
  21515. phiSegments: phiSegments,
  21516. thetaStart: thetaStart,
  21517. thetaLength: thetaLength
  21518. };
  21519. thetaSegments = Math.max( 3, thetaSegments );
  21520. phiSegments = Math.max( 1, phiSegments );
  21521. // buffers
  21522. const indices = [];
  21523. const vertices = [];
  21524. const normals = [];
  21525. const uvs = [];
  21526. // some helper variables
  21527. let radius = innerRadius;
  21528. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21529. const vertex = new Vector3();
  21530. const uv = new Vector2();
  21531. // generate vertices, normals and uvs
  21532. for ( let j = 0; j <= phiSegments; j ++ ) {
  21533. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21534. // values are generate from the inside of the ring to the outside
  21535. const segment = thetaStart + i / thetaSegments * thetaLength;
  21536. // vertex
  21537. vertex.x = radius * Math.cos( segment );
  21538. vertex.y = radius * Math.sin( segment );
  21539. vertices.push( vertex.x, vertex.y, vertex.z );
  21540. // normal
  21541. normals.push( 0, 0, 1 );
  21542. // uv
  21543. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21544. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21545. uvs.push( uv.x, uv.y );
  21546. }
  21547. // increase the radius for next row of vertices
  21548. radius += radiusStep;
  21549. }
  21550. // indices
  21551. for ( let j = 0; j < phiSegments; j ++ ) {
  21552. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21553. for ( let i = 0; i < thetaSegments; i ++ ) {
  21554. const segment = i + thetaSegmentLevel;
  21555. const a = segment;
  21556. const b = segment + thetaSegments + 1;
  21557. const c = segment + thetaSegments + 2;
  21558. const d = segment + 1;
  21559. // faces
  21560. indices.push( a, b, d );
  21561. indices.push( b, c, d );
  21562. }
  21563. }
  21564. // build geometry
  21565. this.setIndex( indices );
  21566. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21567. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21568. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21569. }
  21570. static fromJSON( data ) {
  21571. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21572. }
  21573. }
  21574. class ShapeGeometry extends BufferGeometry {
  21575. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21576. super();
  21577. this.type = 'ShapeGeometry';
  21578. this.parameters = {
  21579. shapes: shapes,
  21580. curveSegments: curveSegments
  21581. };
  21582. // buffers
  21583. const indices = [];
  21584. const vertices = [];
  21585. const normals = [];
  21586. const uvs = [];
  21587. // helper variables
  21588. let groupStart = 0;
  21589. let groupCount = 0;
  21590. // allow single and array values for "shapes" parameter
  21591. if ( Array.isArray( shapes ) === false ) {
  21592. addShape( shapes );
  21593. } else {
  21594. for ( let i = 0; i < shapes.length; i ++ ) {
  21595. addShape( shapes[ i ] );
  21596. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21597. groupStart += groupCount;
  21598. groupCount = 0;
  21599. }
  21600. }
  21601. // build geometry
  21602. this.setIndex( indices );
  21603. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21604. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21605. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21606. // helper functions
  21607. function addShape( shape ) {
  21608. const indexOffset = vertices.length / 3;
  21609. const points = shape.extractPoints( curveSegments );
  21610. let shapeVertices = points.shape;
  21611. const shapeHoles = points.holes;
  21612. // check direction of vertices
  21613. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21614. shapeVertices = shapeVertices.reverse();
  21615. }
  21616. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21617. const shapeHole = shapeHoles[ i ];
  21618. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21619. shapeHoles[ i ] = shapeHole.reverse();
  21620. }
  21621. }
  21622. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21623. // join vertices of inner and outer paths to a single array
  21624. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21625. const shapeHole = shapeHoles[ i ];
  21626. shapeVertices = shapeVertices.concat( shapeHole );
  21627. }
  21628. // vertices, normals, uvs
  21629. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21630. const vertex = shapeVertices[ i ];
  21631. vertices.push( vertex.x, vertex.y, 0 );
  21632. normals.push( 0, 0, 1 );
  21633. uvs.push( vertex.x, vertex.y ); // world uvs
  21634. }
  21635. // indices
  21636. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21637. const face = faces[ i ];
  21638. const a = face[ 0 ] + indexOffset;
  21639. const b = face[ 1 ] + indexOffset;
  21640. const c = face[ 2 ] + indexOffset;
  21641. indices.push( a, b, c );
  21642. groupCount += 3;
  21643. }
  21644. }
  21645. }
  21646. toJSON() {
  21647. const data = super.toJSON();
  21648. const shapes = this.parameters.shapes;
  21649. return toJSON( shapes, data );
  21650. }
  21651. static fromJSON( data, shapes ) {
  21652. const geometryShapes = [];
  21653. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21654. const shape = shapes[ data.shapes[ j ] ];
  21655. geometryShapes.push( shape );
  21656. }
  21657. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21658. }
  21659. }
  21660. function toJSON( shapes, data ) {
  21661. data.shapes = [];
  21662. if ( Array.isArray( shapes ) ) {
  21663. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21664. const shape = shapes[ i ];
  21665. data.shapes.push( shape.uuid );
  21666. }
  21667. } else {
  21668. data.shapes.push( shapes.uuid );
  21669. }
  21670. return data;
  21671. }
  21672. class SphereGeometry extends BufferGeometry {
  21673. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21674. super();
  21675. this.type = 'SphereGeometry';
  21676. this.parameters = {
  21677. radius: radius,
  21678. widthSegments: widthSegments,
  21679. heightSegments: heightSegments,
  21680. phiStart: phiStart,
  21681. phiLength: phiLength,
  21682. thetaStart: thetaStart,
  21683. thetaLength: thetaLength
  21684. };
  21685. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21686. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21687. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21688. let index = 0;
  21689. const grid = [];
  21690. const vertex = new Vector3();
  21691. const normal = new Vector3();
  21692. // buffers
  21693. const indices = [];
  21694. const vertices = [];
  21695. const normals = [];
  21696. const uvs = [];
  21697. // generate vertices, normals and uvs
  21698. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21699. const verticesRow = [];
  21700. const v = iy / heightSegments;
  21701. // special case for the poles
  21702. let uOffset = 0;
  21703. if ( iy == 0 && thetaStart == 0 ) {
  21704. uOffset = 0.5 / widthSegments;
  21705. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21706. uOffset = - 0.5 / widthSegments;
  21707. }
  21708. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21709. const u = ix / widthSegments;
  21710. // vertex
  21711. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21712. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21713. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21714. vertices.push( vertex.x, vertex.y, vertex.z );
  21715. // normal
  21716. normal.copy( vertex ).normalize();
  21717. normals.push( normal.x, normal.y, normal.z );
  21718. // uv
  21719. uvs.push( u + uOffset, 1 - v );
  21720. verticesRow.push( index ++ );
  21721. }
  21722. grid.push( verticesRow );
  21723. }
  21724. // indices
  21725. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21726. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21727. const a = grid[ iy ][ ix + 1 ];
  21728. const b = grid[ iy ][ ix ];
  21729. const c = grid[ iy + 1 ][ ix ];
  21730. const d = grid[ iy + 1 ][ ix + 1 ];
  21731. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21732. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21733. }
  21734. }
  21735. // build geometry
  21736. this.setIndex( indices );
  21737. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21738. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21739. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21740. }
  21741. static fromJSON( data ) {
  21742. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21743. }
  21744. }
  21745. class TetrahedronGeometry extends PolyhedronGeometry {
  21746. constructor( radius = 1, detail = 0 ) {
  21747. const vertices = [
  21748. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21749. ];
  21750. const indices = [
  21751. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21752. ];
  21753. super( vertices, indices, radius, detail );
  21754. this.type = 'TetrahedronGeometry';
  21755. this.parameters = {
  21756. radius: radius,
  21757. detail: detail
  21758. };
  21759. }
  21760. static fromJSON( data ) {
  21761. return new TetrahedronGeometry( data.radius, data.detail );
  21762. }
  21763. }
  21764. class TorusGeometry extends BufferGeometry {
  21765. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  21766. super();
  21767. this.type = 'TorusGeometry';
  21768. this.parameters = {
  21769. radius: radius,
  21770. tube: tube,
  21771. radialSegments: radialSegments,
  21772. tubularSegments: tubularSegments,
  21773. arc: arc
  21774. };
  21775. radialSegments = Math.floor( radialSegments );
  21776. tubularSegments = Math.floor( tubularSegments );
  21777. // buffers
  21778. const indices = [];
  21779. const vertices = [];
  21780. const normals = [];
  21781. const uvs = [];
  21782. // helper variables
  21783. const center = new Vector3();
  21784. const vertex = new Vector3();
  21785. const normal = new Vector3();
  21786. // generate vertices, normals and uvs
  21787. for ( let j = 0; j <= radialSegments; j ++ ) {
  21788. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21789. const u = i / tubularSegments * arc;
  21790. const v = j / radialSegments * Math.PI * 2;
  21791. // vertex
  21792. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21793. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21794. vertex.z = tube * Math.sin( v );
  21795. vertices.push( vertex.x, vertex.y, vertex.z );
  21796. // normal
  21797. center.x = radius * Math.cos( u );
  21798. center.y = radius * Math.sin( u );
  21799. normal.subVectors( vertex, center ).normalize();
  21800. normals.push( normal.x, normal.y, normal.z );
  21801. // uv
  21802. uvs.push( i / tubularSegments );
  21803. uvs.push( j / radialSegments );
  21804. }
  21805. }
  21806. // generate indices
  21807. for ( let j = 1; j <= radialSegments; j ++ ) {
  21808. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21809. // indices
  21810. const a = ( tubularSegments + 1 ) * j + i - 1;
  21811. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21812. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21813. const d = ( tubularSegments + 1 ) * j + i;
  21814. // faces
  21815. indices.push( a, b, d );
  21816. indices.push( b, c, d );
  21817. }
  21818. }
  21819. // build geometry
  21820. this.setIndex( indices );
  21821. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21822. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21823. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21824. }
  21825. static fromJSON( data ) {
  21826. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21827. }
  21828. }
  21829. class TorusKnotGeometry extends BufferGeometry {
  21830. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21831. super();
  21832. this.type = 'TorusKnotGeometry';
  21833. this.parameters = {
  21834. radius: radius,
  21835. tube: tube,
  21836. tubularSegments: tubularSegments,
  21837. radialSegments: radialSegments,
  21838. p: p,
  21839. q: q
  21840. };
  21841. tubularSegments = Math.floor( tubularSegments );
  21842. radialSegments = Math.floor( radialSegments );
  21843. // buffers
  21844. const indices = [];
  21845. const vertices = [];
  21846. const normals = [];
  21847. const uvs = [];
  21848. // helper variables
  21849. const vertex = new Vector3();
  21850. const normal = new Vector3();
  21851. const P1 = new Vector3();
  21852. const P2 = new Vector3();
  21853. const B = new Vector3();
  21854. const T = new Vector3();
  21855. const N = new Vector3();
  21856. // generate vertices, normals and uvs
  21857. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21858. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21859. const u = i / tubularSegments * p * Math.PI * 2;
  21860. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21861. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21862. calculatePositionOnCurve( u, p, q, radius, P1 );
  21863. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21864. // calculate orthonormal basis
  21865. T.subVectors( P2, P1 );
  21866. N.addVectors( P2, P1 );
  21867. B.crossVectors( T, N );
  21868. N.crossVectors( B, T );
  21869. // normalize B, N. T can be ignored, we don't use it
  21870. B.normalize();
  21871. N.normalize();
  21872. for ( let j = 0; j <= radialSegments; ++ j ) {
  21873. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21874. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21875. const v = j / radialSegments * Math.PI * 2;
  21876. const cx = - tube * Math.cos( v );
  21877. const cy = tube * Math.sin( v );
  21878. // now calculate the final vertex position.
  21879. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21880. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21881. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21882. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21883. vertices.push( vertex.x, vertex.y, vertex.z );
  21884. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21885. normal.subVectors( vertex, P1 ).normalize();
  21886. normals.push( normal.x, normal.y, normal.z );
  21887. // uv
  21888. uvs.push( i / tubularSegments );
  21889. uvs.push( j / radialSegments );
  21890. }
  21891. }
  21892. // generate indices
  21893. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21894. for ( let i = 1; i <= radialSegments; i ++ ) {
  21895. // indices
  21896. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21897. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21898. const c = ( radialSegments + 1 ) * j + i;
  21899. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21900. // faces
  21901. indices.push( a, b, d );
  21902. indices.push( b, c, d );
  21903. }
  21904. }
  21905. // build geometry
  21906. this.setIndex( indices );
  21907. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21908. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21909. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21910. // this function calculates the current position on the torus curve
  21911. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21912. const cu = Math.cos( u );
  21913. const su = Math.sin( u );
  21914. const quOverP = q / p * u;
  21915. const cs = Math.cos( quOverP );
  21916. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21917. position.y = radius * ( 2 + cs ) * su * 0.5;
  21918. position.z = radius * Math.sin( quOverP ) * 0.5;
  21919. }
  21920. }
  21921. static fromJSON( data ) {
  21922. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21923. }
  21924. }
  21925. class TubeGeometry extends BufferGeometry {
  21926. 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 ) {
  21927. super();
  21928. this.type = 'TubeGeometry';
  21929. this.parameters = {
  21930. path: path,
  21931. tubularSegments: tubularSegments,
  21932. radius: radius,
  21933. radialSegments: radialSegments,
  21934. closed: closed
  21935. };
  21936. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21937. // expose internals
  21938. this.tangents = frames.tangents;
  21939. this.normals = frames.normals;
  21940. this.binormals = frames.binormals;
  21941. // helper variables
  21942. const vertex = new Vector3();
  21943. const normal = new Vector3();
  21944. const uv = new Vector2();
  21945. let P = new Vector3();
  21946. // buffer
  21947. const vertices = [];
  21948. const normals = [];
  21949. const uvs = [];
  21950. const indices = [];
  21951. // create buffer data
  21952. generateBufferData();
  21953. // build geometry
  21954. this.setIndex( indices );
  21955. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21956. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21957. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21958. // functions
  21959. function generateBufferData() {
  21960. for ( let i = 0; i < tubularSegments; i ++ ) {
  21961. generateSegment( i );
  21962. }
  21963. // if the geometry is not closed, generate the last row of vertices and normals
  21964. // at the regular position on the given path
  21965. //
  21966. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21967. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21968. // uvs are generated in a separate function.
  21969. // this makes it easy compute correct values for closed geometries
  21970. generateUVs();
  21971. // finally create faces
  21972. generateIndices();
  21973. }
  21974. function generateSegment( i ) {
  21975. // we use getPointAt to sample evenly distributed points from the given path
  21976. P = path.getPointAt( i / tubularSegments, P );
  21977. // retrieve corresponding normal and binormal
  21978. const N = frames.normals[ i ];
  21979. const B = frames.binormals[ i ];
  21980. // generate normals and vertices for the current segment
  21981. for ( let j = 0; j <= radialSegments; j ++ ) {
  21982. const v = j / radialSegments * Math.PI * 2;
  21983. const sin = Math.sin( v );
  21984. const cos = - Math.cos( v );
  21985. // normal
  21986. normal.x = ( cos * N.x + sin * B.x );
  21987. normal.y = ( cos * N.y + sin * B.y );
  21988. normal.z = ( cos * N.z + sin * B.z );
  21989. normal.normalize();
  21990. normals.push( normal.x, normal.y, normal.z );
  21991. // vertex
  21992. vertex.x = P.x + radius * normal.x;
  21993. vertex.y = P.y + radius * normal.y;
  21994. vertex.z = P.z + radius * normal.z;
  21995. vertices.push( vertex.x, vertex.y, vertex.z );
  21996. }
  21997. }
  21998. function generateIndices() {
  21999. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22000. for ( let i = 1; i <= radialSegments; i ++ ) {
  22001. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22002. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22003. const c = ( radialSegments + 1 ) * j + i;
  22004. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22005. // faces
  22006. indices.push( a, b, d );
  22007. indices.push( b, c, d );
  22008. }
  22009. }
  22010. }
  22011. function generateUVs() {
  22012. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22013. for ( let j = 0; j <= radialSegments; j ++ ) {
  22014. uv.x = i / tubularSegments;
  22015. uv.y = j / radialSegments;
  22016. uvs.push( uv.x, uv.y );
  22017. }
  22018. }
  22019. }
  22020. }
  22021. toJSON() {
  22022. const data = super.toJSON();
  22023. data.path = this.parameters.path.toJSON();
  22024. return data;
  22025. }
  22026. static fromJSON( data ) {
  22027. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22028. // User defined curves or instances of CurvePath will not be deserialized.
  22029. return new TubeGeometry(
  22030. new Curves[ data.path.type ]().fromJSON( data.path ),
  22031. data.tubularSegments,
  22032. data.radius,
  22033. data.radialSegments,
  22034. data.closed
  22035. );
  22036. }
  22037. }
  22038. class WireframeGeometry extends BufferGeometry {
  22039. constructor( geometry = null ) {
  22040. super();
  22041. this.type = 'WireframeGeometry';
  22042. this.parameters = {
  22043. geometry: geometry
  22044. };
  22045. if ( geometry !== null ) {
  22046. // buffer
  22047. const vertices = [];
  22048. const edges = new Set();
  22049. // helper variables
  22050. const start = new Vector3();
  22051. const end = new Vector3();
  22052. if ( geometry.index !== null ) {
  22053. // indexed BufferGeometry
  22054. const position = geometry.attributes.position;
  22055. const indices = geometry.index;
  22056. let groups = geometry.groups;
  22057. if ( groups.length === 0 ) {
  22058. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22059. }
  22060. // create a data structure that contains all edges without duplicates
  22061. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22062. const group = groups[ o ];
  22063. const groupStart = group.start;
  22064. const groupCount = group.count;
  22065. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22066. for ( let j = 0; j < 3; j ++ ) {
  22067. const index1 = indices.getX( i + j );
  22068. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22069. start.fromBufferAttribute( position, index1 );
  22070. end.fromBufferAttribute( position, index2 );
  22071. if ( isUniqueEdge( start, end, edges ) === true ) {
  22072. vertices.push( start.x, start.y, start.z );
  22073. vertices.push( end.x, end.y, end.z );
  22074. }
  22075. }
  22076. }
  22077. }
  22078. } else {
  22079. // non-indexed BufferGeometry
  22080. const position = geometry.attributes.position;
  22081. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22082. for ( let j = 0; j < 3; j ++ ) {
  22083. // three edges per triangle, an edge is represented as (index1, index2)
  22084. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22085. const index1 = 3 * i + j;
  22086. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22087. start.fromBufferAttribute( position, index1 );
  22088. end.fromBufferAttribute( position, index2 );
  22089. if ( isUniqueEdge( start, end, edges ) === true ) {
  22090. vertices.push( start.x, start.y, start.z );
  22091. vertices.push( end.x, end.y, end.z );
  22092. }
  22093. }
  22094. }
  22095. }
  22096. // build geometry
  22097. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22098. }
  22099. }
  22100. }
  22101. function isUniqueEdge( start, end, edges ) {
  22102. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22103. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22104. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22105. return false;
  22106. } else {
  22107. edges.add( hash1 );
  22108. edges.add( hash2 );
  22109. return true;
  22110. }
  22111. }
  22112. var Geometries = /*#__PURE__*/Object.freeze({
  22113. __proto__: null,
  22114. BoxGeometry: BoxGeometry,
  22115. CapsuleGeometry: CapsuleGeometry,
  22116. CircleGeometry: CircleGeometry,
  22117. ConeGeometry: ConeGeometry,
  22118. CylinderGeometry: CylinderGeometry,
  22119. DodecahedronGeometry: DodecahedronGeometry,
  22120. EdgesGeometry: EdgesGeometry,
  22121. ExtrudeGeometry: ExtrudeGeometry,
  22122. IcosahedronGeometry: IcosahedronGeometry,
  22123. LatheGeometry: LatheGeometry,
  22124. OctahedronGeometry: OctahedronGeometry,
  22125. PlaneGeometry: PlaneGeometry,
  22126. PolyhedronGeometry: PolyhedronGeometry,
  22127. RingGeometry: RingGeometry,
  22128. ShapeGeometry: ShapeGeometry,
  22129. SphereGeometry: SphereGeometry,
  22130. TetrahedronGeometry: TetrahedronGeometry,
  22131. TorusGeometry: TorusGeometry,
  22132. TorusKnotGeometry: TorusKnotGeometry,
  22133. TubeGeometry: TubeGeometry,
  22134. WireframeGeometry: WireframeGeometry
  22135. });
  22136. class ShadowMaterial extends Material {
  22137. constructor( parameters ) {
  22138. super();
  22139. this.isShadowMaterial = true;
  22140. this.type = 'ShadowMaterial';
  22141. this.color = new Color( 0x000000 );
  22142. this.transparent = true;
  22143. this.fog = true;
  22144. this.setValues( parameters );
  22145. }
  22146. copy( source ) {
  22147. super.copy( source );
  22148. this.color.copy( source.color );
  22149. this.fog = source.fog;
  22150. return this;
  22151. }
  22152. }
  22153. class RawShaderMaterial extends ShaderMaterial {
  22154. constructor( parameters ) {
  22155. super( parameters );
  22156. this.isRawShaderMaterial = true;
  22157. this.type = 'RawShaderMaterial';
  22158. }
  22159. }
  22160. class MeshStandardMaterial extends Material {
  22161. constructor( parameters ) {
  22162. super();
  22163. this.isMeshStandardMaterial = true;
  22164. this.defines = { 'STANDARD': '' };
  22165. this.type = 'MeshStandardMaterial';
  22166. this.color = new Color( 0xffffff ); // diffuse
  22167. this.roughness = 1.0;
  22168. this.metalness = 0.0;
  22169. this.map = null;
  22170. this.lightMap = null;
  22171. this.lightMapIntensity = 1.0;
  22172. this.aoMap = null;
  22173. this.aoMapIntensity = 1.0;
  22174. this.emissive = new Color( 0x000000 );
  22175. this.emissiveIntensity = 1.0;
  22176. this.emissiveMap = null;
  22177. this.bumpMap = null;
  22178. this.bumpScale = 1;
  22179. this.normalMap = null;
  22180. this.normalMapType = TangentSpaceNormalMap;
  22181. this.normalScale = new Vector2( 1, 1 );
  22182. this.displacementMap = null;
  22183. this.displacementScale = 1;
  22184. this.displacementBias = 0;
  22185. this.roughnessMap = null;
  22186. this.metalnessMap = null;
  22187. this.alphaMap = null;
  22188. this.envMap = null;
  22189. this.envMapIntensity = 1.0;
  22190. this.wireframe = false;
  22191. this.wireframeLinewidth = 1;
  22192. this.wireframeLinecap = 'round';
  22193. this.wireframeLinejoin = 'round';
  22194. this.flatShading = false;
  22195. this.fog = true;
  22196. this.setValues( parameters );
  22197. }
  22198. copy( source ) {
  22199. super.copy( source );
  22200. this.defines = { 'STANDARD': '' };
  22201. this.color.copy( source.color );
  22202. this.roughness = source.roughness;
  22203. this.metalness = source.metalness;
  22204. this.map = source.map;
  22205. this.lightMap = source.lightMap;
  22206. this.lightMapIntensity = source.lightMapIntensity;
  22207. this.aoMap = source.aoMap;
  22208. this.aoMapIntensity = source.aoMapIntensity;
  22209. this.emissive.copy( source.emissive );
  22210. this.emissiveMap = source.emissiveMap;
  22211. this.emissiveIntensity = source.emissiveIntensity;
  22212. this.bumpMap = source.bumpMap;
  22213. this.bumpScale = source.bumpScale;
  22214. this.normalMap = source.normalMap;
  22215. this.normalMapType = source.normalMapType;
  22216. this.normalScale.copy( source.normalScale );
  22217. this.displacementMap = source.displacementMap;
  22218. this.displacementScale = source.displacementScale;
  22219. this.displacementBias = source.displacementBias;
  22220. this.roughnessMap = source.roughnessMap;
  22221. this.metalnessMap = source.metalnessMap;
  22222. this.alphaMap = source.alphaMap;
  22223. this.envMap = source.envMap;
  22224. this.envMapIntensity = source.envMapIntensity;
  22225. this.wireframe = source.wireframe;
  22226. this.wireframeLinewidth = source.wireframeLinewidth;
  22227. this.wireframeLinecap = source.wireframeLinecap;
  22228. this.wireframeLinejoin = source.wireframeLinejoin;
  22229. this.flatShading = source.flatShading;
  22230. this.fog = source.fog;
  22231. return this;
  22232. }
  22233. }
  22234. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22235. constructor( parameters ) {
  22236. super();
  22237. this.isMeshPhysicalMaterial = true;
  22238. this.defines = {
  22239. 'STANDARD': '',
  22240. 'PHYSICAL': ''
  22241. };
  22242. this.type = 'MeshPhysicalMaterial';
  22243. this.clearcoatMap = null;
  22244. this.clearcoatRoughness = 0.0;
  22245. this.clearcoatRoughnessMap = null;
  22246. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22247. this.clearcoatNormalMap = null;
  22248. this.ior = 1.5;
  22249. Object.defineProperty( this, 'reflectivity', {
  22250. get: function () {
  22251. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22252. },
  22253. set: function ( reflectivity ) {
  22254. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22255. }
  22256. } );
  22257. this.iridescenceMap = null;
  22258. this.iridescenceIOR = 1.3;
  22259. this.iridescenceThicknessRange = [ 100, 400 ];
  22260. this.iridescenceThicknessMap = null;
  22261. this.sheenColor = new Color( 0x000000 );
  22262. this.sheenColorMap = null;
  22263. this.sheenRoughness = 1.0;
  22264. this.sheenRoughnessMap = null;
  22265. this.transmissionMap = null;
  22266. this.thickness = 0;
  22267. this.thicknessMap = null;
  22268. this.attenuationDistance = Infinity;
  22269. this.attenuationColor = new Color( 1, 1, 1 );
  22270. this.specularIntensity = 1.0;
  22271. this.specularIntensityMap = null;
  22272. this.specularColor = new Color( 1, 1, 1 );
  22273. this.specularColorMap = null;
  22274. this._sheen = 0.0;
  22275. this._clearcoat = 0;
  22276. this._iridescence = 0;
  22277. this._transmission = 0;
  22278. this.setValues( parameters );
  22279. }
  22280. get sheen() {
  22281. return this._sheen;
  22282. }
  22283. set sheen( value ) {
  22284. if ( this._sheen > 0 !== value > 0 ) {
  22285. this.version ++;
  22286. }
  22287. this._sheen = value;
  22288. }
  22289. get clearcoat() {
  22290. return this._clearcoat;
  22291. }
  22292. set clearcoat( value ) {
  22293. if ( this._clearcoat > 0 !== value > 0 ) {
  22294. this.version ++;
  22295. }
  22296. this._clearcoat = value;
  22297. }
  22298. get iridescence() {
  22299. return this._iridescence;
  22300. }
  22301. set iridescence( value ) {
  22302. if ( this._iridescence > 0 !== value > 0 ) {
  22303. this.version ++;
  22304. }
  22305. this._iridescence = value;
  22306. }
  22307. get transmission() {
  22308. return this._transmission;
  22309. }
  22310. set transmission( value ) {
  22311. if ( this._transmission > 0 !== value > 0 ) {
  22312. this.version ++;
  22313. }
  22314. this._transmission = value;
  22315. }
  22316. copy( source ) {
  22317. super.copy( source );
  22318. this.defines = {
  22319. 'STANDARD': '',
  22320. 'PHYSICAL': ''
  22321. };
  22322. this.clearcoat = source.clearcoat;
  22323. this.clearcoatMap = source.clearcoatMap;
  22324. this.clearcoatRoughness = source.clearcoatRoughness;
  22325. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22326. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22327. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22328. this.ior = source.ior;
  22329. this.iridescence = source.iridescence;
  22330. this.iridescenceMap = source.iridescenceMap;
  22331. this.iridescenceIOR = source.iridescenceIOR;
  22332. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22333. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22334. this.sheen = source.sheen;
  22335. this.sheenColor.copy( source.sheenColor );
  22336. this.sheenColorMap = source.sheenColorMap;
  22337. this.sheenRoughness = source.sheenRoughness;
  22338. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22339. this.transmission = source.transmission;
  22340. this.transmissionMap = source.transmissionMap;
  22341. this.thickness = source.thickness;
  22342. this.thicknessMap = source.thicknessMap;
  22343. this.attenuationDistance = source.attenuationDistance;
  22344. this.attenuationColor.copy( source.attenuationColor );
  22345. this.specularIntensity = source.specularIntensity;
  22346. this.specularIntensityMap = source.specularIntensityMap;
  22347. this.specularColor.copy( source.specularColor );
  22348. this.specularColorMap = source.specularColorMap;
  22349. return this;
  22350. }
  22351. }
  22352. class MeshPhongMaterial extends Material {
  22353. constructor( parameters ) {
  22354. super();
  22355. this.isMeshPhongMaterial = true;
  22356. this.type = 'MeshPhongMaterial';
  22357. this.color = new Color( 0xffffff ); // diffuse
  22358. this.specular = new Color( 0x111111 );
  22359. this.shininess = 30;
  22360. this.map = null;
  22361. this.lightMap = null;
  22362. this.lightMapIntensity = 1.0;
  22363. this.aoMap = null;
  22364. this.aoMapIntensity = 1.0;
  22365. this.emissive = new Color( 0x000000 );
  22366. this.emissiveIntensity = 1.0;
  22367. this.emissiveMap = null;
  22368. this.bumpMap = null;
  22369. this.bumpScale = 1;
  22370. this.normalMap = null;
  22371. this.normalMapType = TangentSpaceNormalMap;
  22372. this.normalScale = new Vector2( 1, 1 );
  22373. this.displacementMap = null;
  22374. this.displacementScale = 1;
  22375. this.displacementBias = 0;
  22376. this.specularMap = null;
  22377. this.alphaMap = null;
  22378. this.envMap = null;
  22379. this.combine = MultiplyOperation;
  22380. this.reflectivity = 1;
  22381. this.refractionRatio = 0.98;
  22382. this.wireframe = false;
  22383. this.wireframeLinewidth = 1;
  22384. this.wireframeLinecap = 'round';
  22385. this.wireframeLinejoin = 'round';
  22386. this.flatShading = false;
  22387. this.fog = true;
  22388. this.setValues( parameters );
  22389. }
  22390. copy( source ) {
  22391. super.copy( source );
  22392. this.color.copy( source.color );
  22393. this.specular.copy( source.specular );
  22394. this.shininess = source.shininess;
  22395. this.map = source.map;
  22396. this.lightMap = source.lightMap;
  22397. this.lightMapIntensity = source.lightMapIntensity;
  22398. this.aoMap = source.aoMap;
  22399. this.aoMapIntensity = source.aoMapIntensity;
  22400. this.emissive.copy( source.emissive );
  22401. this.emissiveMap = source.emissiveMap;
  22402. this.emissiveIntensity = source.emissiveIntensity;
  22403. this.bumpMap = source.bumpMap;
  22404. this.bumpScale = source.bumpScale;
  22405. this.normalMap = source.normalMap;
  22406. this.normalMapType = source.normalMapType;
  22407. this.normalScale.copy( source.normalScale );
  22408. this.displacementMap = source.displacementMap;
  22409. this.displacementScale = source.displacementScale;
  22410. this.displacementBias = source.displacementBias;
  22411. this.specularMap = source.specularMap;
  22412. this.alphaMap = source.alphaMap;
  22413. this.envMap = source.envMap;
  22414. this.combine = source.combine;
  22415. this.reflectivity = source.reflectivity;
  22416. this.refractionRatio = source.refractionRatio;
  22417. this.wireframe = source.wireframe;
  22418. this.wireframeLinewidth = source.wireframeLinewidth;
  22419. this.wireframeLinecap = source.wireframeLinecap;
  22420. this.wireframeLinejoin = source.wireframeLinejoin;
  22421. this.flatShading = source.flatShading;
  22422. this.fog = source.fog;
  22423. return this;
  22424. }
  22425. }
  22426. class MeshToonMaterial extends Material {
  22427. constructor( parameters ) {
  22428. super();
  22429. this.isMeshToonMaterial = true;
  22430. this.defines = { 'TOON': '' };
  22431. this.type = 'MeshToonMaterial';
  22432. this.color = new Color( 0xffffff );
  22433. this.map = null;
  22434. this.gradientMap = null;
  22435. this.lightMap = null;
  22436. this.lightMapIntensity = 1.0;
  22437. this.aoMap = null;
  22438. this.aoMapIntensity = 1.0;
  22439. this.emissive = new Color( 0x000000 );
  22440. this.emissiveIntensity = 1.0;
  22441. this.emissiveMap = null;
  22442. this.bumpMap = null;
  22443. this.bumpScale = 1;
  22444. this.normalMap = null;
  22445. this.normalMapType = TangentSpaceNormalMap;
  22446. this.normalScale = new Vector2( 1, 1 );
  22447. this.displacementMap = null;
  22448. this.displacementScale = 1;
  22449. this.displacementBias = 0;
  22450. this.alphaMap = null;
  22451. this.wireframe = false;
  22452. this.wireframeLinewidth = 1;
  22453. this.wireframeLinecap = 'round';
  22454. this.wireframeLinejoin = 'round';
  22455. this.fog = true;
  22456. this.setValues( parameters );
  22457. }
  22458. copy( source ) {
  22459. super.copy( source );
  22460. this.color.copy( source.color );
  22461. this.map = source.map;
  22462. this.gradientMap = source.gradientMap;
  22463. this.lightMap = source.lightMap;
  22464. this.lightMapIntensity = source.lightMapIntensity;
  22465. this.aoMap = source.aoMap;
  22466. this.aoMapIntensity = source.aoMapIntensity;
  22467. this.emissive.copy( source.emissive );
  22468. this.emissiveMap = source.emissiveMap;
  22469. this.emissiveIntensity = source.emissiveIntensity;
  22470. this.bumpMap = source.bumpMap;
  22471. this.bumpScale = source.bumpScale;
  22472. this.normalMap = source.normalMap;
  22473. this.normalMapType = source.normalMapType;
  22474. this.normalScale.copy( source.normalScale );
  22475. this.displacementMap = source.displacementMap;
  22476. this.displacementScale = source.displacementScale;
  22477. this.displacementBias = source.displacementBias;
  22478. this.alphaMap = source.alphaMap;
  22479. this.wireframe = source.wireframe;
  22480. this.wireframeLinewidth = source.wireframeLinewidth;
  22481. this.wireframeLinecap = source.wireframeLinecap;
  22482. this.wireframeLinejoin = source.wireframeLinejoin;
  22483. this.fog = source.fog;
  22484. return this;
  22485. }
  22486. }
  22487. class MeshNormalMaterial extends Material {
  22488. constructor( parameters ) {
  22489. super();
  22490. this.isMeshNormalMaterial = true;
  22491. this.type = 'MeshNormalMaterial';
  22492. this.bumpMap = null;
  22493. this.bumpScale = 1;
  22494. this.normalMap = null;
  22495. this.normalMapType = TangentSpaceNormalMap;
  22496. this.normalScale = new Vector2( 1, 1 );
  22497. this.displacementMap = null;
  22498. this.displacementScale = 1;
  22499. this.displacementBias = 0;
  22500. this.wireframe = false;
  22501. this.wireframeLinewidth = 1;
  22502. this.flatShading = false;
  22503. this.setValues( parameters );
  22504. }
  22505. copy( source ) {
  22506. super.copy( source );
  22507. this.bumpMap = source.bumpMap;
  22508. this.bumpScale = source.bumpScale;
  22509. this.normalMap = source.normalMap;
  22510. this.normalMapType = source.normalMapType;
  22511. this.normalScale.copy( source.normalScale );
  22512. this.displacementMap = source.displacementMap;
  22513. this.displacementScale = source.displacementScale;
  22514. this.displacementBias = source.displacementBias;
  22515. this.wireframe = source.wireframe;
  22516. this.wireframeLinewidth = source.wireframeLinewidth;
  22517. this.flatShading = source.flatShading;
  22518. return this;
  22519. }
  22520. }
  22521. class MeshLambertMaterial extends Material {
  22522. constructor( parameters ) {
  22523. super();
  22524. this.isMeshLambertMaterial = true;
  22525. this.type = 'MeshLambertMaterial';
  22526. this.color = new Color( 0xffffff ); // diffuse
  22527. this.map = null;
  22528. this.lightMap = null;
  22529. this.lightMapIntensity = 1.0;
  22530. this.aoMap = null;
  22531. this.aoMapIntensity = 1.0;
  22532. this.emissive = new Color( 0x000000 );
  22533. this.emissiveIntensity = 1.0;
  22534. this.emissiveMap = null;
  22535. this.bumpMap = null;
  22536. this.bumpScale = 1;
  22537. this.normalMap = null;
  22538. this.normalMapType = TangentSpaceNormalMap;
  22539. this.normalScale = new Vector2( 1, 1 );
  22540. this.displacementMap = null;
  22541. this.displacementScale = 1;
  22542. this.displacementBias = 0;
  22543. this.specularMap = null;
  22544. this.alphaMap = null;
  22545. this.envMap = null;
  22546. this.combine = MultiplyOperation;
  22547. this.reflectivity = 1;
  22548. this.refractionRatio = 0.98;
  22549. this.wireframe = false;
  22550. this.wireframeLinewidth = 1;
  22551. this.wireframeLinecap = 'round';
  22552. this.wireframeLinejoin = 'round';
  22553. this.flatShading = false;
  22554. this.fog = true;
  22555. this.setValues( parameters );
  22556. }
  22557. copy( source ) {
  22558. super.copy( source );
  22559. this.color.copy( source.color );
  22560. this.map = source.map;
  22561. this.lightMap = source.lightMap;
  22562. this.lightMapIntensity = source.lightMapIntensity;
  22563. this.aoMap = source.aoMap;
  22564. this.aoMapIntensity = source.aoMapIntensity;
  22565. this.emissive.copy( source.emissive );
  22566. this.emissiveMap = source.emissiveMap;
  22567. this.emissiveIntensity = source.emissiveIntensity;
  22568. this.bumpMap = source.bumpMap;
  22569. this.bumpScale = source.bumpScale;
  22570. this.normalMap = source.normalMap;
  22571. this.normalMapType = source.normalMapType;
  22572. this.normalScale.copy( source.normalScale );
  22573. this.displacementMap = source.displacementMap;
  22574. this.displacementScale = source.displacementScale;
  22575. this.displacementBias = source.displacementBias;
  22576. this.specularMap = source.specularMap;
  22577. this.alphaMap = source.alphaMap;
  22578. this.envMap = source.envMap;
  22579. this.combine = source.combine;
  22580. this.reflectivity = source.reflectivity;
  22581. this.refractionRatio = source.refractionRatio;
  22582. this.wireframe = source.wireframe;
  22583. this.wireframeLinewidth = source.wireframeLinewidth;
  22584. this.wireframeLinecap = source.wireframeLinecap;
  22585. this.wireframeLinejoin = source.wireframeLinejoin;
  22586. this.flatShading = source.flatShading;
  22587. this.fog = source.fog;
  22588. return this;
  22589. }
  22590. }
  22591. class MeshMatcapMaterial extends Material {
  22592. constructor( parameters ) {
  22593. super();
  22594. this.isMeshMatcapMaterial = true;
  22595. this.defines = { 'MATCAP': '' };
  22596. this.type = 'MeshMatcapMaterial';
  22597. this.color = new Color( 0xffffff ); // diffuse
  22598. this.matcap = null;
  22599. this.map = null;
  22600. this.bumpMap = null;
  22601. this.bumpScale = 1;
  22602. this.normalMap = null;
  22603. this.normalMapType = TangentSpaceNormalMap;
  22604. this.normalScale = new Vector2( 1, 1 );
  22605. this.displacementMap = null;
  22606. this.displacementScale = 1;
  22607. this.displacementBias = 0;
  22608. this.alphaMap = null;
  22609. this.flatShading = false;
  22610. this.fog = true;
  22611. this.setValues( parameters );
  22612. }
  22613. copy( source ) {
  22614. super.copy( source );
  22615. this.defines = { 'MATCAP': '' };
  22616. this.color.copy( source.color );
  22617. this.matcap = source.matcap;
  22618. this.map = source.map;
  22619. this.bumpMap = source.bumpMap;
  22620. this.bumpScale = source.bumpScale;
  22621. this.normalMap = source.normalMap;
  22622. this.normalMapType = source.normalMapType;
  22623. this.normalScale.copy( source.normalScale );
  22624. this.displacementMap = source.displacementMap;
  22625. this.displacementScale = source.displacementScale;
  22626. this.displacementBias = source.displacementBias;
  22627. this.alphaMap = source.alphaMap;
  22628. this.flatShading = source.flatShading;
  22629. this.fog = source.fog;
  22630. return this;
  22631. }
  22632. }
  22633. class LineDashedMaterial extends LineBasicMaterial {
  22634. constructor( parameters ) {
  22635. super();
  22636. this.isLineDashedMaterial = true;
  22637. this.type = 'LineDashedMaterial';
  22638. this.scale = 1;
  22639. this.dashSize = 3;
  22640. this.gapSize = 1;
  22641. this.setValues( parameters );
  22642. }
  22643. copy( source ) {
  22644. super.copy( source );
  22645. this.scale = source.scale;
  22646. this.dashSize = source.dashSize;
  22647. this.gapSize = source.gapSize;
  22648. return this;
  22649. }
  22650. }
  22651. // same as Array.prototype.slice, but also works on typed arrays
  22652. function arraySlice( array, from, to ) {
  22653. if ( isTypedArray( array ) ) {
  22654. // in ios9 array.subarray(from, undefined) will return empty array
  22655. // but array.subarray(from) or array.subarray(from, len) is correct
  22656. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22657. }
  22658. return array.slice( from, to );
  22659. }
  22660. // converts an array to a specific type
  22661. function convertArray( array, type, forceClone ) {
  22662. if ( ! array || // let 'undefined' and 'null' pass
  22663. ! forceClone && array.constructor === type ) return array;
  22664. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22665. return new type( array ); // create typed array
  22666. }
  22667. return Array.prototype.slice.call( array ); // create Array
  22668. }
  22669. function isTypedArray( object ) {
  22670. return ArrayBuffer.isView( object ) &&
  22671. ! ( object instanceof DataView );
  22672. }
  22673. // returns an array by which times and values can be sorted
  22674. function getKeyframeOrder( times ) {
  22675. function compareTime( i, j ) {
  22676. return times[ i ] - times[ j ];
  22677. }
  22678. const n = times.length;
  22679. const result = new Array( n );
  22680. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22681. result.sort( compareTime );
  22682. return result;
  22683. }
  22684. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22685. function sortedArray( values, stride, order ) {
  22686. const nValues = values.length;
  22687. const result = new values.constructor( nValues );
  22688. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22689. const srcOffset = order[ i ] * stride;
  22690. for ( let j = 0; j !== stride; ++ j ) {
  22691. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22692. }
  22693. }
  22694. return result;
  22695. }
  22696. // function for parsing AOS keyframe formats
  22697. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22698. let i = 1, key = jsonKeys[ 0 ];
  22699. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22700. key = jsonKeys[ i ++ ];
  22701. }
  22702. if ( key === undefined ) return; // no data
  22703. let value = key[ valuePropertyName ];
  22704. if ( value === undefined ) return; // no data
  22705. if ( Array.isArray( value ) ) {
  22706. do {
  22707. value = key[ valuePropertyName ];
  22708. if ( value !== undefined ) {
  22709. times.push( key.time );
  22710. values.push.apply( values, value ); // push all elements
  22711. }
  22712. key = jsonKeys[ i ++ ];
  22713. } while ( key !== undefined );
  22714. } else if ( value.toArray !== undefined ) {
  22715. // ...assume THREE.Math-ish
  22716. do {
  22717. value = key[ valuePropertyName ];
  22718. if ( value !== undefined ) {
  22719. times.push( key.time );
  22720. value.toArray( values, values.length );
  22721. }
  22722. key = jsonKeys[ i ++ ];
  22723. } while ( key !== undefined );
  22724. } else {
  22725. // otherwise push as-is
  22726. do {
  22727. value = key[ valuePropertyName ];
  22728. if ( value !== undefined ) {
  22729. times.push( key.time );
  22730. values.push( value );
  22731. }
  22732. key = jsonKeys[ i ++ ];
  22733. } while ( key !== undefined );
  22734. }
  22735. }
  22736. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22737. const clip = sourceClip.clone();
  22738. clip.name = name;
  22739. const tracks = [];
  22740. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22741. const track = clip.tracks[ i ];
  22742. const valueSize = track.getValueSize();
  22743. const times = [];
  22744. const values = [];
  22745. for ( let j = 0; j < track.times.length; ++ j ) {
  22746. const frame = track.times[ j ] * fps;
  22747. if ( frame < startFrame || frame >= endFrame ) continue;
  22748. times.push( track.times[ j ] );
  22749. for ( let k = 0; k < valueSize; ++ k ) {
  22750. values.push( track.values[ j * valueSize + k ] );
  22751. }
  22752. }
  22753. if ( times.length === 0 ) continue;
  22754. track.times = convertArray( times, track.times.constructor );
  22755. track.values = convertArray( values, track.values.constructor );
  22756. tracks.push( track );
  22757. }
  22758. clip.tracks = tracks;
  22759. // find minimum .times value across all tracks in the trimmed clip
  22760. let minStartTime = Infinity;
  22761. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22762. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22763. minStartTime = clip.tracks[ i ].times[ 0 ];
  22764. }
  22765. }
  22766. // shift all tracks such that clip begins at t=0
  22767. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22768. clip.tracks[ i ].shift( - 1 * minStartTime );
  22769. }
  22770. clip.resetDuration();
  22771. return clip;
  22772. }
  22773. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22774. if ( fps <= 0 ) fps = 30;
  22775. const numTracks = referenceClip.tracks.length;
  22776. const referenceTime = referenceFrame / fps;
  22777. // Make each track's values relative to the values at the reference frame
  22778. for ( let i = 0; i < numTracks; ++ i ) {
  22779. const referenceTrack = referenceClip.tracks[ i ];
  22780. const referenceTrackType = referenceTrack.ValueTypeName;
  22781. // Skip this track if it's non-numeric
  22782. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22783. // Find the track in the target clip whose name and type matches the reference track
  22784. const targetTrack = targetClip.tracks.find( function ( track ) {
  22785. return track.name === referenceTrack.name
  22786. && track.ValueTypeName === referenceTrackType;
  22787. } );
  22788. if ( targetTrack === undefined ) continue;
  22789. let referenceOffset = 0;
  22790. const referenceValueSize = referenceTrack.getValueSize();
  22791. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22792. referenceOffset = referenceValueSize / 3;
  22793. }
  22794. let targetOffset = 0;
  22795. const targetValueSize = targetTrack.getValueSize();
  22796. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22797. targetOffset = targetValueSize / 3;
  22798. }
  22799. const lastIndex = referenceTrack.times.length - 1;
  22800. let referenceValue;
  22801. // Find the value to subtract out of the track
  22802. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22803. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22804. const startIndex = referenceOffset;
  22805. const endIndex = referenceValueSize - referenceOffset;
  22806. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22807. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22808. // Reference frame is after the last keyframe, so just use the last keyframe
  22809. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22810. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22811. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22812. } else {
  22813. // Interpolate to the reference value
  22814. const interpolant = referenceTrack.createInterpolant();
  22815. const startIndex = referenceOffset;
  22816. const endIndex = referenceValueSize - referenceOffset;
  22817. interpolant.evaluate( referenceTime );
  22818. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22819. }
  22820. // Conjugate the quaternion
  22821. if ( referenceTrackType === 'quaternion' ) {
  22822. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22823. referenceQuat.toArray( referenceValue );
  22824. }
  22825. // Subtract the reference value from all of the track values
  22826. const numTimes = targetTrack.times.length;
  22827. for ( let j = 0; j < numTimes; ++ j ) {
  22828. const valueStart = j * targetValueSize + targetOffset;
  22829. if ( referenceTrackType === 'quaternion' ) {
  22830. // Multiply the conjugate for quaternion track types
  22831. Quaternion.multiplyQuaternionsFlat(
  22832. targetTrack.values,
  22833. valueStart,
  22834. referenceValue,
  22835. 0,
  22836. targetTrack.values,
  22837. valueStart
  22838. );
  22839. } else {
  22840. const valueEnd = targetValueSize - targetOffset * 2;
  22841. // Subtract each value for all other numeric track types
  22842. for ( let k = 0; k < valueEnd; ++ k ) {
  22843. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22844. }
  22845. }
  22846. }
  22847. }
  22848. targetClip.blendMode = AdditiveAnimationBlendMode;
  22849. return targetClip;
  22850. }
  22851. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22852. __proto__: null,
  22853. arraySlice: arraySlice,
  22854. convertArray: convertArray,
  22855. flattenJSON: flattenJSON,
  22856. getKeyframeOrder: getKeyframeOrder,
  22857. isTypedArray: isTypedArray,
  22858. makeClipAdditive: makeClipAdditive,
  22859. sortedArray: sortedArray,
  22860. subclip: subclip
  22861. });
  22862. /**
  22863. * Abstract base class of interpolants over parametric samples.
  22864. *
  22865. * The parameter domain is one dimensional, typically the time or a path
  22866. * along a curve defined by the data.
  22867. *
  22868. * The sample values can have any dimensionality and derived classes may
  22869. * apply special interpretations to the data.
  22870. *
  22871. * This class provides the interval seek in a Template Method, deferring
  22872. * the actual interpolation to derived classes.
  22873. *
  22874. * Time complexity is O(1) for linear access crossing at most two points
  22875. * and O(log N) for random access, where N is the number of positions.
  22876. *
  22877. * References:
  22878. *
  22879. * http://www.oodesign.com/template-method-pattern.html
  22880. *
  22881. */
  22882. class Interpolant {
  22883. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22884. this.parameterPositions = parameterPositions;
  22885. this._cachedIndex = 0;
  22886. this.resultBuffer = resultBuffer !== undefined ?
  22887. resultBuffer : new sampleValues.constructor( sampleSize );
  22888. this.sampleValues = sampleValues;
  22889. this.valueSize = sampleSize;
  22890. this.settings = null;
  22891. this.DefaultSettings_ = {};
  22892. }
  22893. evaluate( t ) {
  22894. const pp = this.parameterPositions;
  22895. let i1 = this._cachedIndex,
  22896. t1 = pp[ i1 ],
  22897. t0 = pp[ i1 - 1 ];
  22898. validate_interval: {
  22899. seek: {
  22900. let right;
  22901. linear_scan: {
  22902. //- See http://jsperf.com/comparison-to-undefined/3
  22903. //- slower code:
  22904. //-
  22905. //- if ( t >= t1 || t1 === undefined ) {
  22906. forward_scan: if ( ! ( t < t1 ) ) {
  22907. for ( let giveUpAt = i1 + 2; ; ) {
  22908. if ( t1 === undefined ) {
  22909. if ( t < t0 ) break forward_scan;
  22910. // after end
  22911. i1 = pp.length;
  22912. this._cachedIndex = i1;
  22913. return this.copySampleValue_( i1 - 1 );
  22914. }
  22915. if ( i1 === giveUpAt ) break; // this loop
  22916. t0 = t1;
  22917. t1 = pp[ ++ i1 ];
  22918. if ( t < t1 ) {
  22919. // we have arrived at the sought interval
  22920. break seek;
  22921. }
  22922. }
  22923. // prepare binary search on the right side of the index
  22924. right = pp.length;
  22925. break linear_scan;
  22926. }
  22927. //- slower code:
  22928. //- if ( t < t0 || t0 === undefined ) {
  22929. if ( ! ( t >= t0 ) ) {
  22930. // looping?
  22931. const t1global = pp[ 1 ];
  22932. if ( t < t1global ) {
  22933. i1 = 2; // + 1, using the scan for the details
  22934. t0 = t1global;
  22935. }
  22936. // linear reverse scan
  22937. for ( let giveUpAt = i1 - 2; ; ) {
  22938. if ( t0 === undefined ) {
  22939. // before start
  22940. this._cachedIndex = 0;
  22941. return this.copySampleValue_( 0 );
  22942. }
  22943. if ( i1 === giveUpAt ) break; // this loop
  22944. t1 = t0;
  22945. t0 = pp[ -- i1 - 1 ];
  22946. if ( t >= t0 ) {
  22947. // we have arrived at the sought interval
  22948. break seek;
  22949. }
  22950. }
  22951. // prepare binary search on the left side of the index
  22952. right = i1;
  22953. i1 = 0;
  22954. break linear_scan;
  22955. }
  22956. // the interval is valid
  22957. break validate_interval;
  22958. } // linear scan
  22959. // binary search
  22960. while ( i1 < right ) {
  22961. const mid = ( i1 + right ) >>> 1;
  22962. if ( t < pp[ mid ] ) {
  22963. right = mid;
  22964. } else {
  22965. i1 = mid + 1;
  22966. }
  22967. }
  22968. t1 = pp[ i1 ];
  22969. t0 = pp[ i1 - 1 ];
  22970. // check boundary cases, again
  22971. if ( t0 === undefined ) {
  22972. this._cachedIndex = 0;
  22973. return this.copySampleValue_( 0 );
  22974. }
  22975. if ( t1 === undefined ) {
  22976. i1 = pp.length;
  22977. this._cachedIndex = i1;
  22978. return this.copySampleValue_( i1 - 1 );
  22979. }
  22980. } // seek
  22981. this._cachedIndex = i1;
  22982. this.intervalChanged_( i1, t0, t1 );
  22983. } // validate_interval
  22984. return this.interpolate_( i1, t0, t, t1 );
  22985. }
  22986. getSettings_() {
  22987. return this.settings || this.DefaultSettings_;
  22988. }
  22989. copySampleValue_( index ) {
  22990. // copies a sample value to the result buffer
  22991. const result = this.resultBuffer,
  22992. values = this.sampleValues,
  22993. stride = this.valueSize,
  22994. offset = index * stride;
  22995. for ( let i = 0; i !== stride; ++ i ) {
  22996. result[ i ] = values[ offset + i ];
  22997. }
  22998. return result;
  22999. }
  23000. // Template methods for derived classes:
  23001. interpolate_( /* i1, t0, t, t1 */ ) {
  23002. throw new Error( 'call to abstract method' );
  23003. // implementations shall return this.resultBuffer
  23004. }
  23005. intervalChanged_( /* i1, t0, t1 */ ) {
  23006. // empty
  23007. }
  23008. }
  23009. /**
  23010. * Fast and simple cubic spline interpolant.
  23011. *
  23012. * It was derived from a Hermitian construction setting the first derivative
  23013. * at each sample position to the linear slope between neighboring positions
  23014. * over their parameter interval.
  23015. */
  23016. class CubicInterpolant extends Interpolant {
  23017. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23018. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23019. this._weightPrev = - 0;
  23020. this._offsetPrev = - 0;
  23021. this._weightNext = - 0;
  23022. this._offsetNext = - 0;
  23023. this.DefaultSettings_ = {
  23024. endingStart: ZeroCurvatureEnding,
  23025. endingEnd: ZeroCurvatureEnding
  23026. };
  23027. }
  23028. intervalChanged_( i1, t0, t1 ) {
  23029. const pp = this.parameterPositions;
  23030. let iPrev = i1 - 2,
  23031. iNext = i1 + 1,
  23032. tPrev = pp[ iPrev ],
  23033. tNext = pp[ iNext ];
  23034. if ( tPrev === undefined ) {
  23035. switch ( this.getSettings_().endingStart ) {
  23036. case ZeroSlopeEnding:
  23037. // f'(t0) = 0
  23038. iPrev = i1;
  23039. tPrev = 2 * t0 - t1;
  23040. break;
  23041. case WrapAroundEnding:
  23042. // use the other end of the curve
  23043. iPrev = pp.length - 2;
  23044. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23045. break;
  23046. default: // ZeroCurvatureEnding
  23047. // f''(t0) = 0 a.k.a. Natural Spline
  23048. iPrev = i1;
  23049. tPrev = t1;
  23050. }
  23051. }
  23052. if ( tNext === undefined ) {
  23053. switch ( this.getSettings_().endingEnd ) {
  23054. case ZeroSlopeEnding:
  23055. // f'(tN) = 0
  23056. iNext = i1;
  23057. tNext = 2 * t1 - t0;
  23058. break;
  23059. case WrapAroundEnding:
  23060. // use the other end of the curve
  23061. iNext = 1;
  23062. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23063. break;
  23064. default: // ZeroCurvatureEnding
  23065. // f''(tN) = 0, a.k.a. Natural Spline
  23066. iNext = i1 - 1;
  23067. tNext = t0;
  23068. }
  23069. }
  23070. const halfDt = ( t1 - t0 ) * 0.5,
  23071. stride = this.valueSize;
  23072. this._weightPrev = halfDt / ( t0 - tPrev );
  23073. this._weightNext = halfDt / ( tNext - t1 );
  23074. this._offsetPrev = iPrev * stride;
  23075. this._offsetNext = iNext * stride;
  23076. }
  23077. interpolate_( i1, t0, t, t1 ) {
  23078. const result = this.resultBuffer,
  23079. values = this.sampleValues,
  23080. stride = this.valueSize,
  23081. o1 = i1 * stride, o0 = o1 - stride,
  23082. oP = this._offsetPrev, oN = this._offsetNext,
  23083. wP = this._weightPrev, wN = this._weightNext,
  23084. p = ( t - t0 ) / ( t1 - t0 ),
  23085. pp = p * p,
  23086. ppp = pp * p;
  23087. // evaluate polynomials
  23088. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23089. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23090. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23091. const sN = wN * ppp - wN * pp;
  23092. // combine data linearly
  23093. for ( let i = 0; i !== stride; ++ i ) {
  23094. result[ i ] =
  23095. sP * values[ oP + i ] +
  23096. s0 * values[ o0 + i ] +
  23097. s1 * values[ o1 + i ] +
  23098. sN * values[ oN + i ];
  23099. }
  23100. return result;
  23101. }
  23102. }
  23103. class LinearInterpolant extends Interpolant {
  23104. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23105. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23106. }
  23107. interpolate_( i1, t0, t, t1 ) {
  23108. const result = this.resultBuffer,
  23109. values = this.sampleValues,
  23110. stride = this.valueSize,
  23111. offset1 = i1 * stride,
  23112. offset0 = offset1 - stride,
  23113. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23114. weight0 = 1 - weight1;
  23115. for ( let i = 0; i !== stride; ++ i ) {
  23116. result[ i ] =
  23117. values[ offset0 + i ] * weight0 +
  23118. values[ offset1 + i ] * weight1;
  23119. }
  23120. return result;
  23121. }
  23122. }
  23123. /**
  23124. *
  23125. * Interpolant that evaluates to the sample value at the position preceding
  23126. * the parameter.
  23127. */
  23128. class DiscreteInterpolant extends Interpolant {
  23129. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23130. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23131. }
  23132. interpolate_( i1 /*, t0, t, t1 */ ) {
  23133. return this.copySampleValue_( i1 - 1 );
  23134. }
  23135. }
  23136. class KeyframeTrack {
  23137. constructor( name, times, values, interpolation ) {
  23138. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23139. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23140. this.name = name;
  23141. this.times = convertArray( times, this.TimeBufferType );
  23142. this.values = convertArray( values, this.ValueBufferType );
  23143. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23144. }
  23145. // Serialization (in static context, because of constructor invocation
  23146. // and automatic invocation of .toJSON):
  23147. static toJSON( track ) {
  23148. const trackType = track.constructor;
  23149. let json;
  23150. // derived classes can define a static toJSON method
  23151. if ( trackType.toJSON !== this.toJSON ) {
  23152. json = trackType.toJSON( track );
  23153. } else {
  23154. // by default, we assume the data can be serialized as-is
  23155. json = {
  23156. 'name': track.name,
  23157. 'times': convertArray( track.times, Array ),
  23158. 'values': convertArray( track.values, Array )
  23159. };
  23160. const interpolation = track.getInterpolation();
  23161. if ( interpolation !== track.DefaultInterpolation ) {
  23162. json.interpolation = interpolation;
  23163. }
  23164. }
  23165. json.type = track.ValueTypeName; // mandatory
  23166. return json;
  23167. }
  23168. InterpolantFactoryMethodDiscrete( result ) {
  23169. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23170. }
  23171. InterpolantFactoryMethodLinear( result ) {
  23172. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23173. }
  23174. InterpolantFactoryMethodSmooth( result ) {
  23175. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23176. }
  23177. setInterpolation( interpolation ) {
  23178. let factoryMethod;
  23179. switch ( interpolation ) {
  23180. case InterpolateDiscrete:
  23181. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23182. break;
  23183. case InterpolateLinear:
  23184. factoryMethod = this.InterpolantFactoryMethodLinear;
  23185. break;
  23186. case InterpolateSmooth:
  23187. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23188. break;
  23189. }
  23190. if ( factoryMethod === undefined ) {
  23191. const message = 'unsupported interpolation for ' +
  23192. this.ValueTypeName + ' keyframe track named ' + this.name;
  23193. if ( this.createInterpolant === undefined ) {
  23194. // fall back to default, unless the default itself is messed up
  23195. if ( interpolation !== this.DefaultInterpolation ) {
  23196. this.setInterpolation( this.DefaultInterpolation );
  23197. } else {
  23198. throw new Error( message ); // fatal, in this case
  23199. }
  23200. }
  23201. console.warn( 'THREE.KeyframeTrack:', message );
  23202. return this;
  23203. }
  23204. this.createInterpolant = factoryMethod;
  23205. return this;
  23206. }
  23207. getInterpolation() {
  23208. switch ( this.createInterpolant ) {
  23209. case this.InterpolantFactoryMethodDiscrete:
  23210. return InterpolateDiscrete;
  23211. case this.InterpolantFactoryMethodLinear:
  23212. return InterpolateLinear;
  23213. case this.InterpolantFactoryMethodSmooth:
  23214. return InterpolateSmooth;
  23215. }
  23216. }
  23217. getValueSize() {
  23218. return this.values.length / this.times.length;
  23219. }
  23220. // move all keyframes either forwards or backwards in time
  23221. shift( timeOffset ) {
  23222. if ( timeOffset !== 0.0 ) {
  23223. const times = this.times;
  23224. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23225. times[ i ] += timeOffset;
  23226. }
  23227. }
  23228. return this;
  23229. }
  23230. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23231. scale( timeScale ) {
  23232. if ( timeScale !== 1.0 ) {
  23233. const times = this.times;
  23234. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23235. times[ i ] *= timeScale;
  23236. }
  23237. }
  23238. return this;
  23239. }
  23240. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23241. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23242. trim( startTime, endTime ) {
  23243. const times = this.times,
  23244. nKeys = times.length;
  23245. let from = 0,
  23246. to = nKeys - 1;
  23247. while ( from !== nKeys && times[ from ] < startTime ) {
  23248. ++ from;
  23249. }
  23250. while ( to !== - 1 && times[ to ] > endTime ) {
  23251. -- to;
  23252. }
  23253. ++ to; // inclusive -> exclusive bound
  23254. if ( from !== 0 || to !== nKeys ) {
  23255. // empty tracks are forbidden, so keep at least one keyframe
  23256. if ( from >= to ) {
  23257. to = Math.max( to, 1 );
  23258. from = to - 1;
  23259. }
  23260. const stride = this.getValueSize();
  23261. this.times = arraySlice( times, from, to );
  23262. this.values = arraySlice( this.values, from * stride, to * stride );
  23263. }
  23264. return this;
  23265. }
  23266. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23267. validate() {
  23268. let valid = true;
  23269. const valueSize = this.getValueSize();
  23270. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23271. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23272. valid = false;
  23273. }
  23274. const times = this.times,
  23275. values = this.values,
  23276. nKeys = times.length;
  23277. if ( nKeys === 0 ) {
  23278. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23279. valid = false;
  23280. }
  23281. let prevTime = null;
  23282. for ( let i = 0; i !== nKeys; i ++ ) {
  23283. const currTime = times[ i ];
  23284. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23285. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23286. valid = false;
  23287. break;
  23288. }
  23289. if ( prevTime !== null && prevTime > currTime ) {
  23290. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23291. valid = false;
  23292. break;
  23293. }
  23294. prevTime = currTime;
  23295. }
  23296. if ( values !== undefined ) {
  23297. if ( isTypedArray( values ) ) {
  23298. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23299. const value = values[ i ];
  23300. if ( isNaN( value ) ) {
  23301. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23302. valid = false;
  23303. break;
  23304. }
  23305. }
  23306. }
  23307. }
  23308. return valid;
  23309. }
  23310. // removes equivalent sequential keys as common in morph target sequences
  23311. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23312. optimize() {
  23313. // times or values may be shared with other tracks, so overwriting is unsafe
  23314. const times = arraySlice( this.times ),
  23315. values = arraySlice( this.values ),
  23316. stride = this.getValueSize(),
  23317. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23318. lastIndex = times.length - 1;
  23319. let writeIndex = 1;
  23320. for ( let i = 1; i < lastIndex; ++ i ) {
  23321. let keep = false;
  23322. const time = times[ i ];
  23323. const timeNext = times[ i + 1 ];
  23324. // remove adjacent keyframes scheduled at the same time
  23325. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23326. if ( ! smoothInterpolation ) {
  23327. // remove unnecessary keyframes same as their neighbors
  23328. const offset = i * stride,
  23329. offsetP = offset - stride,
  23330. offsetN = offset + stride;
  23331. for ( let j = 0; j !== stride; ++ j ) {
  23332. const value = values[ offset + j ];
  23333. if ( value !== values[ offsetP + j ] ||
  23334. value !== values[ offsetN + j ] ) {
  23335. keep = true;
  23336. break;
  23337. }
  23338. }
  23339. } else {
  23340. keep = true;
  23341. }
  23342. }
  23343. // in-place compaction
  23344. if ( keep ) {
  23345. if ( i !== writeIndex ) {
  23346. times[ writeIndex ] = times[ i ];
  23347. const readOffset = i * stride,
  23348. writeOffset = writeIndex * stride;
  23349. for ( let j = 0; j !== stride; ++ j ) {
  23350. values[ writeOffset + j ] = values[ readOffset + j ];
  23351. }
  23352. }
  23353. ++ writeIndex;
  23354. }
  23355. }
  23356. // flush last keyframe (compaction looks ahead)
  23357. if ( lastIndex > 0 ) {
  23358. times[ writeIndex ] = times[ lastIndex ];
  23359. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23360. values[ writeOffset + j ] = values[ readOffset + j ];
  23361. }
  23362. ++ writeIndex;
  23363. }
  23364. if ( writeIndex !== times.length ) {
  23365. this.times = arraySlice( times, 0, writeIndex );
  23366. this.values = arraySlice( values, 0, writeIndex * stride );
  23367. } else {
  23368. this.times = times;
  23369. this.values = values;
  23370. }
  23371. return this;
  23372. }
  23373. clone() {
  23374. const times = arraySlice( this.times, 0 );
  23375. const values = arraySlice( this.values, 0 );
  23376. const TypedKeyframeTrack = this.constructor;
  23377. const track = new TypedKeyframeTrack( this.name, times, values );
  23378. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23379. track.createInterpolant = this.createInterpolant;
  23380. return track;
  23381. }
  23382. }
  23383. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23384. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23385. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23386. /**
  23387. * A Track of Boolean keyframe values.
  23388. */
  23389. class BooleanKeyframeTrack extends KeyframeTrack {}
  23390. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23391. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23392. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23393. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23394. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23395. /**
  23396. * A Track of keyframe values that represent color.
  23397. */
  23398. class ColorKeyframeTrack extends KeyframeTrack {}
  23399. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23400. /**
  23401. * A Track of numeric keyframe values.
  23402. */
  23403. class NumberKeyframeTrack extends KeyframeTrack {}
  23404. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23405. /**
  23406. * Spherical linear unit quaternion interpolant.
  23407. */
  23408. class QuaternionLinearInterpolant extends Interpolant {
  23409. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23410. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23411. }
  23412. interpolate_( i1, t0, t, t1 ) {
  23413. const result = this.resultBuffer,
  23414. values = this.sampleValues,
  23415. stride = this.valueSize,
  23416. alpha = ( t - t0 ) / ( t1 - t0 );
  23417. let offset = i1 * stride;
  23418. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23419. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23420. }
  23421. return result;
  23422. }
  23423. }
  23424. /**
  23425. * A Track of quaternion keyframe values.
  23426. */
  23427. class QuaternionKeyframeTrack extends KeyframeTrack {
  23428. InterpolantFactoryMethodLinear( result ) {
  23429. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23430. }
  23431. }
  23432. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23433. // ValueBufferType is inherited
  23434. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23435. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23436. /**
  23437. * A Track that interpolates Strings
  23438. */
  23439. class StringKeyframeTrack extends KeyframeTrack {}
  23440. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23441. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23442. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23443. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23444. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23445. /**
  23446. * A Track of vectored keyframe values.
  23447. */
  23448. class VectorKeyframeTrack extends KeyframeTrack {}
  23449. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23450. class AnimationClip {
  23451. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23452. this.name = name;
  23453. this.tracks = tracks;
  23454. this.duration = duration;
  23455. this.blendMode = blendMode;
  23456. this.uuid = generateUUID();
  23457. // this means it should figure out its duration by scanning the tracks
  23458. if ( this.duration < 0 ) {
  23459. this.resetDuration();
  23460. }
  23461. }
  23462. static parse( json ) {
  23463. const tracks = [],
  23464. jsonTracks = json.tracks,
  23465. frameTime = 1.0 / ( json.fps || 1.0 );
  23466. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23467. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23468. }
  23469. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23470. clip.uuid = json.uuid;
  23471. return clip;
  23472. }
  23473. static toJSON( clip ) {
  23474. const tracks = [],
  23475. clipTracks = clip.tracks;
  23476. const json = {
  23477. 'name': clip.name,
  23478. 'duration': clip.duration,
  23479. 'tracks': tracks,
  23480. 'uuid': clip.uuid,
  23481. 'blendMode': clip.blendMode
  23482. };
  23483. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23484. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23485. }
  23486. return json;
  23487. }
  23488. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23489. const numMorphTargets = morphTargetSequence.length;
  23490. const tracks = [];
  23491. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23492. let times = [];
  23493. let values = [];
  23494. times.push(
  23495. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23496. i,
  23497. ( i + 1 ) % numMorphTargets );
  23498. values.push( 0, 1, 0 );
  23499. const order = getKeyframeOrder( times );
  23500. times = sortedArray( times, 1, order );
  23501. values = sortedArray( values, 1, order );
  23502. // if there is a key at the first frame, duplicate it as the
  23503. // last frame as well for perfect loop.
  23504. if ( ! noLoop && times[ 0 ] === 0 ) {
  23505. times.push( numMorphTargets );
  23506. values.push( values[ 0 ] );
  23507. }
  23508. tracks.push(
  23509. new NumberKeyframeTrack(
  23510. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23511. times, values
  23512. ).scale( 1.0 / fps ) );
  23513. }
  23514. return new this( name, - 1, tracks );
  23515. }
  23516. static findByName( objectOrClipArray, name ) {
  23517. let clipArray = objectOrClipArray;
  23518. if ( ! Array.isArray( objectOrClipArray ) ) {
  23519. const o = objectOrClipArray;
  23520. clipArray = o.geometry && o.geometry.animations || o.animations;
  23521. }
  23522. for ( let i = 0; i < clipArray.length; i ++ ) {
  23523. if ( clipArray[ i ].name === name ) {
  23524. return clipArray[ i ];
  23525. }
  23526. }
  23527. return null;
  23528. }
  23529. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23530. const animationToMorphTargets = {};
  23531. // tested with https://regex101.com/ on trick sequences
  23532. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23533. const pattern = /^([\w-]*?)([\d]+)$/;
  23534. // sort morph target names into animation groups based
  23535. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23536. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23537. const morphTarget = morphTargets[ i ];
  23538. const parts = morphTarget.name.match( pattern );
  23539. if ( parts && parts.length > 1 ) {
  23540. const name = parts[ 1 ];
  23541. let animationMorphTargets = animationToMorphTargets[ name ];
  23542. if ( ! animationMorphTargets ) {
  23543. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23544. }
  23545. animationMorphTargets.push( morphTarget );
  23546. }
  23547. }
  23548. const clips = [];
  23549. for ( const name in animationToMorphTargets ) {
  23550. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23551. }
  23552. return clips;
  23553. }
  23554. // parse the animation.hierarchy format
  23555. static parseAnimation( animation, bones ) {
  23556. if ( ! animation ) {
  23557. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23558. return null;
  23559. }
  23560. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23561. // only return track if there are actually keys.
  23562. if ( animationKeys.length !== 0 ) {
  23563. const times = [];
  23564. const values = [];
  23565. flattenJSON( animationKeys, times, values, propertyName );
  23566. // empty keys are filtered out, so check again
  23567. if ( times.length !== 0 ) {
  23568. destTracks.push( new trackType( trackName, times, values ) );
  23569. }
  23570. }
  23571. };
  23572. const tracks = [];
  23573. const clipName = animation.name || 'default';
  23574. const fps = animation.fps || 30;
  23575. const blendMode = animation.blendMode;
  23576. // automatic length determination in AnimationClip.
  23577. let duration = animation.length || - 1;
  23578. const hierarchyTracks = animation.hierarchy || [];
  23579. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23580. const animationKeys = hierarchyTracks[ h ].keys;
  23581. // skip empty tracks
  23582. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23583. // process morph targets
  23584. if ( animationKeys[ 0 ].morphTargets ) {
  23585. // figure out all morph targets used in this track
  23586. const morphTargetNames = {};
  23587. let k;
  23588. for ( k = 0; k < animationKeys.length; k ++ ) {
  23589. if ( animationKeys[ k ].morphTargets ) {
  23590. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23591. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23592. }
  23593. }
  23594. }
  23595. // create a track for each morph target with all zero
  23596. // morphTargetInfluences except for the keys in which
  23597. // the morphTarget is named.
  23598. for ( const morphTargetName in morphTargetNames ) {
  23599. const times = [];
  23600. const values = [];
  23601. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23602. const animationKey = animationKeys[ k ];
  23603. times.push( animationKey.time );
  23604. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23605. }
  23606. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23607. }
  23608. duration = morphTargetNames.length * fps;
  23609. } else {
  23610. // ...assume skeletal animation
  23611. const boneName = '.bones[' + bones[ h ].name + ']';
  23612. addNonemptyTrack(
  23613. VectorKeyframeTrack, boneName + '.position',
  23614. animationKeys, 'pos', tracks );
  23615. addNonemptyTrack(
  23616. QuaternionKeyframeTrack, boneName + '.quaternion',
  23617. animationKeys, 'rot', tracks );
  23618. addNonemptyTrack(
  23619. VectorKeyframeTrack, boneName + '.scale',
  23620. animationKeys, 'scl', tracks );
  23621. }
  23622. }
  23623. if ( tracks.length === 0 ) {
  23624. return null;
  23625. }
  23626. const clip = new this( clipName, duration, tracks, blendMode );
  23627. return clip;
  23628. }
  23629. resetDuration() {
  23630. const tracks = this.tracks;
  23631. let duration = 0;
  23632. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23633. const track = this.tracks[ i ];
  23634. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23635. }
  23636. this.duration = duration;
  23637. return this;
  23638. }
  23639. trim() {
  23640. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23641. this.tracks[ i ].trim( 0, this.duration );
  23642. }
  23643. return this;
  23644. }
  23645. validate() {
  23646. let valid = true;
  23647. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23648. valid = valid && this.tracks[ i ].validate();
  23649. }
  23650. return valid;
  23651. }
  23652. optimize() {
  23653. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23654. this.tracks[ i ].optimize();
  23655. }
  23656. return this;
  23657. }
  23658. clone() {
  23659. const tracks = [];
  23660. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23661. tracks.push( this.tracks[ i ].clone() );
  23662. }
  23663. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23664. }
  23665. toJSON() {
  23666. return this.constructor.toJSON( this );
  23667. }
  23668. }
  23669. function getTrackTypeForValueTypeName( typeName ) {
  23670. switch ( typeName.toLowerCase() ) {
  23671. case 'scalar':
  23672. case 'double':
  23673. case 'float':
  23674. case 'number':
  23675. case 'integer':
  23676. return NumberKeyframeTrack;
  23677. case 'vector':
  23678. case 'vector2':
  23679. case 'vector3':
  23680. case 'vector4':
  23681. return VectorKeyframeTrack;
  23682. case 'color':
  23683. return ColorKeyframeTrack;
  23684. case 'quaternion':
  23685. return QuaternionKeyframeTrack;
  23686. case 'bool':
  23687. case 'boolean':
  23688. return BooleanKeyframeTrack;
  23689. case 'string':
  23690. return StringKeyframeTrack;
  23691. }
  23692. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23693. }
  23694. function parseKeyframeTrack( json ) {
  23695. if ( json.type === undefined ) {
  23696. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23697. }
  23698. const trackType = getTrackTypeForValueTypeName( json.type );
  23699. if ( json.times === undefined ) {
  23700. const times = [], values = [];
  23701. flattenJSON( json.keys, times, values, 'value' );
  23702. json.times = times;
  23703. json.values = values;
  23704. }
  23705. // derived classes can define a static parse method
  23706. if ( trackType.parse !== undefined ) {
  23707. return trackType.parse( json );
  23708. } else {
  23709. // by default, we assume a constructor compatible with the base
  23710. return new trackType( json.name, json.times, json.values, json.interpolation );
  23711. }
  23712. }
  23713. const Cache = {
  23714. enabled: false,
  23715. files: {},
  23716. add: function ( key, file ) {
  23717. if ( this.enabled === false ) return;
  23718. // console.log( 'THREE.Cache', 'Adding key:', key );
  23719. this.files[ key ] = file;
  23720. },
  23721. get: function ( key ) {
  23722. if ( this.enabled === false ) return;
  23723. // console.log( 'THREE.Cache', 'Checking key:', key );
  23724. return this.files[ key ];
  23725. },
  23726. remove: function ( key ) {
  23727. delete this.files[ key ];
  23728. },
  23729. clear: function () {
  23730. this.files = {};
  23731. }
  23732. };
  23733. class LoadingManager {
  23734. constructor( onLoad, onProgress, onError ) {
  23735. const scope = this;
  23736. let isLoading = false;
  23737. let itemsLoaded = 0;
  23738. let itemsTotal = 0;
  23739. let urlModifier = undefined;
  23740. const handlers = [];
  23741. // Refer to #5689 for the reason why we don't set .onStart
  23742. // in the constructor
  23743. this.onStart = undefined;
  23744. this.onLoad = onLoad;
  23745. this.onProgress = onProgress;
  23746. this.onError = onError;
  23747. this.itemStart = function ( url ) {
  23748. itemsTotal ++;
  23749. if ( isLoading === false ) {
  23750. if ( scope.onStart !== undefined ) {
  23751. scope.onStart( url, itemsLoaded, itemsTotal );
  23752. }
  23753. }
  23754. isLoading = true;
  23755. };
  23756. this.itemEnd = function ( url ) {
  23757. itemsLoaded ++;
  23758. if ( scope.onProgress !== undefined ) {
  23759. scope.onProgress( url, itemsLoaded, itemsTotal );
  23760. }
  23761. if ( itemsLoaded === itemsTotal ) {
  23762. isLoading = false;
  23763. if ( scope.onLoad !== undefined ) {
  23764. scope.onLoad();
  23765. }
  23766. }
  23767. };
  23768. this.itemError = function ( url ) {
  23769. if ( scope.onError !== undefined ) {
  23770. scope.onError( url );
  23771. }
  23772. };
  23773. this.resolveURL = function ( url ) {
  23774. if ( urlModifier ) {
  23775. return urlModifier( url );
  23776. }
  23777. return url;
  23778. };
  23779. this.setURLModifier = function ( transform ) {
  23780. urlModifier = transform;
  23781. return this;
  23782. };
  23783. this.addHandler = function ( regex, loader ) {
  23784. handlers.push( regex, loader );
  23785. return this;
  23786. };
  23787. this.removeHandler = function ( regex ) {
  23788. const index = handlers.indexOf( regex );
  23789. if ( index !== - 1 ) {
  23790. handlers.splice( index, 2 );
  23791. }
  23792. return this;
  23793. };
  23794. this.getHandler = function ( file ) {
  23795. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23796. const regex = handlers[ i ];
  23797. const loader = handlers[ i + 1 ];
  23798. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23799. if ( regex.test( file ) ) {
  23800. return loader;
  23801. }
  23802. }
  23803. return null;
  23804. };
  23805. }
  23806. }
  23807. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23808. class Loader {
  23809. constructor( manager ) {
  23810. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23811. this.crossOrigin = 'anonymous';
  23812. this.withCredentials = false;
  23813. this.path = '';
  23814. this.resourcePath = '';
  23815. this.requestHeader = {};
  23816. }
  23817. load( /* url, onLoad, onProgress, onError */ ) {}
  23818. loadAsync( url, onProgress ) {
  23819. const scope = this;
  23820. return new Promise( function ( resolve, reject ) {
  23821. scope.load( url, resolve, onProgress, reject );
  23822. } );
  23823. }
  23824. parse( /* data */ ) {}
  23825. setCrossOrigin( crossOrigin ) {
  23826. this.crossOrigin = crossOrigin;
  23827. return this;
  23828. }
  23829. setWithCredentials( value ) {
  23830. this.withCredentials = value;
  23831. return this;
  23832. }
  23833. setPath( path ) {
  23834. this.path = path;
  23835. return this;
  23836. }
  23837. setResourcePath( resourcePath ) {
  23838. this.resourcePath = resourcePath;
  23839. return this;
  23840. }
  23841. setRequestHeader( requestHeader ) {
  23842. this.requestHeader = requestHeader;
  23843. return this;
  23844. }
  23845. }
  23846. const loading = {};
  23847. class HttpError extends Error {
  23848. constructor( message, response ) {
  23849. super( message );
  23850. this.response = response;
  23851. }
  23852. }
  23853. class FileLoader extends Loader {
  23854. constructor( manager ) {
  23855. super( manager );
  23856. }
  23857. load( url, onLoad, onProgress, onError ) {
  23858. if ( url === undefined ) url = '';
  23859. if ( this.path !== undefined ) url = this.path + url;
  23860. url = this.manager.resolveURL( url );
  23861. const cached = Cache.get( url );
  23862. if ( cached !== undefined ) {
  23863. this.manager.itemStart( url );
  23864. setTimeout( () => {
  23865. if ( onLoad ) onLoad( cached );
  23866. this.manager.itemEnd( url );
  23867. }, 0 );
  23868. return cached;
  23869. }
  23870. // Check if request is duplicate
  23871. if ( loading[ url ] !== undefined ) {
  23872. loading[ url ].push( {
  23873. onLoad: onLoad,
  23874. onProgress: onProgress,
  23875. onError: onError
  23876. } );
  23877. return;
  23878. }
  23879. // Initialise array for duplicate requests
  23880. loading[ url ] = [];
  23881. loading[ url ].push( {
  23882. onLoad: onLoad,
  23883. onProgress: onProgress,
  23884. onError: onError,
  23885. } );
  23886. // create request
  23887. const req = new Request( url, {
  23888. headers: new Headers( this.requestHeader ),
  23889. credentials: this.withCredentials ? 'include' : 'same-origin',
  23890. // An abort controller could be added within a future PR
  23891. } );
  23892. // record states ( avoid data race )
  23893. const mimeType = this.mimeType;
  23894. const responseType = this.responseType;
  23895. // start the fetch
  23896. fetch( req )
  23897. .then( response => {
  23898. if ( response.status === 200 || response.status === 0 ) {
  23899. // Some browsers return HTTP Status 0 when using non-http protocol
  23900. // e.g. 'file://' or 'data://'. Handle as success.
  23901. if ( response.status === 0 ) {
  23902. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23903. }
  23904. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23905. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23906. return response;
  23907. }
  23908. const callbacks = loading[ url ];
  23909. const reader = response.body.getReader();
  23910. // Nginx needs X-File-Size check
  23911. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  23912. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  23913. const total = contentLength ? parseInt( contentLength ) : 0;
  23914. const lengthComputable = total !== 0;
  23915. let loaded = 0;
  23916. // periodically read data into the new stream tracking while download progress
  23917. const stream = new ReadableStream( {
  23918. start( controller ) {
  23919. readData();
  23920. function readData() {
  23921. reader.read().then( ( { done, value } ) => {
  23922. if ( done ) {
  23923. controller.close();
  23924. } else {
  23925. loaded += value.byteLength;
  23926. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23927. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23928. const callback = callbacks[ i ];
  23929. if ( callback.onProgress ) callback.onProgress( event );
  23930. }
  23931. controller.enqueue( value );
  23932. readData();
  23933. }
  23934. } );
  23935. }
  23936. }
  23937. } );
  23938. return new Response( stream );
  23939. } else {
  23940. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  23941. }
  23942. } )
  23943. .then( response => {
  23944. switch ( responseType ) {
  23945. case 'arraybuffer':
  23946. return response.arrayBuffer();
  23947. case 'blob':
  23948. return response.blob();
  23949. case 'document':
  23950. return response.text()
  23951. .then( text => {
  23952. const parser = new DOMParser();
  23953. return parser.parseFromString( text, mimeType );
  23954. } );
  23955. case 'json':
  23956. return response.json();
  23957. default:
  23958. if ( mimeType === undefined ) {
  23959. return response.text();
  23960. } else {
  23961. // sniff encoding
  23962. const re = /charset="?([^;"\s]*)"?/i;
  23963. const exec = re.exec( mimeType );
  23964. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23965. const decoder = new TextDecoder( label );
  23966. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23967. }
  23968. }
  23969. } )
  23970. .then( data => {
  23971. // Add to cache only on HTTP success, so that we do not cache
  23972. // error response bodies as proper responses to requests.
  23973. Cache.add( url, data );
  23974. const callbacks = loading[ url ];
  23975. delete loading[ url ];
  23976. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23977. const callback = callbacks[ i ];
  23978. if ( callback.onLoad ) callback.onLoad( data );
  23979. }
  23980. } )
  23981. .catch( err => {
  23982. // Abort errors and other errors are handled the same
  23983. const callbacks = loading[ url ];
  23984. if ( callbacks === undefined ) {
  23985. // When onLoad was called and url was deleted in `loading`
  23986. this.manager.itemError( url );
  23987. throw err;
  23988. }
  23989. delete loading[ url ];
  23990. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23991. const callback = callbacks[ i ];
  23992. if ( callback.onError ) callback.onError( err );
  23993. }
  23994. this.manager.itemError( url );
  23995. } )
  23996. .finally( () => {
  23997. this.manager.itemEnd( url );
  23998. } );
  23999. this.manager.itemStart( url );
  24000. }
  24001. setResponseType( value ) {
  24002. this.responseType = value;
  24003. return this;
  24004. }
  24005. setMimeType( value ) {
  24006. this.mimeType = value;
  24007. return this;
  24008. }
  24009. }
  24010. class AnimationLoader extends Loader {
  24011. constructor( manager ) {
  24012. super( manager );
  24013. }
  24014. load( url, onLoad, onProgress, onError ) {
  24015. const scope = this;
  24016. const loader = new FileLoader( this.manager );
  24017. loader.setPath( this.path );
  24018. loader.setRequestHeader( this.requestHeader );
  24019. loader.setWithCredentials( this.withCredentials );
  24020. loader.load( url, function ( text ) {
  24021. try {
  24022. onLoad( scope.parse( JSON.parse( text ) ) );
  24023. } catch ( e ) {
  24024. if ( onError ) {
  24025. onError( e );
  24026. } else {
  24027. console.error( e );
  24028. }
  24029. scope.manager.itemError( url );
  24030. }
  24031. }, onProgress, onError );
  24032. }
  24033. parse( json ) {
  24034. const animations = [];
  24035. for ( let i = 0; i < json.length; i ++ ) {
  24036. const clip = AnimationClip.parse( json[ i ] );
  24037. animations.push( clip );
  24038. }
  24039. return animations;
  24040. }
  24041. }
  24042. /**
  24043. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24044. *
  24045. * Sub classes have to implement the parse() method which will be used in load().
  24046. */
  24047. class CompressedTextureLoader extends Loader {
  24048. constructor( manager ) {
  24049. super( manager );
  24050. }
  24051. load( url, onLoad, onProgress, onError ) {
  24052. const scope = this;
  24053. const images = [];
  24054. const texture = new CompressedTexture();
  24055. const loader = new FileLoader( this.manager );
  24056. loader.setPath( this.path );
  24057. loader.setResponseType( 'arraybuffer' );
  24058. loader.setRequestHeader( this.requestHeader );
  24059. loader.setWithCredentials( scope.withCredentials );
  24060. let loaded = 0;
  24061. function loadTexture( i ) {
  24062. loader.load( url[ i ], function ( buffer ) {
  24063. const texDatas = scope.parse( buffer, true );
  24064. images[ i ] = {
  24065. width: texDatas.width,
  24066. height: texDatas.height,
  24067. format: texDatas.format,
  24068. mipmaps: texDatas.mipmaps
  24069. };
  24070. loaded += 1;
  24071. if ( loaded === 6 ) {
  24072. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24073. texture.image = images;
  24074. texture.format = texDatas.format;
  24075. texture.needsUpdate = true;
  24076. if ( onLoad ) onLoad( texture );
  24077. }
  24078. }, onProgress, onError );
  24079. }
  24080. if ( Array.isArray( url ) ) {
  24081. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24082. loadTexture( i );
  24083. }
  24084. } else {
  24085. // compressed cubemap texture stored in a single DDS file
  24086. loader.load( url, function ( buffer ) {
  24087. const texDatas = scope.parse( buffer, true );
  24088. if ( texDatas.isCubemap ) {
  24089. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24090. for ( let f = 0; f < faces; f ++ ) {
  24091. images[ f ] = { mipmaps: [] };
  24092. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24093. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24094. images[ f ].format = texDatas.format;
  24095. images[ f ].width = texDatas.width;
  24096. images[ f ].height = texDatas.height;
  24097. }
  24098. }
  24099. texture.image = images;
  24100. } else {
  24101. texture.image.width = texDatas.width;
  24102. texture.image.height = texDatas.height;
  24103. texture.mipmaps = texDatas.mipmaps;
  24104. }
  24105. if ( texDatas.mipmapCount === 1 ) {
  24106. texture.minFilter = LinearFilter;
  24107. }
  24108. texture.format = texDatas.format;
  24109. texture.needsUpdate = true;
  24110. if ( onLoad ) onLoad( texture );
  24111. }, onProgress, onError );
  24112. }
  24113. return texture;
  24114. }
  24115. }
  24116. class ImageLoader extends Loader {
  24117. constructor( manager ) {
  24118. super( manager );
  24119. }
  24120. load( url, onLoad, onProgress, onError ) {
  24121. if ( this.path !== undefined ) url = this.path + url;
  24122. url = this.manager.resolveURL( url );
  24123. const scope = this;
  24124. const cached = Cache.get( url );
  24125. if ( cached !== undefined ) {
  24126. scope.manager.itemStart( url );
  24127. setTimeout( function () {
  24128. if ( onLoad ) onLoad( cached );
  24129. scope.manager.itemEnd( url );
  24130. }, 0 );
  24131. return cached;
  24132. }
  24133. const image = createElementNS( 'img' );
  24134. function onImageLoad() {
  24135. removeEventListeners();
  24136. Cache.add( url, this );
  24137. if ( onLoad ) onLoad( this );
  24138. scope.manager.itemEnd( url );
  24139. }
  24140. function onImageError( event ) {
  24141. removeEventListeners();
  24142. if ( onError ) onError( event );
  24143. scope.manager.itemError( url );
  24144. scope.manager.itemEnd( url );
  24145. }
  24146. function removeEventListeners() {
  24147. image.removeEventListener( 'load', onImageLoad, false );
  24148. image.removeEventListener( 'error', onImageError, false );
  24149. }
  24150. image.addEventListener( 'load', onImageLoad, false );
  24151. image.addEventListener( 'error', onImageError, false );
  24152. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24153. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24154. }
  24155. scope.manager.itemStart( url );
  24156. image.src = url;
  24157. return image;
  24158. }
  24159. }
  24160. class CubeTextureLoader extends Loader {
  24161. constructor( manager ) {
  24162. super( manager );
  24163. }
  24164. load( urls, onLoad, onProgress, onError ) {
  24165. const texture = new CubeTexture();
  24166. const loader = new ImageLoader( this.manager );
  24167. loader.setCrossOrigin( this.crossOrigin );
  24168. loader.setPath( this.path );
  24169. let loaded = 0;
  24170. function loadTexture( i ) {
  24171. loader.load( urls[ i ], function ( image ) {
  24172. texture.images[ i ] = image;
  24173. loaded ++;
  24174. if ( loaded === 6 ) {
  24175. texture.needsUpdate = true;
  24176. if ( onLoad ) onLoad( texture );
  24177. }
  24178. }, undefined, onError );
  24179. }
  24180. for ( let i = 0; i < urls.length; ++ i ) {
  24181. loadTexture( i );
  24182. }
  24183. return texture;
  24184. }
  24185. }
  24186. /**
  24187. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24188. *
  24189. * Sub classes have to implement the parse() method which will be used in load().
  24190. */
  24191. class DataTextureLoader extends Loader {
  24192. constructor( manager ) {
  24193. super( manager );
  24194. }
  24195. load( url, onLoad, onProgress, onError ) {
  24196. const scope = this;
  24197. const texture = new DataTexture();
  24198. const loader = new FileLoader( this.manager );
  24199. loader.setResponseType( 'arraybuffer' );
  24200. loader.setRequestHeader( this.requestHeader );
  24201. loader.setPath( this.path );
  24202. loader.setWithCredentials( scope.withCredentials );
  24203. loader.load( url, function ( buffer ) {
  24204. const texData = scope.parse( buffer );
  24205. if ( ! texData ) return;
  24206. if ( texData.image !== undefined ) {
  24207. texture.image = texData.image;
  24208. } else if ( texData.data !== undefined ) {
  24209. texture.image.width = texData.width;
  24210. texture.image.height = texData.height;
  24211. texture.image.data = texData.data;
  24212. }
  24213. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24214. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24215. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24216. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24217. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24218. if ( texData.encoding !== undefined ) {
  24219. texture.encoding = texData.encoding;
  24220. }
  24221. if ( texData.flipY !== undefined ) {
  24222. texture.flipY = texData.flipY;
  24223. }
  24224. if ( texData.format !== undefined ) {
  24225. texture.format = texData.format;
  24226. }
  24227. if ( texData.type !== undefined ) {
  24228. texture.type = texData.type;
  24229. }
  24230. if ( texData.mipmaps !== undefined ) {
  24231. texture.mipmaps = texData.mipmaps;
  24232. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24233. }
  24234. if ( texData.mipmapCount === 1 ) {
  24235. texture.minFilter = LinearFilter;
  24236. }
  24237. if ( texData.generateMipmaps !== undefined ) {
  24238. texture.generateMipmaps = texData.generateMipmaps;
  24239. }
  24240. texture.needsUpdate = true;
  24241. if ( onLoad ) onLoad( texture, texData );
  24242. }, onProgress, onError );
  24243. return texture;
  24244. }
  24245. }
  24246. class TextureLoader extends Loader {
  24247. constructor( manager ) {
  24248. super( manager );
  24249. }
  24250. load( url, onLoad, onProgress, onError ) {
  24251. const texture = new Texture();
  24252. const loader = new ImageLoader( this.manager );
  24253. loader.setCrossOrigin( this.crossOrigin );
  24254. loader.setPath( this.path );
  24255. loader.load( url, function ( image ) {
  24256. texture.image = image;
  24257. texture.needsUpdate = true;
  24258. if ( onLoad !== undefined ) {
  24259. onLoad( texture );
  24260. }
  24261. }, onProgress, onError );
  24262. return texture;
  24263. }
  24264. }
  24265. class Light extends Object3D {
  24266. constructor( color, intensity = 1 ) {
  24267. super();
  24268. this.isLight = true;
  24269. this.type = 'Light';
  24270. this.color = new Color( color );
  24271. this.intensity = intensity;
  24272. }
  24273. dispose() {
  24274. // Empty here in base class; some subclasses override.
  24275. }
  24276. copy( source, recursive ) {
  24277. super.copy( source, recursive );
  24278. this.color.copy( source.color );
  24279. this.intensity = source.intensity;
  24280. return this;
  24281. }
  24282. toJSON( meta ) {
  24283. const data = super.toJSON( meta );
  24284. data.object.color = this.color.getHex();
  24285. data.object.intensity = this.intensity;
  24286. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24287. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24288. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24289. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24290. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24291. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24292. return data;
  24293. }
  24294. }
  24295. class HemisphereLight extends Light {
  24296. constructor( skyColor, groundColor, intensity ) {
  24297. super( skyColor, intensity );
  24298. this.isHemisphereLight = true;
  24299. this.type = 'HemisphereLight';
  24300. this.position.copy( Object3D.DEFAULT_UP );
  24301. this.updateMatrix();
  24302. this.groundColor = new Color( groundColor );
  24303. }
  24304. copy( source, recursive ) {
  24305. super.copy( source, recursive );
  24306. this.groundColor.copy( source.groundColor );
  24307. return this;
  24308. }
  24309. }
  24310. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24311. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24312. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24313. class LightShadow {
  24314. constructor( camera ) {
  24315. this.camera = camera;
  24316. this.bias = 0;
  24317. this.normalBias = 0;
  24318. this.radius = 1;
  24319. this.blurSamples = 8;
  24320. this.mapSize = new Vector2( 512, 512 );
  24321. this.map = null;
  24322. this.mapPass = null;
  24323. this.matrix = new Matrix4();
  24324. this.autoUpdate = true;
  24325. this.needsUpdate = false;
  24326. this._frustum = new Frustum();
  24327. this._frameExtents = new Vector2( 1, 1 );
  24328. this._viewportCount = 1;
  24329. this._viewports = [
  24330. new Vector4( 0, 0, 1, 1 )
  24331. ];
  24332. }
  24333. getViewportCount() {
  24334. return this._viewportCount;
  24335. }
  24336. getFrustum() {
  24337. return this._frustum;
  24338. }
  24339. updateMatrices( light ) {
  24340. const shadowCamera = this.camera;
  24341. const shadowMatrix = this.matrix;
  24342. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24343. shadowCamera.position.copy( _lightPositionWorld$1 );
  24344. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24345. shadowCamera.lookAt( _lookTarget$1 );
  24346. shadowCamera.updateMatrixWorld();
  24347. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24348. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24349. shadowMatrix.set(
  24350. 0.5, 0.0, 0.0, 0.5,
  24351. 0.0, 0.5, 0.0, 0.5,
  24352. 0.0, 0.0, 0.5, 0.5,
  24353. 0.0, 0.0, 0.0, 1.0
  24354. );
  24355. shadowMatrix.multiply( _projScreenMatrix$1 );
  24356. }
  24357. getViewport( viewportIndex ) {
  24358. return this._viewports[ viewportIndex ];
  24359. }
  24360. getFrameExtents() {
  24361. return this._frameExtents;
  24362. }
  24363. dispose() {
  24364. if ( this.map ) {
  24365. this.map.dispose();
  24366. }
  24367. if ( this.mapPass ) {
  24368. this.mapPass.dispose();
  24369. }
  24370. }
  24371. copy( source ) {
  24372. this.camera = source.camera.clone();
  24373. this.bias = source.bias;
  24374. this.radius = source.radius;
  24375. this.mapSize.copy( source.mapSize );
  24376. return this;
  24377. }
  24378. clone() {
  24379. return new this.constructor().copy( this );
  24380. }
  24381. toJSON() {
  24382. const object = {};
  24383. if ( this.bias !== 0 ) object.bias = this.bias;
  24384. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24385. if ( this.radius !== 1 ) object.radius = this.radius;
  24386. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24387. object.camera = this.camera.toJSON( false ).object;
  24388. delete object.camera.matrix;
  24389. return object;
  24390. }
  24391. }
  24392. class SpotLightShadow extends LightShadow {
  24393. constructor() {
  24394. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24395. this.isSpotLightShadow = true;
  24396. this.focus = 1;
  24397. }
  24398. updateMatrices( light ) {
  24399. const camera = this.camera;
  24400. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24401. const aspect = this.mapSize.width / this.mapSize.height;
  24402. const far = light.distance || camera.far;
  24403. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24404. camera.fov = fov;
  24405. camera.aspect = aspect;
  24406. camera.far = far;
  24407. camera.updateProjectionMatrix();
  24408. }
  24409. super.updateMatrices( light );
  24410. }
  24411. copy( source ) {
  24412. super.copy( source );
  24413. this.focus = source.focus;
  24414. return this;
  24415. }
  24416. }
  24417. class SpotLight extends Light {
  24418. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24419. super( color, intensity );
  24420. this.isSpotLight = true;
  24421. this.type = 'SpotLight';
  24422. this.position.copy( Object3D.DEFAULT_UP );
  24423. this.updateMatrix();
  24424. this.target = new Object3D();
  24425. this.distance = distance;
  24426. this.angle = angle;
  24427. this.penumbra = penumbra;
  24428. this.decay = decay;
  24429. this.map = null;
  24430. this.shadow = new SpotLightShadow();
  24431. }
  24432. get power() {
  24433. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24434. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24435. return this.intensity * Math.PI;
  24436. }
  24437. set power( power ) {
  24438. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24439. this.intensity = power / Math.PI;
  24440. }
  24441. dispose() {
  24442. this.shadow.dispose();
  24443. }
  24444. copy( source, recursive ) {
  24445. super.copy( source, recursive );
  24446. this.distance = source.distance;
  24447. this.angle = source.angle;
  24448. this.penumbra = source.penumbra;
  24449. this.decay = source.decay;
  24450. this.target = source.target.clone();
  24451. this.shadow = source.shadow.clone();
  24452. return this;
  24453. }
  24454. }
  24455. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24456. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24457. const _lookTarget = /*@__PURE__*/ new Vector3();
  24458. class PointLightShadow extends LightShadow {
  24459. constructor() {
  24460. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24461. this.isPointLightShadow = true;
  24462. this._frameExtents = new Vector2( 4, 2 );
  24463. this._viewportCount = 6;
  24464. this._viewports = [
  24465. // These viewports map a cube-map onto a 2D texture with the
  24466. // following orientation:
  24467. //
  24468. // xzXZ
  24469. // y Y
  24470. //
  24471. // X - Positive x direction
  24472. // x - Negative x direction
  24473. // Y - Positive y direction
  24474. // y - Negative y direction
  24475. // Z - Positive z direction
  24476. // z - Negative z direction
  24477. // positive X
  24478. new Vector4( 2, 1, 1, 1 ),
  24479. // negative X
  24480. new Vector4( 0, 1, 1, 1 ),
  24481. // positive Z
  24482. new Vector4( 3, 1, 1, 1 ),
  24483. // negative Z
  24484. new Vector4( 1, 1, 1, 1 ),
  24485. // positive Y
  24486. new Vector4( 3, 0, 1, 1 ),
  24487. // negative Y
  24488. new Vector4( 1, 0, 1, 1 )
  24489. ];
  24490. this._cubeDirections = [
  24491. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24492. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24493. ];
  24494. this._cubeUps = [
  24495. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24496. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24497. ];
  24498. }
  24499. updateMatrices( light, viewportIndex = 0 ) {
  24500. const camera = this.camera;
  24501. const shadowMatrix = this.matrix;
  24502. const far = light.distance || camera.far;
  24503. if ( far !== camera.far ) {
  24504. camera.far = far;
  24505. camera.updateProjectionMatrix();
  24506. }
  24507. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24508. camera.position.copy( _lightPositionWorld );
  24509. _lookTarget.copy( camera.position );
  24510. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24511. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24512. camera.lookAt( _lookTarget );
  24513. camera.updateMatrixWorld();
  24514. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24515. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24516. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24517. }
  24518. }
  24519. class PointLight extends Light {
  24520. constructor( color, intensity, distance = 0, decay = 2 ) {
  24521. super( color, intensity );
  24522. this.isPointLight = true;
  24523. this.type = 'PointLight';
  24524. this.distance = distance;
  24525. this.decay = decay;
  24526. this.shadow = new PointLightShadow();
  24527. }
  24528. get power() {
  24529. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24530. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24531. return this.intensity * 4 * Math.PI;
  24532. }
  24533. set power( power ) {
  24534. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24535. this.intensity = power / ( 4 * Math.PI );
  24536. }
  24537. dispose() {
  24538. this.shadow.dispose();
  24539. }
  24540. copy( source, recursive ) {
  24541. super.copy( source, recursive );
  24542. this.distance = source.distance;
  24543. this.decay = source.decay;
  24544. this.shadow = source.shadow.clone();
  24545. return this;
  24546. }
  24547. }
  24548. class DirectionalLightShadow extends LightShadow {
  24549. constructor() {
  24550. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24551. this.isDirectionalLightShadow = true;
  24552. }
  24553. }
  24554. class DirectionalLight extends Light {
  24555. constructor( color, intensity ) {
  24556. super( color, intensity );
  24557. this.isDirectionalLight = true;
  24558. this.type = 'DirectionalLight';
  24559. this.position.copy( Object3D.DEFAULT_UP );
  24560. this.updateMatrix();
  24561. this.target = new Object3D();
  24562. this.shadow = new DirectionalLightShadow();
  24563. }
  24564. dispose() {
  24565. this.shadow.dispose();
  24566. }
  24567. copy( source ) {
  24568. super.copy( source );
  24569. this.target = source.target.clone();
  24570. this.shadow = source.shadow.clone();
  24571. return this;
  24572. }
  24573. }
  24574. class AmbientLight extends Light {
  24575. constructor( color, intensity ) {
  24576. super( color, intensity );
  24577. this.isAmbientLight = true;
  24578. this.type = 'AmbientLight';
  24579. }
  24580. }
  24581. class RectAreaLight extends Light {
  24582. constructor( color, intensity, width = 10, height = 10 ) {
  24583. super( color, intensity );
  24584. this.isRectAreaLight = true;
  24585. this.type = 'RectAreaLight';
  24586. this.width = width;
  24587. this.height = height;
  24588. }
  24589. get power() {
  24590. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24591. return this.intensity * this.width * this.height * Math.PI;
  24592. }
  24593. set power( power ) {
  24594. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24595. this.intensity = power / ( this.width * this.height * Math.PI );
  24596. }
  24597. copy( source ) {
  24598. super.copy( source );
  24599. this.width = source.width;
  24600. this.height = source.height;
  24601. return this;
  24602. }
  24603. toJSON( meta ) {
  24604. const data = super.toJSON( meta );
  24605. data.object.width = this.width;
  24606. data.object.height = this.height;
  24607. return data;
  24608. }
  24609. }
  24610. /**
  24611. * Primary reference:
  24612. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24613. *
  24614. * Secondary reference:
  24615. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24616. */
  24617. // 3-band SH defined by 9 coefficients
  24618. class SphericalHarmonics3 {
  24619. constructor() {
  24620. this.isSphericalHarmonics3 = true;
  24621. this.coefficients = [];
  24622. for ( let i = 0; i < 9; i ++ ) {
  24623. this.coefficients.push( new Vector3() );
  24624. }
  24625. }
  24626. set( coefficients ) {
  24627. for ( let i = 0; i < 9; i ++ ) {
  24628. this.coefficients[ i ].copy( coefficients[ i ] );
  24629. }
  24630. return this;
  24631. }
  24632. zero() {
  24633. for ( let i = 0; i < 9; i ++ ) {
  24634. this.coefficients[ i ].set( 0, 0, 0 );
  24635. }
  24636. return this;
  24637. }
  24638. // get the radiance in the direction of the normal
  24639. // target is a Vector3
  24640. getAt( normal, target ) {
  24641. // normal is assumed to be unit length
  24642. const x = normal.x, y = normal.y, z = normal.z;
  24643. const coeff = this.coefficients;
  24644. // band 0
  24645. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24646. // band 1
  24647. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24648. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24649. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24650. // band 2
  24651. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24652. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24653. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24654. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24655. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24656. return target;
  24657. }
  24658. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24659. // target is a Vector3
  24660. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24661. getIrradianceAt( normal, target ) {
  24662. // normal is assumed to be unit length
  24663. const x = normal.x, y = normal.y, z = normal.z;
  24664. const coeff = this.coefficients;
  24665. // band 0
  24666. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24667. // band 1
  24668. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24669. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24670. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24671. // band 2
  24672. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24673. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24674. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24675. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24676. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24677. return target;
  24678. }
  24679. add( sh ) {
  24680. for ( let i = 0; i < 9; i ++ ) {
  24681. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24682. }
  24683. return this;
  24684. }
  24685. addScaledSH( sh, s ) {
  24686. for ( let i = 0; i < 9; i ++ ) {
  24687. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24688. }
  24689. return this;
  24690. }
  24691. scale( s ) {
  24692. for ( let i = 0; i < 9; i ++ ) {
  24693. this.coefficients[ i ].multiplyScalar( s );
  24694. }
  24695. return this;
  24696. }
  24697. lerp( sh, alpha ) {
  24698. for ( let i = 0; i < 9; i ++ ) {
  24699. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24700. }
  24701. return this;
  24702. }
  24703. equals( sh ) {
  24704. for ( let i = 0; i < 9; i ++ ) {
  24705. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24706. return false;
  24707. }
  24708. }
  24709. return true;
  24710. }
  24711. copy( sh ) {
  24712. return this.set( sh.coefficients );
  24713. }
  24714. clone() {
  24715. return new this.constructor().copy( this );
  24716. }
  24717. fromArray( array, offset = 0 ) {
  24718. const coefficients = this.coefficients;
  24719. for ( let i = 0; i < 9; i ++ ) {
  24720. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24721. }
  24722. return this;
  24723. }
  24724. toArray( array = [], offset = 0 ) {
  24725. const coefficients = this.coefficients;
  24726. for ( let i = 0; i < 9; i ++ ) {
  24727. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24728. }
  24729. return array;
  24730. }
  24731. // evaluate the basis functions
  24732. // shBasis is an Array[ 9 ]
  24733. static getBasisAt( normal, shBasis ) {
  24734. // normal is assumed to be unit length
  24735. const x = normal.x, y = normal.y, z = normal.z;
  24736. // band 0
  24737. shBasis[ 0 ] = 0.282095;
  24738. // band 1
  24739. shBasis[ 1 ] = 0.488603 * y;
  24740. shBasis[ 2 ] = 0.488603 * z;
  24741. shBasis[ 3 ] = 0.488603 * x;
  24742. // band 2
  24743. shBasis[ 4 ] = 1.092548 * x * y;
  24744. shBasis[ 5 ] = 1.092548 * y * z;
  24745. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24746. shBasis[ 7 ] = 1.092548 * x * z;
  24747. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24748. }
  24749. }
  24750. class LightProbe extends Light {
  24751. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24752. super( undefined, intensity );
  24753. this.isLightProbe = true;
  24754. this.sh = sh;
  24755. }
  24756. copy( source ) {
  24757. super.copy( source );
  24758. this.sh.copy( source.sh );
  24759. return this;
  24760. }
  24761. fromJSON( json ) {
  24762. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24763. this.sh.fromArray( json.sh );
  24764. return this;
  24765. }
  24766. toJSON( meta ) {
  24767. const data = super.toJSON( meta );
  24768. data.object.sh = this.sh.toArray();
  24769. return data;
  24770. }
  24771. }
  24772. class MaterialLoader extends Loader {
  24773. constructor( manager ) {
  24774. super( manager );
  24775. this.textures = {};
  24776. }
  24777. load( url, onLoad, onProgress, onError ) {
  24778. const scope = this;
  24779. const loader = new FileLoader( scope.manager );
  24780. loader.setPath( scope.path );
  24781. loader.setRequestHeader( scope.requestHeader );
  24782. loader.setWithCredentials( scope.withCredentials );
  24783. loader.load( url, function ( text ) {
  24784. try {
  24785. onLoad( scope.parse( JSON.parse( text ) ) );
  24786. } catch ( e ) {
  24787. if ( onError ) {
  24788. onError( e );
  24789. } else {
  24790. console.error( e );
  24791. }
  24792. scope.manager.itemError( url );
  24793. }
  24794. }, onProgress, onError );
  24795. }
  24796. parse( json ) {
  24797. const textures = this.textures;
  24798. function getTexture( name ) {
  24799. if ( textures[ name ] === undefined ) {
  24800. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24801. }
  24802. return textures[ name ];
  24803. }
  24804. const material = MaterialLoader.createMaterialFromType( json.type );
  24805. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24806. if ( json.name !== undefined ) material.name = json.name;
  24807. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24808. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24809. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24810. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24811. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24812. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24813. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24814. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24815. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24816. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24817. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24818. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24819. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24820. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24821. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24822. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24823. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24824. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24825. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24826. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24827. if ( json.fog !== undefined ) material.fog = json.fog;
  24828. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24829. if ( json.blending !== undefined ) material.blending = json.blending;
  24830. if ( json.combine !== undefined ) material.combine = json.combine;
  24831. if ( json.side !== undefined ) material.side = json.side;
  24832. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24833. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24834. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24835. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24836. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24837. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24838. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24839. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24840. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24841. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24842. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24843. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24844. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24845. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24846. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24847. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24848. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24849. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24850. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24851. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24852. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24853. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24854. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24855. if ( json.scale !== undefined ) material.scale = json.scale;
  24856. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24857. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24858. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24859. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24860. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24861. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24862. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24863. if ( json.visible !== undefined ) material.visible = json.visible;
  24864. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24865. if ( json.userData !== undefined ) material.userData = json.userData;
  24866. if ( json.vertexColors !== undefined ) {
  24867. if ( typeof json.vertexColors === 'number' ) {
  24868. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24869. } else {
  24870. material.vertexColors = json.vertexColors;
  24871. }
  24872. }
  24873. // Shader Material
  24874. if ( json.uniforms !== undefined ) {
  24875. for ( const name in json.uniforms ) {
  24876. const uniform = json.uniforms[ name ];
  24877. material.uniforms[ name ] = {};
  24878. switch ( uniform.type ) {
  24879. case 't':
  24880. material.uniforms[ name ].value = getTexture( uniform.value );
  24881. break;
  24882. case 'c':
  24883. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24884. break;
  24885. case 'v2':
  24886. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24887. break;
  24888. case 'v3':
  24889. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24890. break;
  24891. case 'v4':
  24892. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24893. break;
  24894. case 'm3':
  24895. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24896. break;
  24897. case 'm4':
  24898. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24899. break;
  24900. default:
  24901. material.uniforms[ name ].value = uniform.value;
  24902. }
  24903. }
  24904. }
  24905. if ( json.defines !== undefined ) material.defines = json.defines;
  24906. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24907. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24908. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24909. if ( json.extensions !== undefined ) {
  24910. for ( const key in json.extensions ) {
  24911. material.extensions[ key ] = json.extensions[ key ];
  24912. }
  24913. }
  24914. // for PointsMaterial
  24915. if ( json.size !== undefined ) material.size = json.size;
  24916. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24917. // maps
  24918. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24919. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24920. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24921. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24922. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24923. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24924. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24925. if ( json.normalScale !== undefined ) {
  24926. let normalScale = json.normalScale;
  24927. if ( Array.isArray( normalScale ) === false ) {
  24928. // Blender exporter used to export a scalar. See #7459
  24929. normalScale = [ normalScale, normalScale ];
  24930. }
  24931. material.normalScale = new Vector2().fromArray( normalScale );
  24932. }
  24933. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24934. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24935. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24936. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24937. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24938. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24939. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24940. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24941. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24942. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24943. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24944. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24945. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24946. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24947. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24948. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24949. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24950. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24951. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24952. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24953. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24954. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24955. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24956. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24957. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24958. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24959. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24960. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24961. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24962. return material;
  24963. }
  24964. setTextures( value ) {
  24965. this.textures = value;
  24966. return this;
  24967. }
  24968. static createMaterialFromType( type ) {
  24969. const materialLib = {
  24970. ShadowMaterial,
  24971. SpriteMaterial,
  24972. RawShaderMaterial,
  24973. ShaderMaterial,
  24974. PointsMaterial,
  24975. MeshPhysicalMaterial,
  24976. MeshStandardMaterial,
  24977. MeshPhongMaterial,
  24978. MeshToonMaterial,
  24979. MeshNormalMaterial,
  24980. MeshLambertMaterial,
  24981. MeshDepthMaterial,
  24982. MeshDistanceMaterial,
  24983. MeshBasicMaterial,
  24984. MeshMatcapMaterial,
  24985. LineDashedMaterial,
  24986. LineBasicMaterial,
  24987. Material
  24988. };
  24989. return new materialLib[ type ]();
  24990. }
  24991. }
  24992. class LoaderUtils {
  24993. static decodeText( array ) {
  24994. if ( typeof TextDecoder !== 'undefined' ) {
  24995. return new TextDecoder().decode( array );
  24996. }
  24997. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24998. // throws a "maximum call stack size exceeded" error for large arrays.
  24999. let s = '';
  25000. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25001. // Implicitly assumes little-endian.
  25002. s += String.fromCharCode( array[ i ] );
  25003. }
  25004. try {
  25005. // merges multi-byte utf-8 characters.
  25006. return decodeURIComponent( escape( s ) );
  25007. } catch ( e ) { // see #16358
  25008. return s;
  25009. }
  25010. }
  25011. static extractUrlBase( url ) {
  25012. const index = url.lastIndexOf( '/' );
  25013. if ( index === - 1 ) return './';
  25014. return url.slice( 0, index + 1 );
  25015. }
  25016. static resolveURL( url, path ) {
  25017. // Invalid URL
  25018. if ( typeof url !== 'string' || url === '' ) return '';
  25019. // Host Relative URL
  25020. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25021. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25022. }
  25023. // Absolute URL http://,https://,//
  25024. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25025. // Data URI
  25026. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25027. // Blob URL
  25028. if ( /^blob:.*$/i.test( url ) ) return url;
  25029. // Relative URL
  25030. return path + url;
  25031. }
  25032. }
  25033. class InstancedBufferGeometry extends BufferGeometry {
  25034. constructor() {
  25035. super();
  25036. this.isInstancedBufferGeometry = true;
  25037. this.type = 'InstancedBufferGeometry';
  25038. this.instanceCount = Infinity;
  25039. }
  25040. copy( source ) {
  25041. super.copy( source );
  25042. this.instanceCount = source.instanceCount;
  25043. return this;
  25044. }
  25045. toJSON() {
  25046. const data = super.toJSON();
  25047. data.instanceCount = this.instanceCount;
  25048. data.isInstancedBufferGeometry = true;
  25049. return data;
  25050. }
  25051. }
  25052. class BufferGeometryLoader extends Loader {
  25053. constructor( manager ) {
  25054. super( manager );
  25055. }
  25056. load( url, onLoad, onProgress, onError ) {
  25057. const scope = this;
  25058. const loader = new FileLoader( scope.manager );
  25059. loader.setPath( scope.path );
  25060. loader.setRequestHeader( scope.requestHeader );
  25061. loader.setWithCredentials( scope.withCredentials );
  25062. loader.load( url, function ( text ) {
  25063. try {
  25064. onLoad( scope.parse( JSON.parse( text ) ) );
  25065. } catch ( e ) {
  25066. if ( onError ) {
  25067. onError( e );
  25068. } else {
  25069. console.error( e );
  25070. }
  25071. scope.manager.itemError( url );
  25072. }
  25073. }, onProgress, onError );
  25074. }
  25075. parse( json ) {
  25076. const interleavedBufferMap = {};
  25077. const arrayBufferMap = {};
  25078. function getInterleavedBuffer( json, uuid ) {
  25079. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25080. const interleavedBuffers = json.interleavedBuffers;
  25081. const interleavedBuffer = interleavedBuffers[ uuid ];
  25082. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25083. const array = getTypedArray( interleavedBuffer.type, buffer );
  25084. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25085. ib.uuid = interleavedBuffer.uuid;
  25086. interleavedBufferMap[ uuid ] = ib;
  25087. return ib;
  25088. }
  25089. function getArrayBuffer( json, uuid ) {
  25090. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25091. const arrayBuffers = json.arrayBuffers;
  25092. const arrayBuffer = arrayBuffers[ uuid ];
  25093. const ab = new Uint32Array( arrayBuffer ).buffer;
  25094. arrayBufferMap[ uuid ] = ab;
  25095. return ab;
  25096. }
  25097. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25098. const index = json.data.index;
  25099. if ( index !== undefined ) {
  25100. const typedArray = getTypedArray( index.type, index.array );
  25101. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25102. }
  25103. const attributes = json.data.attributes;
  25104. for ( const key in attributes ) {
  25105. const attribute = attributes[ key ];
  25106. let bufferAttribute;
  25107. if ( attribute.isInterleavedBufferAttribute ) {
  25108. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25109. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25110. } else {
  25111. const typedArray = getTypedArray( attribute.type, attribute.array );
  25112. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25113. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25114. }
  25115. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25116. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25117. if ( attribute.updateRange !== undefined ) {
  25118. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25119. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25120. }
  25121. geometry.setAttribute( key, bufferAttribute );
  25122. }
  25123. const morphAttributes = json.data.morphAttributes;
  25124. if ( morphAttributes ) {
  25125. for ( const key in morphAttributes ) {
  25126. const attributeArray = morphAttributes[ key ];
  25127. const array = [];
  25128. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25129. const attribute = attributeArray[ i ];
  25130. let bufferAttribute;
  25131. if ( attribute.isInterleavedBufferAttribute ) {
  25132. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25133. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25134. } else {
  25135. const typedArray = getTypedArray( attribute.type, attribute.array );
  25136. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25137. }
  25138. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25139. array.push( bufferAttribute );
  25140. }
  25141. geometry.morphAttributes[ key ] = array;
  25142. }
  25143. }
  25144. const morphTargetsRelative = json.data.morphTargetsRelative;
  25145. if ( morphTargetsRelative ) {
  25146. geometry.morphTargetsRelative = true;
  25147. }
  25148. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25149. if ( groups !== undefined ) {
  25150. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25151. const group = groups[ i ];
  25152. geometry.addGroup( group.start, group.count, group.materialIndex );
  25153. }
  25154. }
  25155. const boundingSphere = json.data.boundingSphere;
  25156. if ( boundingSphere !== undefined ) {
  25157. const center = new Vector3();
  25158. if ( boundingSphere.center !== undefined ) {
  25159. center.fromArray( boundingSphere.center );
  25160. }
  25161. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25162. }
  25163. if ( json.name ) geometry.name = json.name;
  25164. if ( json.userData ) geometry.userData = json.userData;
  25165. return geometry;
  25166. }
  25167. }
  25168. class ObjectLoader extends Loader {
  25169. constructor( manager ) {
  25170. super( manager );
  25171. }
  25172. load( url, onLoad, onProgress, onError ) {
  25173. const scope = this;
  25174. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25175. this.resourcePath = this.resourcePath || path;
  25176. const loader = new FileLoader( this.manager );
  25177. loader.setPath( this.path );
  25178. loader.setRequestHeader( this.requestHeader );
  25179. loader.setWithCredentials( this.withCredentials );
  25180. loader.load( url, function ( text ) {
  25181. let json = null;
  25182. try {
  25183. json = JSON.parse( text );
  25184. } catch ( error ) {
  25185. if ( onError !== undefined ) onError( error );
  25186. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25187. return;
  25188. }
  25189. const metadata = json.metadata;
  25190. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25191. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25192. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25193. return;
  25194. }
  25195. scope.parse( json, onLoad );
  25196. }, onProgress, onError );
  25197. }
  25198. async loadAsync( url, onProgress ) {
  25199. const scope = this;
  25200. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25201. this.resourcePath = this.resourcePath || path;
  25202. const loader = new FileLoader( this.manager );
  25203. loader.setPath( this.path );
  25204. loader.setRequestHeader( this.requestHeader );
  25205. loader.setWithCredentials( this.withCredentials );
  25206. const text = await loader.loadAsync( url, onProgress );
  25207. const json = JSON.parse( text );
  25208. const metadata = json.metadata;
  25209. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25210. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25211. }
  25212. return await scope.parseAsync( json );
  25213. }
  25214. parse( json, onLoad ) {
  25215. const animations = this.parseAnimations( json.animations );
  25216. const shapes = this.parseShapes( json.shapes );
  25217. const geometries = this.parseGeometries( json.geometries, shapes );
  25218. const images = this.parseImages( json.images, function () {
  25219. if ( onLoad !== undefined ) onLoad( object );
  25220. } );
  25221. const textures = this.parseTextures( json.textures, images );
  25222. const materials = this.parseMaterials( json.materials, textures );
  25223. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25224. const skeletons = this.parseSkeletons( json.skeletons, object );
  25225. this.bindSkeletons( object, skeletons );
  25226. //
  25227. if ( onLoad !== undefined ) {
  25228. let hasImages = false;
  25229. for ( const uuid in images ) {
  25230. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25231. hasImages = true;
  25232. break;
  25233. }
  25234. }
  25235. if ( hasImages === false ) onLoad( object );
  25236. }
  25237. return object;
  25238. }
  25239. async parseAsync( json ) {
  25240. const animations = this.parseAnimations( json.animations );
  25241. const shapes = this.parseShapes( json.shapes );
  25242. const geometries = this.parseGeometries( json.geometries, shapes );
  25243. const images = await this.parseImagesAsync( json.images );
  25244. const textures = this.parseTextures( json.textures, images );
  25245. const materials = this.parseMaterials( json.materials, textures );
  25246. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25247. const skeletons = this.parseSkeletons( json.skeletons, object );
  25248. this.bindSkeletons( object, skeletons );
  25249. return object;
  25250. }
  25251. parseShapes( json ) {
  25252. const shapes = {};
  25253. if ( json !== undefined ) {
  25254. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25255. const shape = new Shape().fromJSON( json[ i ] );
  25256. shapes[ shape.uuid ] = shape;
  25257. }
  25258. }
  25259. return shapes;
  25260. }
  25261. parseSkeletons( json, object ) {
  25262. const skeletons = {};
  25263. const bones = {};
  25264. // generate bone lookup table
  25265. object.traverse( function ( child ) {
  25266. if ( child.isBone ) bones[ child.uuid ] = child;
  25267. } );
  25268. // create skeletons
  25269. if ( json !== undefined ) {
  25270. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25271. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25272. skeletons[ skeleton.uuid ] = skeleton;
  25273. }
  25274. }
  25275. return skeletons;
  25276. }
  25277. parseGeometries( json, shapes ) {
  25278. const geometries = {};
  25279. if ( json !== undefined ) {
  25280. const bufferGeometryLoader = new BufferGeometryLoader();
  25281. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25282. let geometry;
  25283. const data = json[ i ];
  25284. switch ( data.type ) {
  25285. case 'BufferGeometry':
  25286. case 'InstancedBufferGeometry':
  25287. geometry = bufferGeometryLoader.parse( data );
  25288. break;
  25289. default:
  25290. if ( data.type in Geometries ) {
  25291. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25292. } else {
  25293. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25294. }
  25295. }
  25296. geometry.uuid = data.uuid;
  25297. if ( data.name !== undefined ) geometry.name = data.name;
  25298. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25299. geometries[ data.uuid ] = geometry;
  25300. }
  25301. }
  25302. return geometries;
  25303. }
  25304. parseMaterials( json, textures ) {
  25305. const cache = {}; // MultiMaterial
  25306. const materials = {};
  25307. if ( json !== undefined ) {
  25308. const loader = new MaterialLoader();
  25309. loader.setTextures( textures );
  25310. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25311. const data = json[ i ];
  25312. if ( cache[ data.uuid ] === undefined ) {
  25313. cache[ data.uuid ] = loader.parse( data );
  25314. }
  25315. materials[ data.uuid ] = cache[ data.uuid ];
  25316. }
  25317. }
  25318. return materials;
  25319. }
  25320. parseAnimations( json ) {
  25321. const animations = {};
  25322. if ( json !== undefined ) {
  25323. for ( let i = 0; i < json.length; i ++ ) {
  25324. const data = json[ i ];
  25325. const clip = AnimationClip.parse( data );
  25326. animations[ clip.uuid ] = clip;
  25327. }
  25328. }
  25329. return animations;
  25330. }
  25331. parseImages( json, onLoad ) {
  25332. const scope = this;
  25333. const images = {};
  25334. let loader;
  25335. function loadImage( url ) {
  25336. scope.manager.itemStart( url );
  25337. return loader.load( url, function () {
  25338. scope.manager.itemEnd( url );
  25339. }, undefined, function () {
  25340. scope.manager.itemError( url );
  25341. scope.manager.itemEnd( url );
  25342. } );
  25343. }
  25344. function deserializeImage( image ) {
  25345. if ( typeof image === 'string' ) {
  25346. const url = image;
  25347. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25348. return loadImage( path );
  25349. } else {
  25350. if ( image.data ) {
  25351. return {
  25352. data: getTypedArray( image.type, image.data ),
  25353. width: image.width,
  25354. height: image.height
  25355. };
  25356. } else {
  25357. return null;
  25358. }
  25359. }
  25360. }
  25361. if ( json !== undefined && json.length > 0 ) {
  25362. const manager = new LoadingManager( onLoad );
  25363. loader = new ImageLoader( manager );
  25364. loader.setCrossOrigin( this.crossOrigin );
  25365. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25366. const image = json[ i ];
  25367. const url = image.url;
  25368. if ( Array.isArray( url ) ) {
  25369. // load array of images e.g CubeTexture
  25370. const imageArray = [];
  25371. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25372. const currentUrl = url[ j ];
  25373. const deserializedImage = deserializeImage( currentUrl );
  25374. if ( deserializedImage !== null ) {
  25375. if ( deserializedImage instanceof HTMLImageElement ) {
  25376. imageArray.push( deserializedImage );
  25377. } else {
  25378. // special case: handle array of data textures for cube textures
  25379. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25380. }
  25381. }
  25382. }
  25383. images[ image.uuid ] = new Source( imageArray );
  25384. } else {
  25385. // load single image
  25386. const deserializedImage = deserializeImage( image.url );
  25387. images[ image.uuid ] = new Source( deserializedImage );
  25388. }
  25389. }
  25390. }
  25391. return images;
  25392. }
  25393. async parseImagesAsync( json ) {
  25394. const scope = this;
  25395. const images = {};
  25396. let loader;
  25397. async function deserializeImage( image ) {
  25398. if ( typeof image === 'string' ) {
  25399. const url = image;
  25400. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25401. return await loader.loadAsync( path );
  25402. } else {
  25403. if ( image.data ) {
  25404. return {
  25405. data: getTypedArray( image.type, image.data ),
  25406. width: image.width,
  25407. height: image.height
  25408. };
  25409. } else {
  25410. return null;
  25411. }
  25412. }
  25413. }
  25414. if ( json !== undefined && json.length > 0 ) {
  25415. loader = new ImageLoader( this.manager );
  25416. loader.setCrossOrigin( this.crossOrigin );
  25417. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25418. const image = json[ i ];
  25419. const url = image.url;
  25420. if ( Array.isArray( url ) ) {
  25421. // load array of images e.g CubeTexture
  25422. const imageArray = [];
  25423. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25424. const currentUrl = url[ j ];
  25425. const deserializedImage = await deserializeImage( currentUrl );
  25426. if ( deserializedImage !== null ) {
  25427. if ( deserializedImage instanceof HTMLImageElement ) {
  25428. imageArray.push( deserializedImage );
  25429. } else {
  25430. // special case: handle array of data textures for cube textures
  25431. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25432. }
  25433. }
  25434. }
  25435. images[ image.uuid ] = new Source( imageArray );
  25436. } else {
  25437. // load single image
  25438. const deserializedImage = await deserializeImage( image.url );
  25439. images[ image.uuid ] = new Source( deserializedImage );
  25440. }
  25441. }
  25442. }
  25443. return images;
  25444. }
  25445. parseTextures( json, images ) {
  25446. function parseConstant( value, type ) {
  25447. if ( typeof value === 'number' ) return value;
  25448. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25449. return type[ value ];
  25450. }
  25451. const textures = {};
  25452. if ( json !== undefined ) {
  25453. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25454. const data = json[ i ];
  25455. if ( data.image === undefined ) {
  25456. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25457. }
  25458. if ( images[ data.image ] === undefined ) {
  25459. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25460. }
  25461. const source = images[ data.image ];
  25462. const image = source.data;
  25463. let texture;
  25464. if ( Array.isArray( image ) ) {
  25465. texture = new CubeTexture();
  25466. if ( image.length === 6 ) texture.needsUpdate = true;
  25467. } else {
  25468. if ( image && image.data ) {
  25469. texture = new DataTexture();
  25470. } else {
  25471. texture = new Texture();
  25472. }
  25473. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25474. }
  25475. texture.source = source;
  25476. texture.uuid = data.uuid;
  25477. if ( data.name !== undefined ) texture.name = data.name;
  25478. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25479. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25480. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25481. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25482. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25483. if ( data.wrap !== undefined ) {
  25484. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25485. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25486. }
  25487. if ( data.format !== undefined ) texture.format = data.format;
  25488. if ( data.type !== undefined ) texture.type = data.type;
  25489. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25490. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25491. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25492. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25493. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25494. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25495. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25496. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25497. if ( data.userData !== undefined ) texture.userData = data.userData;
  25498. textures[ data.uuid ] = texture;
  25499. }
  25500. }
  25501. return textures;
  25502. }
  25503. parseObject( data, geometries, materials, textures, animations ) {
  25504. let object;
  25505. function getGeometry( name ) {
  25506. if ( geometries[ name ] === undefined ) {
  25507. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25508. }
  25509. return geometries[ name ];
  25510. }
  25511. function getMaterial( name ) {
  25512. if ( name === undefined ) return undefined;
  25513. if ( Array.isArray( name ) ) {
  25514. const array = [];
  25515. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25516. const uuid = name[ i ];
  25517. if ( materials[ uuid ] === undefined ) {
  25518. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25519. }
  25520. array.push( materials[ uuid ] );
  25521. }
  25522. return array;
  25523. }
  25524. if ( materials[ name ] === undefined ) {
  25525. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25526. }
  25527. return materials[ name ];
  25528. }
  25529. function getTexture( uuid ) {
  25530. if ( textures[ uuid ] === undefined ) {
  25531. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25532. }
  25533. return textures[ uuid ];
  25534. }
  25535. let geometry, material;
  25536. switch ( data.type ) {
  25537. case 'Scene':
  25538. object = new Scene();
  25539. if ( data.background !== undefined ) {
  25540. if ( Number.isInteger( data.background ) ) {
  25541. object.background = new Color( data.background );
  25542. } else {
  25543. object.background = getTexture( data.background );
  25544. }
  25545. }
  25546. if ( data.environment !== undefined ) {
  25547. object.environment = getTexture( data.environment );
  25548. }
  25549. if ( data.fog !== undefined ) {
  25550. if ( data.fog.type === 'Fog' ) {
  25551. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25552. } else if ( data.fog.type === 'FogExp2' ) {
  25553. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25554. }
  25555. }
  25556. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25557. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25558. break;
  25559. case 'PerspectiveCamera':
  25560. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25561. if ( data.focus !== undefined ) object.focus = data.focus;
  25562. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25563. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25564. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25565. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25566. break;
  25567. case 'OrthographicCamera':
  25568. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25569. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25570. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25571. break;
  25572. case 'AmbientLight':
  25573. object = new AmbientLight( data.color, data.intensity );
  25574. break;
  25575. case 'DirectionalLight':
  25576. object = new DirectionalLight( data.color, data.intensity );
  25577. break;
  25578. case 'PointLight':
  25579. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25580. break;
  25581. case 'RectAreaLight':
  25582. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25583. break;
  25584. case 'SpotLight':
  25585. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25586. break;
  25587. case 'HemisphereLight':
  25588. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25589. break;
  25590. case 'LightProbe':
  25591. object = new LightProbe().fromJSON( data );
  25592. break;
  25593. case 'SkinnedMesh':
  25594. geometry = getGeometry( data.geometry );
  25595. material = getMaterial( data.material );
  25596. object = new SkinnedMesh( geometry, material );
  25597. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25598. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25599. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25600. break;
  25601. case 'Mesh':
  25602. geometry = getGeometry( data.geometry );
  25603. material = getMaterial( data.material );
  25604. object = new Mesh( geometry, material );
  25605. break;
  25606. case 'InstancedMesh':
  25607. geometry = getGeometry( data.geometry );
  25608. material = getMaterial( data.material );
  25609. const count = data.count;
  25610. const instanceMatrix = data.instanceMatrix;
  25611. const instanceColor = data.instanceColor;
  25612. object = new InstancedMesh( geometry, material, count );
  25613. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25614. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25615. break;
  25616. case 'LOD':
  25617. object = new LOD();
  25618. break;
  25619. case 'Line':
  25620. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25621. break;
  25622. case 'LineLoop':
  25623. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25624. break;
  25625. case 'LineSegments':
  25626. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25627. break;
  25628. case 'PointCloud':
  25629. case 'Points':
  25630. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25631. break;
  25632. case 'Sprite':
  25633. object = new Sprite( getMaterial( data.material ) );
  25634. break;
  25635. case 'Group':
  25636. object = new Group();
  25637. break;
  25638. case 'Bone':
  25639. object = new Bone();
  25640. break;
  25641. default:
  25642. object = new Object3D();
  25643. }
  25644. object.uuid = data.uuid;
  25645. if ( data.name !== undefined ) object.name = data.name;
  25646. if ( data.matrix !== undefined ) {
  25647. object.matrix.fromArray( data.matrix );
  25648. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25649. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25650. } else {
  25651. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25652. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25653. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25654. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25655. }
  25656. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25657. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25658. if ( data.shadow ) {
  25659. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25660. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25661. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25662. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25663. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25664. }
  25665. if ( data.visible !== undefined ) object.visible = data.visible;
  25666. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25667. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25668. if ( data.userData !== undefined ) object.userData = data.userData;
  25669. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25670. if ( data.children !== undefined ) {
  25671. const children = data.children;
  25672. for ( let i = 0; i < children.length; i ++ ) {
  25673. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25674. }
  25675. }
  25676. if ( data.animations !== undefined ) {
  25677. const objectAnimations = data.animations;
  25678. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25679. const uuid = objectAnimations[ i ];
  25680. object.animations.push( animations[ uuid ] );
  25681. }
  25682. }
  25683. if ( data.type === 'LOD' ) {
  25684. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25685. const levels = data.levels;
  25686. for ( let l = 0; l < levels.length; l ++ ) {
  25687. const level = levels[ l ];
  25688. const child = object.getObjectByProperty( 'uuid', level.object );
  25689. if ( child !== undefined ) {
  25690. object.addLevel( child, level.distance, level.hysteresis );
  25691. }
  25692. }
  25693. }
  25694. return object;
  25695. }
  25696. bindSkeletons( object, skeletons ) {
  25697. if ( Object.keys( skeletons ).length === 0 ) return;
  25698. object.traverse( function ( child ) {
  25699. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25700. const skeleton = skeletons[ child.skeleton ];
  25701. if ( skeleton === undefined ) {
  25702. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25703. } else {
  25704. child.bind( skeleton, child.bindMatrix );
  25705. }
  25706. }
  25707. } );
  25708. }
  25709. }
  25710. const TEXTURE_MAPPING = {
  25711. UVMapping: UVMapping,
  25712. CubeReflectionMapping: CubeReflectionMapping,
  25713. CubeRefractionMapping: CubeRefractionMapping,
  25714. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25715. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25716. CubeUVReflectionMapping: CubeUVReflectionMapping
  25717. };
  25718. const TEXTURE_WRAPPING = {
  25719. RepeatWrapping: RepeatWrapping,
  25720. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25721. MirroredRepeatWrapping: MirroredRepeatWrapping
  25722. };
  25723. const TEXTURE_FILTER = {
  25724. NearestFilter: NearestFilter,
  25725. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25726. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25727. LinearFilter: LinearFilter,
  25728. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25729. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25730. };
  25731. class ImageBitmapLoader extends Loader {
  25732. constructor( manager ) {
  25733. super( manager );
  25734. this.isImageBitmapLoader = true;
  25735. if ( typeof createImageBitmap === 'undefined' ) {
  25736. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25737. }
  25738. if ( typeof fetch === 'undefined' ) {
  25739. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25740. }
  25741. this.options = { premultiplyAlpha: 'none' };
  25742. }
  25743. setOptions( options ) {
  25744. this.options = options;
  25745. return this;
  25746. }
  25747. load( url, onLoad, onProgress, onError ) {
  25748. if ( url === undefined ) url = '';
  25749. if ( this.path !== undefined ) url = this.path + url;
  25750. url = this.manager.resolveURL( url );
  25751. const scope = this;
  25752. const cached = Cache.get( url );
  25753. if ( cached !== undefined ) {
  25754. scope.manager.itemStart( url );
  25755. setTimeout( function () {
  25756. if ( onLoad ) onLoad( cached );
  25757. scope.manager.itemEnd( url );
  25758. }, 0 );
  25759. return cached;
  25760. }
  25761. const fetchOptions = {};
  25762. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25763. fetchOptions.headers = this.requestHeader;
  25764. fetch( url, fetchOptions ).then( function ( res ) {
  25765. return res.blob();
  25766. } ).then( function ( blob ) {
  25767. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25768. } ).then( function ( imageBitmap ) {
  25769. Cache.add( url, imageBitmap );
  25770. if ( onLoad ) onLoad( imageBitmap );
  25771. scope.manager.itemEnd( url );
  25772. } ).catch( function ( e ) {
  25773. if ( onError ) onError( e );
  25774. scope.manager.itemError( url );
  25775. scope.manager.itemEnd( url );
  25776. } );
  25777. scope.manager.itemStart( url );
  25778. }
  25779. }
  25780. let _context;
  25781. class AudioContext {
  25782. static getContext() {
  25783. if ( _context === undefined ) {
  25784. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25785. }
  25786. return _context;
  25787. }
  25788. static setContext( value ) {
  25789. _context = value;
  25790. }
  25791. }
  25792. class AudioLoader extends Loader {
  25793. constructor( manager ) {
  25794. super( manager );
  25795. }
  25796. load( url, onLoad, onProgress, onError ) {
  25797. const scope = this;
  25798. const loader = new FileLoader( this.manager );
  25799. loader.setResponseType( 'arraybuffer' );
  25800. loader.setPath( this.path );
  25801. loader.setRequestHeader( this.requestHeader );
  25802. loader.setWithCredentials( this.withCredentials );
  25803. loader.load( url, function ( buffer ) {
  25804. try {
  25805. // Create a copy of the buffer. The `decodeAudioData` method
  25806. // detaches the buffer when complete, preventing reuse.
  25807. const bufferCopy = buffer.slice( 0 );
  25808. const context = AudioContext.getContext();
  25809. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25810. onLoad( audioBuffer );
  25811. } );
  25812. } catch ( e ) {
  25813. if ( onError ) {
  25814. onError( e );
  25815. } else {
  25816. console.error( e );
  25817. }
  25818. scope.manager.itemError( url );
  25819. }
  25820. }, onProgress, onError );
  25821. }
  25822. }
  25823. class HemisphereLightProbe extends LightProbe {
  25824. constructor( skyColor, groundColor, intensity = 1 ) {
  25825. super( undefined, intensity );
  25826. this.isHemisphereLightProbe = true;
  25827. const color1 = new Color().set( skyColor );
  25828. const color2 = new Color().set( groundColor );
  25829. const sky = new Vector3( color1.r, color1.g, color1.b );
  25830. const ground = new Vector3( color2.r, color2.g, color2.b );
  25831. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25832. const c0 = Math.sqrt( Math.PI );
  25833. const c1 = c0 * Math.sqrt( 0.75 );
  25834. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25835. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25836. }
  25837. }
  25838. class AmbientLightProbe extends LightProbe {
  25839. constructor( color, intensity = 1 ) {
  25840. super( undefined, intensity );
  25841. this.isAmbientLightProbe = true;
  25842. const color1 = new Color().set( color );
  25843. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25844. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25845. }
  25846. }
  25847. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25848. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25849. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25850. class StereoCamera {
  25851. constructor() {
  25852. this.type = 'StereoCamera';
  25853. this.aspect = 1;
  25854. this.eyeSep = 0.064;
  25855. this.cameraL = new PerspectiveCamera();
  25856. this.cameraL.layers.enable( 1 );
  25857. this.cameraL.matrixAutoUpdate = false;
  25858. this.cameraR = new PerspectiveCamera();
  25859. this.cameraR.layers.enable( 2 );
  25860. this.cameraR.matrixAutoUpdate = false;
  25861. this._cache = {
  25862. focus: null,
  25863. fov: null,
  25864. aspect: null,
  25865. near: null,
  25866. far: null,
  25867. zoom: null,
  25868. eyeSep: null
  25869. };
  25870. }
  25871. update( camera ) {
  25872. const cache = this._cache;
  25873. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25874. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25875. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25876. if ( needsUpdate ) {
  25877. cache.focus = camera.focus;
  25878. cache.fov = camera.fov;
  25879. cache.aspect = camera.aspect * this.aspect;
  25880. cache.near = camera.near;
  25881. cache.far = camera.far;
  25882. cache.zoom = camera.zoom;
  25883. cache.eyeSep = this.eyeSep;
  25884. // Off-axis stereoscopic effect based on
  25885. // http://paulbourke.net/stereographics/stereorender/
  25886. _projectionMatrix.copy( camera.projectionMatrix );
  25887. const eyeSepHalf = cache.eyeSep / 2;
  25888. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25889. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25890. let xmin, xmax;
  25891. // translate xOffset
  25892. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25893. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25894. // for left eye
  25895. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25896. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25897. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25898. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25899. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25900. // for right eye
  25901. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25902. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25903. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25904. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25905. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25906. }
  25907. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25908. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25909. }
  25910. }
  25911. class Clock {
  25912. constructor( autoStart = true ) {
  25913. this.autoStart = autoStart;
  25914. this.startTime = 0;
  25915. this.oldTime = 0;
  25916. this.elapsedTime = 0;
  25917. this.running = false;
  25918. }
  25919. start() {
  25920. this.startTime = now();
  25921. this.oldTime = this.startTime;
  25922. this.elapsedTime = 0;
  25923. this.running = true;
  25924. }
  25925. stop() {
  25926. this.getElapsedTime();
  25927. this.running = false;
  25928. this.autoStart = false;
  25929. }
  25930. getElapsedTime() {
  25931. this.getDelta();
  25932. return this.elapsedTime;
  25933. }
  25934. getDelta() {
  25935. let diff = 0;
  25936. if ( this.autoStart && ! this.running ) {
  25937. this.start();
  25938. return 0;
  25939. }
  25940. if ( this.running ) {
  25941. const newTime = now();
  25942. diff = ( newTime - this.oldTime ) / 1000;
  25943. this.oldTime = newTime;
  25944. this.elapsedTime += diff;
  25945. }
  25946. return diff;
  25947. }
  25948. }
  25949. function now() {
  25950. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25951. }
  25952. const _position$1 = /*@__PURE__*/ new Vector3();
  25953. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25954. const _scale$1 = /*@__PURE__*/ new Vector3();
  25955. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25956. class AudioListener extends Object3D {
  25957. constructor() {
  25958. super();
  25959. this.type = 'AudioListener';
  25960. this.context = AudioContext.getContext();
  25961. this.gain = this.context.createGain();
  25962. this.gain.connect( this.context.destination );
  25963. this.filter = null;
  25964. this.timeDelta = 0;
  25965. // private
  25966. this._clock = new Clock();
  25967. }
  25968. getInput() {
  25969. return this.gain;
  25970. }
  25971. removeFilter() {
  25972. if ( this.filter !== null ) {
  25973. this.gain.disconnect( this.filter );
  25974. this.filter.disconnect( this.context.destination );
  25975. this.gain.connect( this.context.destination );
  25976. this.filter = null;
  25977. }
  25978. return this;
  25979. }
  25980. getFilter() {
  25981. return this.filter;
  25982. }
  25983. setFilter( value ) {
  25984. if ( this.filter !== null ) {
  25985. this.gain.disconnect( this.filter );
  25986. this.filter.disconnect( this.context.destination );
  25987. } else {
  25988. this.gain.disconnect( this.context.destination );
  25989. }
  25990. this.filter = value;
  25991. this.gain.connect( this.filter );
  25992. this.filter.connect( this.context.destination );
  25993. return this;
  25994. }
  25995. getMasterVolume() {
  25996. return this.gain.gain.value;
  25997. }
  25998. setMasterVolume( value ) {
  25999. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26000. return this;
  26001. }
  26002. updateMatrixWorld( force ) {
  26003. super.updateMatrixWorld( force );
  26004. const listener = this.context.listener;
  26005. const up = this.up;
  26006. this.timeDelta = this._clock.getDelta();
  26007. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26008. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26009. if ( listener.positionX ) {
  26010. // code path for Chrome (see #14393)
  26011. const endTime = this.context.currentTime + this.timeDelta;
  26012. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26013. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26014. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26015. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26016. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26017. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26018. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26019. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26020. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26021. } else {
  26022. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26023. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26024. }
  26025. }
  26026. }
  26027. class Audio extends Object3D {
  26028. constructor( listener ) {
  26029. super();
  26030. this.type = 'Audio';
  26031. this.listener = listener;
  26032. this.context = listener.context;
  26033. this.gain = this.context.createGain();
  26034. this.gain.connect( listener.getInput() );
  26035. this.autoplay = false;
  26036. this.buffer = null;
  26037. this.detune = 0;
  26038. this.loop = false;
  26039. this.loopStart = 0;
  26040. this.loopEnd = 0;
  26041. this.offset = 0;
  26042. this.duration = undefined;
  26043. this.playbackRate = 1;
  26044. this.isPlaying = false;
  26045. this.hasPlaybackControl = true;
  26046. this.source = null;
  26047. this.sourceType = 'empty';
  26048. this._startedAt = 0;
  26049. this._progress = 0;
  26050. this._connected = false;
  26051. this.filters = [];
  26052. }
  26053. getOutput() {
  26054. return this.gain;
  26055. }
  26056. setNodeSource( audioNode ) {
  26057. this.hasPlaybackControl = false;
  26058. this.sourceType = 'audioNode';
  26059. this.source = audioNode;
  26060. this.connect();
  26061. return this;
  26062. }
  26063. setMediaElementSource( mediaElement ) {
  26064. this.hasPlaybackControl = false;
  26065. this.sourceType = 'mediaNode';
  26066. this.source = this.context.createMediaElementSource( mediaElement );
  26067. this.connect();
  26068. return this;
  26069. }
  26070. setMediaStreamSource( mediaStream ) {
  26071. this.hasPlaybackControl = false;
  26072. this.sourceType = 'mediaStreamNode';
  26073. this.source = this.context.createMediaStreamSource( mediaStream );
  26074. this.connect();
  26075. return this;
  26076. }
  26077. setBuffer( audioBuffer ) {
  26078. this.buffer = audioBuffer;
  26079. this.sourceType = 'buffer';
  26080. if ( this.autoplay ) this.play();
  26081. return this;
  26082. }
  26083. play( delay = 0 ) {
  26084. if ( this.isPlaying === true ) {
  26085. console.warn( 'THREE.Audio: Audio is already playing.' );
  26086. return;
  26087. }
  26088. if ( this.hasPlaybackControl === false ) {
  26089. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26090. return;
  26091. }
  26092. this._startedAt = this.context.currentTime + delay;
  26093. const source = this.context.createBufferSource();
  26094. source.buffer = this.buffer;
  26095. source.loop = this.loop;
  26096. source.loopStart = this.loopStart;
  26097. source.loopEnd = this.loopEnd;
  26098. source.onended = this.onEnded.bind( this );
  26099. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26100. this.isPlaying = true;
  26101. this.source = source;
  26102. this.setDetune( this.detune );
  26103. this.setPlaybackRate( this.playbackRate );
  26104. return this.connect();
  26105. }
  26106. pause() {
  26107. if ( this.hasPlaybackControl === false ) {
  26108. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26109. return;
  26110. }
  26111. if ( this.isPlaying === true ) {
  26112. // update current progress
  26113. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26114. if ( this.loop === true ) {
  26115. // ensure _progress does not exceed duration with looped audios
  26116. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26117. }
  26118. this.source.stop();
  26119. this.source.onended = null;
  26120. this.isPlaying = false;
  26121. }
  26122. return this;
  26123. }
  26124. stop() {
  26125. if ( this.hasPlaybackControl === false ) {
  26126. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26127. return;
  26128. }
  26129. this._progress = 0;
  26130. if ( this.source !== null ) {
  26131. this.source.stop();
  26132. this.source.onended = null;
  26133. }
  26134. this.isPlaying = false;
  26135. return this;
  26136. }
  26137. connect() {
  26138. if ( this.filters.length > 0 ) {
  26139. this.source.connect( this.filters[ 0 ] );
  26140. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26141. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26142. }
  26143. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26144. } else {
  26145. this.source.connect( this.getOutput() );
  26146. }
  26147. this._connected = true;
  26148. return this;
  26149. }
  26150. disconnect() {
  26151. if ( this.filters.length > 0 ) {
  26152. this.source.disconnect( this.filters[ 0 ] );
  26153. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26154. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26155. }
  26156. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26157. } else {
  26158. this.source.disconnect( this.getOutput() );
  26159. }
  26160. this._connected = false;
  26161. return this;
  26162. }
  26163. getFilters() {
  26164. return this.filters;
  26165. }
  26166. setFilters( value ) {
  26167. if ( ! value ) value = [];
  26168. if ( this._connected === true ) {
  26169. this.disconnect();
  26170. this.filters = value.slice();
  26171. this.connect();
  26172. } else {
  26173. this.filters = value.slice();
  26174. }
  26175. return this;
  26176. }
  26177. setDetune( value ) {
  26178. this.detune = value;
  26179. if ( this.source.detune === undefined ) return; // only set detune when available
  26180. if ( this.isPlaying === true ) {
  26181. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26182. }
  26183. return this;
  26184. }
  26185. getDetune() {
  26186. return this.detune;
  26187. }
  26188. getFilter() {
  26189. return this.getFilters()[ 0 ];
  26190. }
  26191. setFilter( filter ) {
  26192. return this.setFilters( filter ? [ filter ] : [] );
  26193. }
  26194. setPlaybackRate( value ) {
  26195. if ( this.hasPlaybackControl === false ) {
  26196. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26197. return;
  26198. }
  26199. this.playbackRate = value;
  26200. if ( this.isPlaying === true ) {
  26201. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26202. }
  26203. return this;
  26204. }
  26205. getPlaybackRate() {
  26206. return this.playbackRate;
  26207. }
  26208. onEnded() {
  26209. this.isPlaying = false;
  26210. }
  26211. getLoop() {
  26212. if ( this.hasPlaybackControl === false ) {
  26213. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26214. return false;
  26215. }
  26216. return this.loop;
  26217. }
  26218. setLoop( value ) {
  26219. if ( this.hasPlaybackControl === false ) {
  26220. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26221. return;
  26222. }
  26223. this.loop = value;
  26224. if ( this.isPlaying === true ) {
  26225. this.source.loop = this.loop;
  26226. }
  26227. return this;
  26228. }
  26229. setLoopStart( value ) {
  26230. this.loopStart = value;
  26231. return this;
  26232. }
  26233. setLoopEnd( value ) {
  26234. this.loopEnd = value;
  26235. return this;
  26236. }
  26237. getVolume() {
  26238. return this.gain.gain.value;
  26239. }
  26240. setVolume( value ) {
  26241. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26242. return this;
  26243. }
  26244. }
  26245. const _position = /*@__PURE__*/ new Vector3();
  26246. const _quaternion = /*@__PURE__*/ new Quaternion();
  26247. const _scale = /*@__PURE__*/ new Vector3();
  26248. const _orientation = /*@__PURE__*/ new Vector3();
  26249. class PositionalAudio extends Audio {
  26250. constructor( listener ) {
  26251. super( listener );
  26252. this.panner = this.context.createPanner();
  26253. this.panner.panningModel = 'HRTF';
  26254. this.panner.connect( this.gain );
  26255. }
  26256. disconnect() {
  26257. super.disconnect();
  26258. this.panner.disconnect( this.gain );
  26259. }
  26260. getOutput() {
  26261. return this.panner;
  26262. }
  26263. getRefDistance() {
  26264. return this.panner.refDistance;
  26265. }
  26266. setRefDistance( value ) {
  26267. this.panner.refDistance = value;
  26268. return this;
  26269. }
  26270. getRolloffFactor() {
  26271. return this.panner.rolloffFactor;
  26272. }
  26273. setRolloffFactor( value ) {
  26274. this.panner.rolloffFactor = value;
  26275. return this;
  26276. }
  26277. getDistanceModel() {
  26278. return this.panner.distanceModel;
  26279. }
  26280. setDistanceModel( value ) {
  26281. this.panner.distanceModel = value;
  26282. return this;
  26283. }
  26284. getMaxDistance() {
  26285. return this.panner.maxDistance;
  26286. }
  26287. setMaxDistance( value ) {
  26288. this.panner.maxDistance = value;
  26289. return this;
  26290. }
  26291. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26292. this.panner.coneInnerAngle = coneInnerAngle;
  26293. this.panner.coneOuterAngle = coneOuterAngle;
  26294. this.panner.coneOuterGain = coneOuterGain;
  26295. return this;
  26296. }
  26297. updateMatrixWorld( force ) {
  26298. super.updateMatrixWorld( force );
  26299. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26300. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26301. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26302. const panner = this.panner;
  26303. if ( panner.positionX ) {
  26304. // code path for Chrome and Firefox (see #14393)
  26305. const endTime = this.context.currentTime + this.listener.timeDelta;
  26306. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26307. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26308. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26309. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26310. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26311. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26312. } else {
  26313. panner.setPosition( _position.x, _position.y, _position.z );
  26314. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26315. }
  26316. }
  26317. }
  26318. class AudioAnalyser {
  26319. constructor( audio, fftSize = 2048 ) {
  26320. this.analyser = audio.context.createAnalyser();
  26321. this.analyser.fftSize = fftSize;
  26322. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26323. audio.getOutput().connect( this.analyser );
  26324. }
  26325. getFrequencyData() {
  26326. this.analyser.getByteFrequencyData( this.data );
  26327. return this.data;
  26328. }
  26329. getAverageFrequency() {
  26330. let value = 0;
  26331. const data = this.getFrequencyData();
  26332. for ( let i = 0; i < data.length; i ++ ) {
  26333. value += data[ i ];
  26334. }
  26335. return value / data.length;
  26336. }
  26337. }
  26338. class PropertyMixer {
  26339. constructor( binding, typeName, valueSize ) {
  26340. this.binding = binding;
  26341. this.valueSize = valueSize;
  26342. let mixFunction,
  26343. mixFunctionAdditive,
  26344. setIdentity;
  26345. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26346. //
  26347. // interpolators can use .buffer as their .result
  26348. // the data then goes to 'incoming'
  26349. //
  26350. // 'accu0' and 'accu1' are used frame-interleaved for
  26351. // the cumulative result and are compared to detect
  26352. // changes
  26353. //
  26354. // 'orig' stores the original state of the property
  26355. //
  26356. // 'add' is used for additive cumulative results
  26357. //
  26358. // 'work' is optional and is only present for quaternion types. It is used
  26359. // to store intermediate quaternion multiplication results
  26360. switch ( typeName ) {
  26361. case 'quaternion':
  26362. mixFunction = this._slerp;
  26363. mixFunctionAdditive = this._slerpAdditive;
  26364. setIdentity = this._setAdditiveIdentityQuaternion;
  26365. this.buffer = new Float64Array( valueSize * 6 );
  26366. this._workIndex = 5;
  26367. break;
  26368. case 'string':
  26369. case 'bool':
  26370. mixFunction = this._select;
  26371. // Use the regular mix function and for additive on these types,
  26372. // additive is not relevant for non-numeric types
  26373. mixFunctionAdditive = this._select;
  26374. setIdentity = this._setAdditiveIdentityOther;
  26375. this.buffer = new Array( valueSize * 5 );
  26376. break;
  26377. default:
  26378. mixFunction = this._lerp;
  26379. mixFunctionAdditive = this._lerpAdditive;
  26380. setIdentity = this._setAdditiveIdentityNumeric;
  26381. this.buffer = new Float64Array( valueSize * 5 );
  26382. }
  26383. this._mixBufferRegion = mixFunction;
  26384. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26385. this._setIdentity = setIdentity;
  26386. this._origIndex = 3;
  26387. this._addIndex = 4;
  26388. this.cumulativeWeight = 0;
  26389. this.cumulativeWeightAdditive = 0;
  26390. this.useCount = 0;
  26391. this.referenceCount = 0;
  26392. }
  26393. // accumulate data in the 'incoming' region into 'accu<i>'
  26394. accumulate( accuIndex, weight ) {
  26395. // note: happily accumulating nothing when weight = 0, the caller knows
  26396. // the weight and shouldn't have made the call in the first place
  26397. const buffer = this.buffer,
  26398. stride = this.valueSize,
  26399. offset = accuIndex * stride + stride;
  26400. let currentWeight = this.cumulativeWeight;
  26401. if ( currentWeight === 0 ) {
  26402. // accuN := incoming * weight
  26403. for ( let i = 0; i !== stride; ++ i ) {
  26404. buffer[ offset + i ] = buffer[ i ];
  26405. }
  26406. currentWeight = weight;
  26407. } else {
  26408. // accuN := accuN + incoming * weight
  26409. currentWeight += weight;
  26410. const mix = weight / currentWeight;
  26411. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26412. }
  26413. this.cumulativeWeight = currentWeight;
  26414. }
  26415. // accumulate data in the 'incoming' region into 'add'
  26416. accumulateAdditive( weight ) {
  26417. const buffer = this.buffer,
  26418. stride = this.valueSize,
  26419. offset = stride * this._addIndex;
  26420. if ( this.cumulativeWeightAdditive === 0 ) {
  26421. // add = identity
  26422. this._setIdentity();
  26423. }
  26424. // add := add + incoming * weight
  26425. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26426. this.cumulativeWeightAdditive += weight;
  26427. }
  26428. // apply the state of 'accu<i>' to the binding when accus differ
  26429. apply( accuIndex ) {
  26430. const stride = this.valueSize,
  26431. buffer = this.buffer,
  26432. offset = accuIndex * stride + stride,
  26433. weight = this.cumulativeWeight,
  26434. weightAdditive = this.cumulativeWeightAdditive,
  26435. binding = this.binding;
  26436. this.cumulativeWeight = 0;
  26437. this.cumulativeWeightAdditive = 0;
  26438. if ( weight < 1 ) {
  26439. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26440. const originalValueOffset = stride * this._origIndex;
  26441. this._mixBufferRegion(
  26442. buffer, offset, originalValueOffset, 1 - weight, stride );
  26443. }
  26444. if ( weightAdditive > 0 ) {
  26445. // accuN := accuN + additive accuN
  26446. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26447. }
  26448. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26449. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26450. // value has changed -> update scene graph
  26451. binding.setValue( buffer, offset );
  26452. break;
  26453. }
  26454. }
  26455. }
  26456. // remember the state of the bound property and copy it to both accus
  26457. saveOriginalState() {
  26458. const binding = this.binding;
  26459. const buffer = this.buffer,
  26460. stride = this.valueSize,
  26461. originalValueOffset = stride * this._origIndex;
  26462. binding.getValue( buffer, originalValueOffset );
  26463. // accu[0..1] := orig -- initially detect changes against the original
  26464. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26465. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26466. }
  26467. // Add to identity for additive
  26468. this._setIdentity();
  26469. this.cumulativeWeight = 0;
  26470. this.cumulativeWeightAdditive = 0;
  26471. }
  26472. // apply the state previously taken via 'saveOriginalState' to the binding
  26473. restoreOriginalState() {
  26474. const originalValueOffset = this.valueSize * 3;
  26475. this.binding.setValue( this.buffer, originalValueOffset );
  26476. }
  26477. _setAdditiveIdentityNumeric() {
  26478. const startIndex = this._addIndex * this.valueSize;
  26479. const endIndex = startIndex + this.valueSize;
  26480. for ( let i = startIndex; i < endIndex; i ++ ) {
  26481. this.buffer[ i ] = 0;
  26482. }
  26483. }
  26484. _setAdditiveIdentityQuaternion() {
  26485. this._setAdditiveIdentityNumeric();
  26486. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26487. }
  26488. _setAdditiveIdentityOther() {
  26489. const startIndex = this._origIndex * this.valueSize;
  26490. const targetIndex = this._addIndex * this.valueSize;
  26491. for ( let i = 0; i < this.valueSize; i ++ ) {
  26492. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26493. }
  26494. }
  26495. // mix functions
  26496. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26497. if ( t >= 0.5 ) {
  26498. for ( let i = 0; i !== stride; ++ i ) {
  26499. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26500. }
  26501. }
  26502. }
  26503. _slerp( buffer, dstOffset, srcOffset, t ) {
  26504. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26505. }
  26506. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26507. const workOffset = this._workIndex * stride;
  26508. // Store result in intermediate buffer offset
  26509. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26510. // Slerp to the intermediate result
  26511. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26512. }
  26513. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26514. const s = 1 - t;
  26515. for ( let i = 0; i !== stride; ++ i ) {
  26516. const j = dstOffset + i;
  26517. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26518. }
  26519. }
  26520. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26521. for ( let i = 0; i !== stride; ++ i ) {
  26522. const j = dstOffset + i;
  26523. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26524. }
  26525. }
  26526. }
  26527. // Characters [].:/ are reserved for track binding syntax.
  26528. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26529. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26530. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26531. // only latin characters, and the unicode \p{L} is not yet supported. So
  26532. // instead, we exclude reserved characters and match everything else.
  26533. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26534. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26535. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26536. // be matched to parse the rest of the track name.
  26537. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26538. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26539. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26540. // Object on target node, and accessor. May not contain reserved
  26541. // characters. Accessor may contain any character except closing bracket.
  26542. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26543. // Property and accessor. May not contain reserved characters. Accessor may
  26544. // contain any non-bracket characters.
  26545. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26546. const _trackRe = new RegExp( ''
  26547. + '^'
  26548. + _directoryRe
  26549. + _nodeRe
  26550. + _objectRe
  26551. + _propertyRe
  26552. + '$'
  26553. );
  26554. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26555. class Composite {
  26556. constructor( targetGroup, path, optionalParsedPath ) {
  26557. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26558. this._targetGroup = targetGroup;
  26559. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26560. }
  26561. getValue( array, offset ) {
  26562. this.bind(); // bind all binding
  26563. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26564. binding = this._bindings[ firstValidIndex ];
  26565. // and only call .getValue on the first
  26566. if ( binding !== undefined ) binding.getValue( array, offset );
  26567. }
  26568. setValue( array, offset ) {
  26569. const bindings = this._bindings;
  26570. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26571. bindings[ i ].setValue( array, offset );
  26572. }
  26573. }
  26574. bind() {
  26575. const bindings = this._bindings;
  26576. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26577. bindings[ i ].bind();
  26578. }
  26579. }
  26580. unbind() {
  26581. const bindings = this._bindings;
  26582. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26583. bindings[ i ].unbind();
  26584. }
  26585. }
  26586. }
  26587. // Note: This class uses a State pattern on a per-method basis:
  26588. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26589. // prototype version of these methods with one that represents
  26590. // the bound state. When the property is not found, the methods
  26591. // become no-ops.
  26592. class PropertyBinding {
  26593. constructor( rootNode, path, parsedPath ) {
  26594. this.path = path;
  26595. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26596. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  26597. this.rootNode = rootNode;
  26598. // initial state of these methods that calls 'bind'
  26599. this.getValue = this._getValue_unbound;
  26600. this.setValue = this._setValue_unbound;
  26601. }
  26602. static create( root, path, parsedPath ) {
  26603. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26604. return new PropertyBinding( root, path, parsedPath );
  26605. } else {
  26606. return new PropertyBinding.Composite( root, path, parsedPath );
  26607. }
  26608. }
  26609. /**
  26610. * Replaces spaces with underscores and removes unsupported characters from
  26611. * node names, to ensure compatibility with parseTrackName().
  26612. *
  26613. * @param {string} name Node name to be sanitized.
  26614. * @return {string}
  26615. */
  26616. static sanitizeNodeName( name ) {
  26617. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26618. }
  26619. static parseTrackName( trackName ) {
  26620. const matches = _trackRe.exec( trackName );
  26621. if ( matches === null ) {
  26622. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26623. }
  26624. const results = {
  26625. // directoryName: matches[ 1 ], // (tschw) currently unused
  26626. nodeName: matches[ 2 ],
  26627. objectName: matches[ 3 ],
  26628. objectIndex: matches[ 4 ],
  26629. propertyName: matches[ 5 ], // required
  26630. propertyIndex: matches[ 6 ]
  26631. };
  26632. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26633. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26634. const objectName = results.nodeName.substring( lastDot + 1 );
  26635. // Object names must be checked against an allowlist. Otherwise, there
  26636. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26637. // 'bar' could be the objectName, or part of a nodeName (which can
  26638. // include '.' characters).
  26639. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26640. results.nodeName = results.nodeName.substring( 0, lastDot );
  26641. results.objectName = objectName;
  26642. }
  26643. }
  26644. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26645. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26646. }
  26647. return results;
  26648. }
  26649. static findNode( root, nodeName ) {
  26650. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26651. return root;
  26652. }
  26653. // search into skeleton bones.
  26654. if ( root.skeleton ) {
  26655. const bone = root.skeleton.getBoneByName( nodeName );
  26656. if ( bone !== undefined ) {
  26657. return bone;
  26658. }
  26659. }
  26660. // search into node subtree.
  26661. if ( root.children ) {
  26662. const searchNodeSubtree = function ( children ) {
  26663. for ( let i = 0; i < children.length; i ++ ) {
  26664. const childNode = children[ i ];
  26665. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26666. return childNode;
  26667. }
  26668. const result = searchNodeSubtree( childNode.children );
  26669. if ( result ) return result;
  26670. }
  26671. return null;
  26672. };
  26673. const subTreeNode = searchNodeSubtree( root.children );
  26674. if ( subTreeNode ) {
  26675. return subTreeNode;
  26676. }
  26677. }
  26678. return null;
  26679. }
  26680. // these are used to "bind" a nonexistent property
  26681. _getValue_unavailable() {}
  26682. _setValue_unavailable() {}
  26683. // Getters
  26684. _getValue_direct( buffer, offset ) {
  26685. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26686. }
  26687. _getValue_array( buffer, offset ) {
  26688. const source = this.resolvedProperty;
  26689. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26690. buffer[ offset ++ ] = source[ i ];
  26691. }
  26692. }
  26693. _getValue_arrayElement( buffer, offset ) {
  26694. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26695. }
  26696. _getValue_toArray( buffer, offset ) {
  26697. this.resolvedProperty.toArray( buffer, offset );
  26698. }
  26699. // Direct
  26700. _setValue_direct( buffer, offset ) {
  26701. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26702. }
  26703. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26704. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26705. this.targetObject.needsUpdate = true;
  26706. }
  26707. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26708. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26709. this.targetObject.matrixWorldNeedsUpdate = true;
  26710. }
  26711. // EntireArray
  26712. _setValue_array( buffer, offset ) {
  26713. const dest = this.resolvedProperty;
  26714. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26715. dest[ i ] = buffer[ offset ++ ];
  26716. }
  26717. }
  26718. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26719. const dest = this.resolvedProperty;
  26720. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26721. dest[ i ] = buffer[ offset ++ ];
  26722. }
  26723. this.targetObject.needsUpdate = true;
  26724. }
  26725. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26726. const dest = this.resolvedProperty;
  26727. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26728. dest[ i ] = buffer[ offset ++ ];
  26729. }
  26730. this.targetObject.matrixWorldNeedsUpdate = true;
  26731. }
  26732. // ArrayElement
  26733. _setValue_arrayElement( buffer, offset ) {
  26734. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26735. }
  26736. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26737. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26738. this.targetObject.needsUpdate = true;
  26739. }
  26740. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26741. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26742. this.targetObject.matrixWorldNeedsUpdate = true;
  26743. }
  26744. // HasToFromArray
  26745. _setValue_fromArray( buffer, offset ) {
  26746. this.resolvedProperty.fromArray( buffer, offset );
  26747. }
  26748. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26749. this.resolvedProperty.fromArray( buffer, offset );
  26750. this.targetObject.needsUpdate = true;
  26751. }
  26752. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26753. this.resolvedProperty.fromArray( buffer, offset );
  26754. this.targetObject.matrixWorldNeedsUpdate = true;
  26755. }
  26756. _getValue_unbound( targetArray, offset ) {
  26757. this.bind();
  26758. this.getValue( targetArray, offset );
  26759. }
  26760. _setValue_unbound( sourceArray, offset ) {
  26761. this.bind();
  26762. this.setValue( sourceArray, offset );
  26763. }
  26764. // create getter / setter pair for a property in the scene graph
  26765. bind() {
  26766. let targetObject = this.node;
  26767. const parsedPath = this.parsedPath;
  26768. const objectName = parsedPath.objectName;
  26769. const propertyName = parsedPath.propertyName;
  26770. let propertyIndex = parsedPath.propertyIndex;
  26771. if ( ! targetObject ) {
  26772. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  26773. this.node = targetObject;
  26774. }
  26775. // set fail state so we can just 'return' on error
  26776. this.getValue = this._getValue_unavailable;
  26777. this.setValue = this._setValue_unavailable;
  26778. // ensure there is a value node
  26779. if ( ! targetObject ) {
  26780. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26781. return;
  26782. }
  26783. if ( objectName ) {
  26784. let objectIndex = parsedPath.objectIndex;
  26785. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26786. switch ( objectName ) {
  26787. case 'materials':
  26788. if ( ! targetObject.material ) {
  26789. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26790. return;
  26791. }
  26792. if ( ! targetObject.material.materials ) {
  26793. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26794. return;
  26795. }
  26796. targetObject = targetObject.material.materials;
  26797. break;
  26798. case 'bones':
  26799. if ( ! targetObject.skeleton ) {
  26800. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26801. return;
  26802. }
  26803. // potential future optimization: skip this if propertyIndex is already an integer
  26804. // and convert the integer string to a true integer.
  26805. targetObject = targetObject.skeleton.bones;
  26806. // support resolving morphTarget names into indices.
  26807. for ( let i = 0; i < targetObject.length; i ++ ) {
  26808. if ( targetObject[ i ].name === objectIndex ) {
  26809. objectIndex = i;
  26810. break;
  26811. }
  26812. }
  26813. break;
  26814. case 'map':
  26815. if ( 'map' in targetObject ) {
  26816. targetObject = targetObject.map;
  26817. break;
  26818. }
  26819. if ( ! targetObject.material ) {
  26820. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26821. return;
  26822. }
  26823. if ( ! targetObject.material.map ) {
  26824. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26825. return;
  26826. }
  26827. targetObject = targetObject.material.map;
  26828. break;
  26829. default:
  26830. if ( targetObject[ objectName ] === undefined ) {
  26831. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26832. return;
  26833. }
  26834. targetObject = targetObject[ objectName ];
  26835. }
  26836. if ( objectIndex !== undefined ) {
  26837. if ( targetObject[ objectIndex ] === undefined ) {
  26838. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26839. return;
  26840. }
  26841. targetObject = targetObject[ objectIndex ];
  26842. }
  26843. }
  26844. // resolve property
  26845. const nodeProperty = targetObject[ propertyName ];
  26846. if ( nodeProperty === undefined ) {
  26847. const nodeName = parsedPath.nodeName;
  26848. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26849. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26850. return;
  26851. }
  26852. // determine versioning scheme
  26853. let versioning = this.Versioning.None;
  26854. this.targetObject = targetObject;
  26855. if ( targetObject.needsUpdate !== undefined ) { // material
  26856. versioning = this.Versioning.NeedsUpdate;
  26857. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26858. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26859. }
  26860. // determine how the property gets bound
  26861. let bindingType = this.BindingType.Direct;
  26862. if ( propertyIndex !== undefined ) {
  26863. // access a sub element of the property array (only primitives are supported right now)
  26864. if ( propertyName === 'morphTargetInfluences' ) {
  26865. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26866. // support resolving morphTarget names into indices.
  26867. if ( ! targetObject.geometry ) {
  26868. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26869. return;
  26870. }
  26871. if ( ! targetObject.geometry.morphAttributes ) {
  26872. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26873. return;
  26874. }
  26875. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26876. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26877. }
  26878. }
  26879. bindingType = this.BindingType.ArrayElement;
  26880. this.resolvedProperty = nodeProperty;
  26881. this.propertyIndex = propertyIndex;
  26882. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26883. // must use copy for Object3D.Euler/Quaternion
  26884. bindingType = this.BindingType.HasFromToArray;
  26885. this.resolvedProperty = nodeProperty;
  26886. } else if ( Array.isArray( nodeProperty ) ) {
  26887. bindingType = this.BindingType.EntireArray;
  26888. this.resolvedProperty = nodeProperty;
  26889. } else {
  26890. this.propertyName = propertyName;
  26891. }
  26892. // select getter / setter
  26893. this.getValue = this.GetterByBindingType[ bindingType ];
  26894. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26895. }
  26896. unbind() {
  26897. this.node = null;
  26898. // back to the prototype version of getValue / setValue
  26899. // note: avoiding to mutate the shape of 'this' via 'delete'
  26900. this.getValue = this._getValue_unbound;
  26901. this.setValue = this._setValue_unbound;
  26902. }
  26903. }
  26904. PropertyBinding.Composite = Composite;
  26905. PropertyBinding.prototype.BindingType = {
  26906. Direct: 0,
  26907. EntireArray: 1,
  26908. ArrayElement: 2,
  26909. HasFromToArray: 3
  26910. };
  26911. PropertyBinding.prototype.Versioning = {
  26912. None: 0,
  26913. NeedsUpdate: 1,
  26914. MatrixWorldNeedsUpdate: 2
  26915. };
  26916. PropertyBinding.prototype.GetterByBindingType = [
  26917. PropertyBinding.prototype._getValue_direct,
  26918. PropertyBinding.prototype._getValue_array,
  26919. PropertyBinding.prototype._getValue_arrayElement,
  26920. PropertyBinding.prototype._getValue_toArray,
  26921. ];
  26922. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26923. [
  26924. // Direct
  26925. PropertyBinding.prototype._setValue_direct,
  26926. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26927. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26928. ], [
  26929. // EntireArray
  26930. PropertyBinding.prototype._setValue_array,
  26931. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26932. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26933. ], [
  26934. // ArrayElement
  26935. PropertyBinding.prototype._setValue_arrayElement,
  26936. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26937. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26938. ], [
  26939. // HasToFromArray
  26940. PropertyBinding.prototype._setValue_fromArray,
  26941. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26942. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26943. ]
  26944. ];
  26945. /**
  26946. *
  26947. * A group of objects that receives a shared animation state.
  26948. *
  26949. * Usage:
  26950. *
  26951. * - Add objects you would otherwise pass as 'root' to the
  26952. * constructor or the .clipAction method of AnimationMixer.
  26953. *
  26954. * - Instead pass this object as 'root'.
  26955. *
  26956. * - You can also add and remove objects later when the mixer
  26957. * is running.
  26958. *
  26959. * Note:
  26960. *
  26961. * Objects of this class appear as one object to the mixer,
  26962. * so cache control of the individual objects must be done
  26963. * on the group.
  26964. *
  26965. * Limitation:
  26966. *
  26967. * - The animated properties must be compatible among the
  26968. * all objects in the group.
  26969. *
  26970. * - A single property can either be controlled through a
  26971. * target group or directly, but not both.
  26972. */
  26973. class AnimationObjectGroup {
  26974. constructor() {
  26975. this.isAnimationObjectGroup = true;
  26976. this.uuid = generateUUID();
  26977. // cached objects followed by the active ones
  26978. this._objects = Array.prototype.slice.call( arguments );
  26979. this.nCachedObjects_ = 0; // threshold
  26980. // note: read by PropertyBinding.Composite
  26981. const indices = {};
  26982. this._indicesByUUID = indices; // for bookkeeping
  26983. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26984. indices[ arguments[ i ].uuid ] = i;
  26985. }
  26986. this._paths = []; // inside: string
  26987. this._parsedPaths = []; // inside: { we don't care, here }
  26988. this._bindings = []; // inside: Array< PropertyBinding >
  26989. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26990. const scope = this;
  26991. this.stats = {
  26992. objects: {
  26993. get total() {
  26994. return scope._objects.length;
  26995. },
  26996. get inUse() {
  26997. return this.total - scope.nCachedObjects_;
  26998. }
  26999. },
  27000. get bindingsPerObject() {
  27001. return scope._bindings.length;
  27002. }
  27003. };
  27004. }
  27005. add() {
  27006. const objects = this._objects,
  27007. indicesByUUID = this._indicesByUUID,
  27008. paths = this._paths,
  27009. parsedPaths = this._parsedPaths,
  27010. bindings = this._bindings,
  27011. nBindings = bindings.length;
  27012. let knownObject = undefined,
  27013. nObjects = objects.length,
  27014. nCachedObjects = this.nCachedObjects_;
  27015. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27016. const object = arguments[ i ],
  27017. uuid = object.uuid;
  27018. let index = indicesByUUID[ uuid ];
  27019. if ( index === undefined ) {
  27020. // unknown object -> add it to the ACTIVE region
  27021. index = nObjects ++;
  27022. indicesByUUID[ uuid ] = index;
  27023. objects.push( object );
  27024. // accounting is done, now do the same for all bindings
  27025. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27026. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27027. }
  27028. } else if ( index < nCachedObjects ) {
  27029. knownObject = objects[ index ];
  27030. // move existing object to the ACTIVE region
  27031. const firstActiveIndex = -- nCachedObjects,
  27032. lastCachedObject = objects[ firstActiveIndex ];
  27033. indicesByUUID[ lastCachedObject.uuid ] = index;
  27034. objects[ index ] = lastCachedObject;
  27035. indicesByUUID[ uuid ] = firstActiveIndex;
  27036. objects[ firstActiveIndex ] = object;
  27037. // accounting is done, now do the same for all bindings
  27038. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27039. const bindingsForPath = bindings[ j ],
  27040. lastCached = bindingsForPath[ firstActiveIndex ];
  27041. let binding = bindingsForPath[ index ];
  27042. bindingsForPath[ index ] = lastCached;
  27043. if ( binding === undefined ) {
  27044. // since we do not bother to create new bindings
  27045. // for objects that are cached, the binding may
  27046. // or may not exist
  27047. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27048. }
  27049. bindingsForPath[ firstActiveIndex ] = binding;
  27050. }
  27051. } else if ( objects[ index ] !== knownObject ) {
  27052. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27053. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27054. } // else the object is already where we want it to be
  27055. } // for arguments
  27056. this.nCachedObjects_ = nCachedObjects;
  27057. }
  27058. remove() {
  27059. const objects = this._objects,
  27060. indicesByUUID = this._indicesByUUID,
  27061. bindings = this._bindings,
  27062. nBindings = bindings.length;
  27063. let nCachedObjects = this.nCachedObjects_;
  27064. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27065. const object = arguments[ i ],
  27066. uuid = object.uuid,
  27067. index = indicesByUUID[ uuid ];
  27068. if ( index !== undefined && index >= nCachedObjects ) {
  27069. // move existing object into the CACHED region
  27070. const lastCachedIndex = nCachedObjects ++,
  27071. firstActiveObject = objects[ lastCachedIndex ];
  27072. indicesByUUID[ firstActiveObject.uuid ] = index;
  27073. objects[ index ] = firstActiveObject;
  27074. indicesByUUID[ uuid ] = lastCachedIndex;
  27075. objects[ lastCachedIndex ] = object;
  27076. // accounting is done, now do the same for all bindings
  27077. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27078. const bindingsForPath = bindings[ j ],
  27079. firstActive = bindingsForPath[ lastCachedIndex ],
  27080. binding = bindingsForPath[ index ];
  27081. bindingsForPath[ index ] = firstActive;
  27082. bindingsForPath[ lastCachedIndex ] = binding;
  27083. }
  27084. }
  27085. } // for arguments
  27086. this.nCachedObjects_ = nCachedObjects;
  27087. }
  27088. // remove & forget
  27089. uncache() {
  27090. const objects = this._objects,
  27091. indicesByUUID = this._indicesByUUID,
  27092. bindings = this._bindings,
  27093. nBindings = bindings.length;
  27094. let nCachedObjects = this.nCachedObjects_,
  27095. nObjects = objects.length;
  27096. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27097. const object = arguments[ i ],
  27098. uuid = object.uuid,
  27099. index = indicesByUUID[ uuid ];
  27100. if ( index !== undefined ) {
  27101. delete indicesByUUID[ uuid ];
  27102. if ( index < nCachedObjects ) {
  27103. // object is cached, shrink the CACHED region
  27104. const firstActiveIndex = -- nCachedObjects,
  27105. lastCachedObject = objects[ firstActiveIndex ],
  27106. lastIndex = -- nObjects,
  27107. lastObject = objects[ lastIndex ];
  27108. // last cached object takes this object's place
  27109. indicesByUUID[ lastCachedObject.uuid ] = index;
  27110. objects[ index ] = lastCachedObject;
  27111. // last object goes to the activated slot and pop
  27112. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27113. objects[ firstActiveIndex ] = lastObject;
  27114. objects.pop();
  27115. // accounting is done, now do the same for all bindings
  27116. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27117. const bindingsForPath = bindings[ j ],
  27118. lastCached = bindingsForPath[ firstActiveIndex ],
  27119. last = bindingsForPath[ lastIndex ];
  27120. bindingsForPath[ index ] = lastCached;
  27121. bindingsForPath[ firstActiveIndex ] = last;
  27122. bindingsForPath.pop();
  27123. }
  27124. } else {
  27125. // object is active, just swap with the last and pop
  27126. const lastIndex = -- nObjects,
  27127. lastObject = objects[ lastIndex ];
  27128. if ( lastIndex > 0 ) {
  27129. indicesByUUID[ lastObject.uuid ] = index;
  27130. }
  27131. objects[ index ] = lastObject;
  27132. objects.pop();
  27133. // accounting is done, now do the same for all bindings
  27134. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27135. const bindingsForPath = bindings[ j ];
  27136. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27137. bindingsForPath.pop();
  27138. }
  27139. } // cached or active
  27140. } // if object is known
  27141. } // for arguments
  27142. this.nCachedObjects_ = nCachedObjects;
  27143. }
  27144. // Internal interface used by befriended PropertyBinding.Composite:
  27145. subscribe_( path, parsedPath ) {
  27146. // returns an array of bindings for the given path that is changed
  27147. // according to the contained objects in the group
  27148. const indicesByPath = this._bindingsIndicesByPath;
  27149. let index = indicesByPath[ path ];
  27150. const bindings = this._bindings;
  27151. if ( index !== undefined ) return bindings[ index ];
  27152. const paths = this._paths,
  27153. parsedPaths = this._parsedPaths,
  27154. objects = this._objects,
  27155. nObjects = objects.length,
  27156. nCachedObjects = this.nCachedObjects_,
  27157. bindingsForPath = new Array( nObjects );
  27158. index = bindings.length;
  27159. indicesByPath[ path ] = index;
  27160. paths.push( path );
  27161. parsedPaths.push( parsedPath );
  27162. bindings.push( bindingsForPath );
  27163. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27164. const object = objects[ i ];
  27165. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27166. }
  27167. return bindingsForPath;
  27168. }
  27169. unsubscribe_( path ) {
  27170. // tells the group to forget about a property path and no longer
  27171. // update the array previously obtained with 'subscribe_'
  27172. const indicesByPath = this._bindingsIndicesByPath,
  27173. index = indicesByPath[ path ];
  27174. if ( index !== undefined ) {
  27175. const paths = this._paths,
  27176. parsedPaths = this._parsedPaths,
  27177. bindings = this._bindings,
  27178. lastBindingsIndex = bindings.length - 1,
  27179. lastBindings = bindings[ lastBindingsIndex ],
  27180. lastBindingsPath = path[ lastBindingsIndex ];
  27181. indicesByPath[ lastBindingsPath ] = index;
  27182. bindings[ index ] = lastBindings;
  27183. bindings.pop();
  27184. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27185. parsedPaths.pop();
  27186. paths[ index ] = paths[ lastBindingsIndex ];
  27187. paths.pop();
  27188. }
  27189. }
  27190. }
  27191. class AnimationAction {
  27192. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27193. this._mixer = mixer;
  27194. this._clip = clip;
  27195. this._localRoot = localRoot;
  27196. this.blendMode = blendMode;
  27197. const tracks = clip.tracks,
  27198. nTracks = tracks.length,
  27199. interpolants = new Array( nTracks );
  27200. const interpolantSettings = {
  27201. endingStart: ZeroCurvatureEnding,
  27202. endingEnd: ZeroCurvatureEnding
  27203. };
  27204. for ( let i = 0; i !== nTracks; ++ i ) {
  27205. const interpolant = tracks[ i ].createInterpolant( null );
  27206. interpolants[ i ] = interpolant;
  27207. interpolant.settings = interpolantSettings;
  27208. }
  27209. this._interpolantSettings = interpolantSettings;
  27210. this._interpolants = interpolants; // bound by the mixer
  27211. // inside: PropertyMixer (managed by the mixer)
  27212. this._propertyBindings = new Array( nTracks );
  27213. this._cacheIndex = null; // for the memory manager
  27214. this._byClipCacheIndex = null; // for the memory manager
  27215. this._timeScaleInterpolant = null;
  27216. this._weightInterpolant = null;
  27217. this.loop = LoopRepeat;
  27218. this._loopCount = - 1;
  27219. // global mixer time when the action is to be started
  27220. // it's set back to 'null' upon start of the action
  27221. this._startTime = null;
  27222. // scaled local time of the action
  27223. // gets clamped or wrapped to 0..clip.duration according to loop
  27224. this.time = 0;
  27225. this.timeScale = 1;
  27226. this._effectiveTimeScale = 1;
  27227. this.weight = 1;
  27228. this._effectiveWeight = 1;
  27229. this.repetitions = Infinity; // no. of repetitions when looping
  27230. this.paused = false; // true -> zero effective time scale
  27231. this.enabled = true; // false -> zero effective weight
  27232. this.clampWhenFinished = false;// keep feeding the last frame?
  27233. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27234. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27235. }
  27236. // State & Scheduling
  27237. play() {
  27238. this._mixer._activateAction( this );
  27239. return this;
  27240. }
  27241. stop() {
  27242. this._mixer._deactivateAction( this );
  27243. return this.reset();
  27244. }
  27245. reset() {
  27246. this.paused = false;
  27247. this.enabled = true;
  27248. this.time = 0; // restart clip
  27249. this._loopCount = - 1;// forget previous loops
  27250. this._startTime = null;// forget scheduling
  27251. return this.stopFading().stopWarping();
  27252. }
  27253. isRunning() {
  27254. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27255. this._startTime === null && this._mixer._isActiveAction( this );
  27256. }
  27257. // return true when play has been called
  27258. isScheduled() {
  27259. return this._mixer._isActiveAction( this );
  27260. }
  27261. startAt( time ) {
  27262. this._startTime = time;
  27263. return this;
  27264. }
  27265. setLoop( mode, repetitions ) {
  27266. this.loop = mode;
  27267. this.repetitions = repetitions;
  27268. return this;
  27269. }
  27270. // Weight
  27271. // set the weight stopping any scheduled fading
  27272. // although .enabled = false yields an effective weight of zero, this
  27273. // method does *not* change .enabled, because it would be confusing
  27274. setEffectiveWeight( weight ) {
  27275. this.weight = weight;
  27276. // note: same logic as when updated at runtime
  27277. this._effectiveWeight = this.enabled ? weight : 0;
  27278. return this.stopFading();
  27279. }
  27280. // return the weight considering fading and .enabled
  27281. getEffectiveWeight() {
  27282. return this._effectiveWeight;
  27283. }
  27284. fadeIn( duration ) {
  27285. return this._scheduleFading( duration, 0, 1 );
  27286. }
  27287. fadeOut( duration ) {
  27288. return this._scheduleFading( duration, 1, 0 );
  27289. }
  27290. crossFadeFrom( fadeOutAction, duration, warp ) {
  27291. fadeOutAction.fadeOut( duration );
  27292. this.fadeIn( duration );
  27293. if ( warp ) {
  27294. const fadeInDuration = this._clip.duration,
  27295. fadeOutDuration = fadeOutAction._clip.duration,
  27296. startEndRatio = fadeOutDuration / fadeInDuration,
  27297. endStartRatio = fadeInDuration / fadeOutDuration;
  27298. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27299. this.warp( endStartRatio, 1.0, duration );
  27300. }
  27301. return this;
  27302. }
  27303. crossFadeTo( fadeInAction, duration, warp ) {
  27304. return fadeInAction.crossFadeFrom( this, duration, warp );
  27305. }
  27306. stopFading() {
  27307. const weightInterpolant = this._weightInterpolant;
  27308. if ( weightInterpolant !== null ) {
  27309. this._weightInterpolant = null;
  27310. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27311. }
  27312. return this;
  27313. }
  27314. // Time Scale Control
  27315. // set the time scale stopping any scheduled warping
  27316. // although .paused = true yields an effective time scale of zero, this
  27317. // method does *not* change .paused, because it would be confusing
  27318. setEffectiveTimeScale( timeScale ) {
  27319. this.timeScale = timeScale;
  27320. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27321. return this.stopWarping();
  27322. }
  27323. // return the time scale considering warping and .paused
  27324. getEffectiveTimeScale() {
  27325. return this._effectiveTimeScale;
  27326. }
  27327. setDuration( duration ) {
  27328. this.timeScale = this._clip.duration / duration;
  27329. return this.stopWarping();
  27330. }
  27331. syncWith( action ) {
  27332. this.time = action.time;
  27333. this.timeScale = action.timeScale;
  27334. return this.stopWarping();
  27335. }
  27336. halt( duration ) {
  27337. return this.warp( this._effectiveTimeScale, 0, duration );
  27338. }
  27339. warp( startTimeScale, endTimeScale, duration ) {
  27340. const mixer = this._mixer,
  27341. now = mixer.time,
  27342. timeScale = this.timeScale;
  27343. let interpolant = this._timeScaleInterpolant;
  27344. if ( interpolant === null ) {
  27345. interpolant = mixer._lendControlInterpolant();
  27346. this._timeScaleInterpolant = interpolant;
  27347. }
  27348. const times = interpolant.parameterPositions,
  27349. values = interpolant.sampleValues;
  27350. times[ 0 ] = now;
  27351. times[ 1 ] = now + duration;
  27352. values[ 0 ] = startTimeScale / timeScale;
  27353. values[ 1 ] = endTimeScale / timeScale;
  27354. return this;
  27355. }
  27356. stopWarping() {
  27357. const timeScaleInterpolant = this._timeScaleInterpolant;
  27358. if ( timeScaleInterpolant !== null ) {
  27359. this._timeScaleInterpolant = null;
  27360. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27361. }
  27362. return this;
  27363. }
  27364. // Object Accessors
  27365. getMixer() {
  27366. return this._mixer;
  27367. }
  27368. getClip() {
  27369. return this._clip;
  27370. }
  27371. getRoot() {
  27372. return this._localRoot || this._mixer._root;
  27373. }
  27374. // Interna
  27375. _update( time, deltaTime, timeDirection, accuIndex ) {
  27376. // called by the mixer
  27377. if ( ! this.enabled ) {
  27378. // call ._updateWeight() to update ._effectiveWeight
  27379. this._updateWeight( time );
  27380. return;
  27381. }
  27382. const startTime = this._startTime;
  27383. if ( startTime !== null ) {
  27384. // check for scheduled start of action
  27385. const timeRunning = ( time - startTime ) * timeDirection;
  27386. if ( timeRunning < 0 || timeDirection === 0 ) {
  27387. deltaTime = 0;
  27388. } else {
  27389. this._startTime = null; // unschedule
  27390. deltaTime = timeDirection * timeRunning;
  27391. }
  27392. }
  27393. // apply time scale and advance time
  27394. deltaTime *= this._updateTimeScale( time );
  27395. const clipTime = this._updateTime( deltaTime );
  27396. // note: _updateTime may disable the action resulting in
  27397. // an effective weight of 0
  27398. const weight = this._updateWeight( time );
  27399. if ( weight > 0 ) {
  27400. const interpolants = this._interpolants;
  27401. const propertyMixers = this._propertyBindings;
  27402. switch ( this.blendMode ) {
  27403. case AdditiveAnimationBlendMode:
  27404. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27405. interpolants[ j ].evaluate( clipTime );
  27406. propertyMixers[ j ].accumulateAdditive( weight );
  27407. }
  27408. break;
  27409. case NormalAnimationBlendMode:
  27410. default:
  27411. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27412. interpolants[ j ].evaluate( clipTime );
  27413. propertyMixers[ j ].accumulate( accuIndex, weight );
  27414. }
  27415. }
  27416. }
  27417. }
  27418. _updateWeight( time ) {
  27419. let weight = 0;
  27420. if ( this.enabled ) {
  27421. weight = this.weight;
  27422. const interpolant = this._weightInterpolant;
  27423. if ( interpolant !== null ) {
  27424. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27425. weight *= interpolantValue;
  27426. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27427. this.stopFading();
  27428. if ( interpolantValue === 0 ) {
  27429. // faded out, disable
  27430. this.enabled = false;
  27431. }
  27432. }
  27433. }
  27434. }
  27435. this._effectiveWeight = weight;
  27436. return weight;
  27437. }
  27438. _updateTimeScale( time ) {
  27439. let timeScale = 0;
  27440. if ( ! this.paused ) {
  27441. timeScale = this.timeScale;
  27442. const interpolant = this._timeScaleInterpolant;
  27443. if ( interpolant !== null ) {
  27444. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27445. timeScale *= interpolantValue;
  27446. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27447. this.stopWarping();
  27448. if ( timeScale === 0 ) {
  27449. // motion has halted, pause
  27450. this.paused = true;
  27451. } else {
  27452. // warp done - apply final time scale
  27453. this.timeScale = timeScale;
  27454. }
  27455. }
  27456. }
  27457. }
  27458. this._effectiveTimeScale = timeScale;
  27459. return timeScale;
  27460. }
  27461. _updateTime( deltaTime ) {
  27462. const duration = this._clip.duration;
  27463. const loop = this.loop;
  27464. let time = this.time + deltaTime;
  27465. let loopCount = this._loopCount;
  27466. const pingPong = ( loop === LoopPingPong );
  27467. if ( deltaTime === 0 ) {
  27468. if ( loopCount === - 1 ) return time;
  27469. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27470. }
  27471. if ( loop === LoopOnce ) {
  27472. if ( loopCount === - 1 ) {
  27473. // just started
  27474. this._loopCount = 0;
  27475. this._setEndings( true, true, false );
  27476. }
  27477. handle_stop: {
  27478. if ( time >= duration ) {
  27479. time = duration;
  27480. } else if ( time < 0 ) {
  27481. time = 0;
  27482. } else {
  27483. this.time = time;
  27484. break handle_stop;
  27485. }
  27486. if ( this.clampWhenFinished ) this.paused = true;
  27487. else this.enabled = false;
  27488. this.time = time;
  27489. this._mixer.dispatchEvent( {
  27490. type: 'finished', action: this,
  27491. direction: deltaTime < 0 ? - 1 : 1
  27492. } );
  27493. }
  27494. } else { // repetitive Repeat or PingPong
  27495. if ( loopCount === - 1 ) {
  27496. // just started
  27497. if ( deltaTime >= 0 ) {
  27498. loopCount = 0;
  27499. this._setEndings( true, this.repetitions === 0, pingPong );
  27500. } else {
  27501. // when looping in reverse direction, the initial
  27502. // transition through zero counts as a repetition,
  27503. // so leave loopCount at -1
  27504. this._setEndings( this.repetitions === 0, true, pingPong );
  27505. }
  27506. }
  27507. if ( time >= duration || time < 0 ) {
  27508. // wrap around
  27509. const loopDelta = Math.floor( time / duration ); // signed
  27510. time -= duration * loopDelta;
  27511. loopCount += Math.abs( loopDelta );
  27512. const pending = this.repetitions - loopCount;
  27513. if ( pending <= 0 ) {
  27514. // have to stop (switch state, clamp time, fire event)
  27515. if ( this.clampWhenFinished ) this.paused = true;
  27516. else this.enabled = false;
  27517. time = deltaTime > 0 ? duration : 0;
  27518. this.time = time;
  27519. this._mixer.dispatchEvent( {
  27520. type: 'finished', action: this,
  27521. direction: deltaTime > 0 ? 1 : - 1
  27522. } );
  27523. } else {
  27524. // keep running
  27525. if ( pending === 1 ) {
  27526. // entering the last round
  27527. const atStart = deltaTime < 0;
  27528. this._setEndings( atStart, ! atStart, pingPong );
  27529. } else {
  27530. this._setEndings( false, false, pingPong );
  27531. }
  27532. this._loopCount = loopCount;
  27533. this.time = time;
  27534. this._mixer.dispatchEvent( {
  27535. type: 'loop', action: this, loopDelta: loopDelta
  27536. } );
  27537. }
  27538. } else {
  27539. this.time = time;
  27540. }
  27541. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27542. // invert time for the "pong round"
  27543. return duration - time;
  27544. }
  27545. }
  27546. return time;
  27547. }
  27548. _setEndings( atStart, atEnd, pingPong ) {
  27549. const settings = this._interpolantSettings;
  27550. if ( pingPong ) {
  27551. settings.endingStart = ZeroSlopeEnding;
  27552. settings.endingEnd = ZeroSlopeEnding;
  27553. } else {
  27554. // assuming for LoopOnce atStart == atEnd == true
  27555. if ( atStart ) {
  27556. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27557. } else {
  27558. settings.endingStart = WrapAroundEnding;
  27559. }
  27560. if ( atEnd ) {
  27561. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27562. } else {
  27563. settings.endingEnd = WrapAroundEnding;
  27564. }
  27565. }
  27566. }
  27567. _scheduleFading( duration, weightNow, weightThen ) {
  27568. const mixer = this._mixer, now = mixer.time;
  27569. let interpolant = this._weightInterpolant;
  27570. if ( interpolant === null ) {
  27571. interpolant = mixer._lendControlInterpolant();
  27572. this._weightInterpolant = interpolant;
  27573. }
  27574. const times = interpolant.parameterPositions,
  27575. values = interpolant.sampleValues;
  27576. times[ 0 ] = now;
  27577. values[ 0 ] = weightNow;
  27578. times[ 1 ] = now + duration;
  27579. values[ 1 ] = weightThen;
  27580. return this;
  27581. }
  27582. }
  27583. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27584. class AnimationMixer extends EventDispatcher {
  27585. constructor( root ) {
  27586. super();
  27587. this._root = root;
  27588. this._initMemoryManager();
  27589. this._accuIndex = 0;
  27590. this.time = 0;
  27591. this.timeScale = 1.0;
  27592. }
  27593. _bindAction( action, prototypeAction ) {
  27594. const root = action._localRoot || this._root,
  27595. tracks = action._clip.tracks,
  27596. nTracks = tracks.length,
  27597. bindings = action._propertyBindings,
  27598. interpolants = action._interpolants,
  27599. rootUuid = root.uuid,
  27600. bindingsByRoot = this._bindingsByRootAndName;
  27601. let bindingsByName = bindingsByRoot[ rootUuid ];
  27602. if ( bindingsByName === undefined ) {
  27603. bindingsByName = {};
  27604. bindingsByRoot[ rootUuid ] = bindingsByName;
  27605. }
  27606. for ( let i = 0; i !== nTracks; ++ i ) {
  27607. const track = tracks[ i ],
  27608. trackName = track.name;
  27609. let binding = bindingsByName[ trackName ];
  27610. if ( binding !== undefined ) {
  27611. ++ binding.referenceCount;
  27612. bindings[ i ] = binding;
  27613. } else {
  27614. binding = bindings[ i ];
  27615. if ( binding !== undefined ) {
  27616. // existing binding, make sure the cache knows
  27617. if ( binding._cacheIndex === null ) {
  27618. ++ binding.referenceCount;
  27619. this._addInactiveBinding( binding, rootUuid, trackName );
  27620. }
  27621. continue;
  27622. }
  27623. const path = prototypeAction && prototypeAction.
  27624. _propertyBindings[ i ].binding.parsedPath;
  27625. binding = new PropertyMixer(
  27626. PropertyBinding.create( root, trackName, path ),
  27627. track.ValueTypeName, track.getValueSize() );
  27628. ++ binding.referenceCount;
  27629. this._addInactiveBinding( binding, rootUuid, trackName );
  27630. bindings[ i ] = binding;
  27631. }
  27632. interpolants[ i ].resultBuffer = binding.buffer;
  27633. }
  27634. }
  27635. _activateAction( action ) {
  27636. if ( ! this._isActiveAction( action ) ) {
  27637. if ( action._cacheIndex === null ) {
  27638. // this action has been forgotten by the cache, but the user
  27639. // appears to be still using it -> rebind
  27640. const rootUuid = ( action._localRoot || this._root ).uuid,
  27641. clipUuid = action._clip.uuid,
  27642. actionsForClip = this._actionsByClip[ clipUuid ];
  27643. this._bindAction( action,
  27644. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27645. this._addInactiveAction( action, clipUuid, rootUuid );
  27646. }
  27647. const bindings = action._propertyBindings;
  27648. // increment reference counts / sort out state
  27649. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27650. const binding = bindings[ i ];
  27651. if ( binding.useCount ++ === 0 ) {
  27652. this._lendBinding( binding );
  27653. binding.saveOriginalState();
  27654. }
  27655. }
  27656. this._lendAction( action );
  27657. }
  27658. }
  27659. _deactivateAction( action ) {
  27660. if ( this._isActiveAction( action ) ) {
  27661. const bindings = action._propertyBindings;
  27662. // decrement reference counts / sort out state
  27663. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27664. const binding = bindings[ i ];
  27665. if ( -- binding.useCount === 0 ) {
  27666. binding.restoreOriginalState();
  27667. this._takeBackBinding( binding );
  27668. }
  27669. }
  27670. this._takeBackAction( action );
  27671. }
  27672. }
  27673. // Memory manager
  27674. _initMemoryManager() {
  27675. this._actions = []; // 'nActiveActions' followed by inactive ones
  27676. this._nActiveActions = 0;
  27677. this._actionsByClip = {};
  27678. // inside:
  27679. // {
  27680. // knownActions: Array< AnimationAction > - used as prototypes
  27681. // actionByRoot: AnimationAction - lookup
  27682. // }
  27683. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27684. this._nActiveBindings = 0;
  27685. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27686. this._controlInterpolants = []; // same game as above
  27687. this._nActiveControlInterpolants = 0;
  27688. const scope = this;
  27689. this.stats = {
  27690. actions: {
  27691. get total() {
  27692. return scope._actions.length;
  27693. },
  27694. get inUse() {
  27695. return scope._nActiveActions;
  27696. }
  27697. },
  27698. bindings: {
  27699. get total() {
  27700. return scope._bindings.length;
  27701. },
  27702. get inUse() {
  27703. return scope._nActiveBindings;
  27704. }
  27705. },
  27706. controlInterpolants: {
  27707. get total() {
  27708. return scope._controlInterpolants.length;
  27709. },
  27710. get inUse() {
  27711. return scope._nActiveControlInterpolants;
  27712. }
  27713. }
  27714. };
  27715. }
  27716. // Memory management for AnimationAction objects
  27717. _isActiveAction( action ) {
  27718. const index = action._cacheIndex;
  27719. return index !== null && index < this._nActiveActions;
  27720. }
  27721. _addInactiveAction( action, clipUuid, rootUuid ) {
  27722. const actions = this._actions,
  27723. actionsByClip = this._actionsByClip;
  27724. let actionsForClip = actionsByClip[ clipUuid ];
  27725. if ( actionsForClip === undefined ) {
  27726. actionsForClip = {
  27727. knownActions: [ action ],
  27728. actionByRoot: {}
  27729. };
  27730. action._byClipCacheIndex = 0;
  27731. actionsByClip[ clipUuid ] = actionsForClip;
  27732. } else {
  27733. const knownActions = actionsForClip.knownActions;
  27734. action._byClipCacheIndex = knownActions.length;
  27735. knownActions.push( action );
  27736. }
  27737. action._cacheIndex = actions.length;
  27738. actions.push( action );
  27739. actionsForClip.actionByRoot[ rootUuid ] = action;
  27740. }
  27741. _removeInactiveAction( action ) {
  27742. const actions = this._actions,
  27743. lastInactiveAction = actions[ actions.length - 1 ],
  27744. cacheIndex = action._cacheIndex;
  27745. lastInactiveAction._cacheIndex = cacheIndex;
  27746. actions[ cacheIndex ] = lastInactiveAction;
  27747. actions.pop();
  27748. action._cacheIndex = null;
  27749. const clipUuid = action._clip.uuid,
  27750. actionsByClip = this._actionsByClip,
  27751. actionsForClip = actionsByClip[ clipUuid ],
  27752. knownActionsForClip = actionsForClip.knownActions,
  27753. lastKnownAction =
  27754. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27755. byClipCacheIndex = action._byClipCacheIndex;
  27756. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27757. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27758. knownActionsForClip.pop();
  27759. action._byClipCacheIndex = null;
  27760. const actionByRoot = actionsForClip.actionByRoot,
  27761. rootUuid = ( action._localRoot || this._root ).uuid;
  27762. delete actionByRoot[ rootUuid ];
  27763. if ( knownActionsForClip.length === 0 ) {
  27764. delete actionsByClip[ clipUuid ];
  27765. }
  27766. this._removeInactiveBindingsForAction( action );
  27767. }
  27768. _removeInactiveBindingsForAction( action ) {
  27769. const bindings = action._propertyBindings;
  27770. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27771. const binding = bindings[ i ];
  27772. if ( -- binding.referenceCount === 0 ) {
  27773. this._removeInactiveBinding( binding );
  27774. }
  27775. }
  27776. }
  27777. _lendAction( action ) {
  27778. // [ active actions | inactive actions ]
  27779. // [ active actions >| inactive actions ]
  27780. // s a
  27781. // <-swap->
  27782. // a s
  27783. const actions = this._actions,
  27784. prevIndex = action._cacheIndex,
  27785. lastActiveIndex = this._nActiveActions ++,
  27786. firstInactiveAction = actions[ lastActiveIndex ];
  27787. action._cacheIndex = lastActiveIndex;
  27788. actions[ lastActiveIndex ] = action;
  27789. firstInactiveAction._cacheIndex = prevIndex;
  27790. actions[ prevIndex ] = firstInactiveAction;
  27791. }
  27792. _takeBackAction( action ) {
  27793. // [ active actions | inactive actions ]
  27794. // [ active actions |< inactive actions ]
  27795. // a s
  27796. // <-swap->
  27797. // s a
  27798. const actions = this._actions,
  27799. prevIndex = action._cacheIndex,
  27800. firstInactiveIndex = -- this._nActiveActions,
  27801. lastActiveAction = actions[ firstInactiveIndex ];
  27802. action._cacheIndex = firstInactiveIndex;
  27803. actions[ firstInactiveIndex ] = action;
  27804. lastActiveAction._cacheIndex = prevIndex;
  27805. actions[ prevIndex ] = lastActiveAction;
  27806. }
  27807. // Memory management for PropertyMixer objects
  27808. _addInactiveBinding( binding, rootUuid, trackName ) {
  27809. const bindingsByRoot = this._bindingsByRootAndName,
  27810. bindings = this._bindings;
  27811. let bindingByName = bindingsByRoot[ rootUuid ];
  27812. if ( bindingByName === undefined ) {
  27813. bindingByName = {};
  27814. bindingsByRoot[ rootUuid ] = bindingByName;
  27815. }
  27816. bindingByName[ trackName ] = binding;
  27817. binding._cacheIndex = bindings.length;
  27818. bindings.push( binding );
  27819. }
  27820. _removeInactiveBinding( binding ) {
  27821. const bindings = this._bindings,
  27822. propBinding = binding.binding,
  27823. rootUuid = propBinding.rootNode.uuid,
  27824. trackName = propBinding.path,
  27825. bindingsByRoot = this._bindingsByRootAndName,
  27826. bindingByName = bindingsByRoot[ rootUuid ],
  27827. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27828. cacheIndex = binding._cacheIndex;
  27829. lastInactiveBinding._cacheIndex = cacheIndex;
  27830. bindings[ cacheIndex ] = lastInactiveBinding;
  27831. bindings.pop();
  27832. delete bindingByName[ trackName ];
  27833. if ( Object.keys( bindingByName ).length === 0 ) {
  27834. delete bindingsByRoot[ rootUuid ];
  27835. }
  27836. }
  27837. _lendBinding( binding ) {
  27838. const bindings = this._bindings,
  27839. prevIndex = binding._cacheIndex,
  27840. lastActiveIndex = this._nActiveBindings ++,
  27841. firstInactiveBinding = bindings[ lastActiveIndex ];
  27842. binding._cacheIndex = lastActiveIndex;
  27843. bindings[ lastActiveIndex ] = binding;
  27844. firstInactiveBinding._cacheIndex = prevIndex;
  27845. bindings[ prevIndex ] = firstInactiveBinding;
  27846. }
  27847. _takeBackBinding( binding ) {
  27848. const bindings = this._bindings,
  27849. prevIndex = binding._cacheIndex,
  27850. firstInactiveIndex = -- this._nActiveBindings,
  27851. lastActiveBinding = bindings[ firstInactiveIndex ];
  27852. binding._cacheIndex = firstInactiveIndex;
  27853. bindings[ firstInactiveIndex ] = binding;
  27854. lastActiveBinding._cacheIndex = prevIndex;
  27855. bindings[ prevIndex ] = lastActiveBinding;
  27856. }
  27857. // Memory management of Interpolants for weight and time scale
  27858. _lendControlInterpolant() {
  27859. const interpolants = this._controlInterpolants,
  27860. lastActiveIndex = this._nActiveControlInterpolants ++;
  27861. let interpolant = interpolants[ lastActiveIndex ];
  27862. if ( interpolant === undefined ) {
  27863. interpolant = new LinearInterpolant(
  27864. new Float32Array( 2 ), new Float32Array( 2 ),
  27865. 1, _controlInterpolantsResultBuffer );
  27866. interpolant.__cacheIndex = lastActiveIndex;
  27867. interpolants[ lastActiveIndex ] = interpolant;
  27868. }
  27869. return interpolant;
  27870. }
  27871. _takeBackControlInterpolant( interpolant ) {
  27872. const interpolants = this._controlInterpolants,
  27873. prevIndex = interpolant.__cacheIndex,
  27874. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27875. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27876. interpolant.__cacheIndex = firstInactiveIndex;
  27877. interpolants[ firstInactiveIndex ] = interpolant;
  27878. lastActiveInterpolant.__cacheIndex = prevIndex;
  27879. interpolants[ prevIndex ] = lastActiveInterpolant;
  27880. }
  27881. // return an action for a clip optionally using a custom root target
  27882. // object (this method allocates a lot of dynamic memory in case a
  27883. // previously unknown clip/root combination is specified)
  27884. clipAction( clip, optionalRoot, blendMode ) {
  27885. const root = optionalRoot || this._root,
  27886. rootUuid = root.uuid;
  27887. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27888. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27889. const actionsForClip = this._actionsByClip[ clipUuid ];
  27890. let prototypeAction = null;
  27891. if ( blendMode === undefined ) {
  27892. if ( clipObject !== null ) {
  27893. blendMode = clipObject.blendMode;
  27894. } else {
  27895. blendMode = NormalAnimationBlendMode;
  27896. }
  27897. }
  27898. if ( actionsForClip !== undefined ) {
  27899. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27900. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27901. return existingAction;
  27902. }
  27903. // we know the clip, so we don't have to parse all
  27904. // the bindings again but can just copy
  27905. prototypeAction = actionsForClip.knownActions[ 0 ];
  27906. // also, take the clip from the prototype action
  27907. if ( clipObject === null )
  27908. clipObject = prototypeAction._clip;
  27909. }
  27910. // clip must be known when specified via string
  27911. if ( clipObject === null ) return null;
  27912. // allocate all resources required to run it
  27913. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27914. this._bindAction( newAction, prototypeAction );
  27915. // and make the action known to the memory manager
  27916. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27917. return newAction;
  27918. }
  27919. // get an existing action
  27920. existingAction( clip, optionalRoot ) {
  27921. const root = optionalRoot || this._root,
  27922. rootUuid = root.uuid,
  27923. clipObject = typeof clip === 'string' ?
  27924. AnimationClip.findByName( root, clip ) : clip,
  27925. clipUuid = clipObject ? clipObject.uuid : clip,
  27926. actionsForClip = this._actionsByClip[ clipUuid ];
  27927. if ( actionsForClip !== undefined ) {
  27928. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27929. }
  27930. return null;
  27931. }
  27932. // deactivates all previously scheduled actions
  27933. stopAllAction() {
  27934. const actions = this._actions,
  27935. nActions = this._nActiveActions;
  27936. for ( let i = nActions - 1; i >= 0; -- i ) {
  27937. actions[ i ].stop();
  27938. }
  27939. return this;
  27940. }
  27941. // advance the time and update apply the animation
  27942. update( deltaTime ) {
  27943. deltaTime *= this.timeScale;
  27944. const actions = this._actions,
  27945. nActions = this._nActiveActions,
  27946. time = this.time += deltaTime,
  27947. timeDirection = Math.sign( deltaTime ),
  27948. accuIndex = this._accuIndex ^= 1;
  27949. // run active actions
  27950. for ( let i = 0; i !== nActions; ++ i ) {
  27951. const action = actions[ i ];
  27952. action._update( time, deltaTime, timeDirection, accuIndex );
  27953. }
  27954. // update scene graph
  27955. const bindings = this._bindings,
  27956. nBindings = this._nActiveBindings;
  27957. for ( let i = 0; i !== nBindings; ++ i ) {
  27958. bindings[ i ].apply( accuIndex );
  27959. }
  27960. return this;
  27961. }
  27962. // Allows you to seek to a specific time in an animation.
  27963. setTime( timeInSeconds ) {
  27964. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27965. for ( let i = 0; i < this._actions.length; i ++ ) {
  27966. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27967. }
  27968. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27969. }
  27970. // return this mixer's root target object
  27971. getRoot() {
  27972. return this._root;
  27973. }
  27974. // free all resources specific to a particular clip
  27975. uncacheClip( clip ) {
  27976. const actions = this._actions,
  27977. clipUuid = clip.uuid,
  27978. actionsByClip = this._actionsByClip,
  27979. actionsForClip = actionsByClip[ clipUuid ];
  27980. if ( actionsForClip !== undefined ) {
  27981. // note: just calling _removeInactiveAction would mess up the
  27982. // iteration state and also require updating the state we can
  27983. // just throw away
  27984. const actionsToRemove = actionsForClip.knownActions;
  27985. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27986. const action = actionsToRemove[ i ];
  27987. this._deactivateAction( action );
  27988. const cacheIndex = action._cacheIndex,
  27989. lastInactiveAction = actions[ actions.length - 1 ];
  27990. action._cacheIndex = null;
  27991. action._byClipCacheIndex = null;
  27992. lastInactiveAction._cacheIndex = cacheIndex;
  27993. actions[ cacheIndex ] = lastInactiveAction;
  27994. actions.pop();
  27995. this._removeInactiveBindingsForAction( action );
  27996. }
  27997. delete actionsByClip[ clipUuid ];
  27998. }
  27999. }
  28000. // free all resources specific to a particular root target object
  28001. uncacheRoot( root ) {
  28002. const rootUuid = root.uuid,
  28003. actionsByClip = this._actionsByClip;
  28004. for ( const clipUuid in actionsByClip ) {
  28005. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28006. action = actionByRoot[ rootUuid ];
  28007. if ( action !== undefined ) {
  28008. this._deactivateAction( action );
  28009. this._removeInactiveAction( action );
  28010. }
  28011. }
  28012. const bindingsByRoot = this._bindingsByRootAndName,
  28013. bindingByName = bindingsByRoot[ rootUuid ];
  28014. if ( bindingByName !== undefined ) {
  28015. for ( const trackName in bindingByName ) {
  28016. const binding = bindingByName[ trackName ];
  28017. binding.restoreOriginalState();
  28018. this._removeInactiveBinding( binding );
  28019. }
  28020. }
  28021. }
  28022. // remove a targeted clip from the cache
  28023. uncacheAction( clip, optionalRoot ) {
  28024. const action = this.existingAction( clip, optionalRoot );
  28025. if ( action !== null ) {
  28026. this._deactivateAction( action );
  28027. this._removeInactiveAction( action );
  28028. }
  28029. }
  28030. }
  28031. class Uniform {
  28032. constructor( value ) {
  28033. this.value = value;
  28034. }
  28035. clone() {
  28036. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28037. }
  28038. }
  28039. let id = 0;
  28040. class UniformsGroup extends EventDispatcher {
  28041. constructor() {
  28042. super();
  28043. this.isUniformsGroup = true;
  28044. Object.defineProperty( this, 'id', { value: id ++ } );
  28045. this.name = '';
  28046. this.usage = StaticDrawUsage;
  28047. this.uniforms = [];
  28048. }
  28049. add( uniform ) {
  28050. this.uniforms.push( uniform );
  28051. return this;
  28052. }
  28053. remove( uniform ) {
  28054. const index = this.uniforms.indexOf( uniform );
  28055. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28056. return this;
  28057. }
  28058. setName( name ) {
  28059. this.name = name;
  28060. return this;
  28061. }
  28062. setUsage( value ) {
  28063. this.usage = value;
  28064. return this;
  28065. }
  28066. dispose() {
  28067. this.dispatchEvent( { type: 'dispose' } );
  28068. return this;
  28069. }
  28070. copy( source ) {
  28071. this.name = source.name;
  28072. this.usage = source.usage;
  28073. const uniformsSource = source.uniforms;
  28074. this.uniforms.length = 0;
  28075. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28076. this.uniforms.push( uniformsSource[ i ].clone() );
  28077. }
  28078. return this;
  28079. }
  28080. clone() {
  28081. return new this.constructor().copy( this );
  28082. }
  28083. }
  28084. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28085. constructor( array, stride, meshPerAttribute = 1 ) {
  28086. super( array, stride );
  28087. this.isInstancedInterleavedBuffer = true;
  28088. this.meshPerAttribute = meshPerAttribute;
  28089. }
  28090. copy( source ) {
  28091. super.copy( source );
  28092. this.meshPerAttribute = source.meshPerAttribute;
  28093. return this;
  28094. }
  28095. clone( data ) {
  28096. const ib = super.clone( data );
  28097. ib.meshPerAttribute = this.meshPerAttribute;
  28098. return ib;
  28099. }
  28100. toJSON( data ) {
  28101. const json = super.toJSON( data );
  28102. json.isInstancedInterleavedBuffer = true;
  28103. json.meshPerAttribute = this.meshPerAttribute;
  28104. return json;
  28105. }
  28106. }
  28107. class GLBufferAttribute {
  28108. constructor( buffer, type, itemSize, elementSize, count ) {
  28109. this.isGLBufferAttribute = true;
  28110. this.name = '';
  28111. this.buffer = buffer;
  28112. this.type = type;
  28113. this.itemSize = itemSize;
  28114. this.elementSize = elementSize;
  28115. this.count = count;
  28116. this.version = 0;
  28117. }
  28118. set needsUpdate( value ) {
  28119. if ( value === true ) this.version ++;
  28120. }
  28121. setBuffer( buffer ) {
  28122. this.buffer = buffer;
  28123. return this;
  28124. }
  28125. setType( type, elementSize ) {
  28126. this.type = type;
  28127. this.elementSize = elementSize;
  28128. return this;
  28129. }
  28130. setItemSize( itemSize ) {
  28131. this.itemSize = itemSize;
  28132. return this;
  28133. }
  28134. setCount( count ) {
  28135. this.count = count;
  28136. return this;
  28137. }
  28138. }
  28139. class Raycaster {
  28140. constructor( origin, direction, near = 0, far = Infinity ) {
  28141. this.ray = new Ray( origin, direction );
  28142. // direction is assumed to be normalized (for accurate distance calculations)
  28143. this.near = near;
  28144. this.far = far;
  28145. this.camera = null;
  28146. this.layers = new Layers();
  28147. this.params = {
  28148. Mesh: {},
  28149. Line: { threshold: 1 },
  28150. LOD: {},
  28151. Points: { threshold: 1 },
  28152. Sprite: {}
  28153. };
  28154. }
  28155. set( origin, direction ) {
  28156. // direction is assumed to be normalized (for accurate distance calculations)
  28157. this.ray.set( origin, direction );
  28158. }
  28159. setFromCamera( coords, camera ) {
  28160. if ( camera.isPerspectiveCamera ) {
  28161. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28162. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28163. this.camera = camera;
  28164. } else if ( camera.isOrthographicCamera ) {
  28165. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28166. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28167. this.camera = camera;
  28168. } else {
  28169. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28170. }
  28171. }
  28172. intersectObject( object, recursive = true, intersects = [] ) {
  28173. intersectObject( object, this, intersects, recursive );
  28174. intersects.sort( ascSort );
  28175. return intersects;
  28176. }
  28177. intersectObjects( objects, recursive = true, intersects = [] ) {
  28178. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28179. intersectObject( objects[ i ], this, intersects, recursive );
  28180. }
  28181. intersects.sort( ascSort );
  28182. return intersects;
  28183. }
  28184. }
  28185. function ascSort( a, b ) {
  28186. return a.distance - b.distance;
  28187. }
  28188. function intersectObject( object, raycaster, intersects, recursive ) {
  28189. if ( object.layers.test( raycaster.layers ) ) {
  28190. object.raycast( raycaster, intersects );
  28191. }
  28192. if ( recursive === true ) {
  28193. const children = object.children;
  28194. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28195. intersectObject( children[ i ], raycaster, intersects, true );
  28196. }
  28197. }
  28198. }
  28199. /**
  28200. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28201. *
  28202. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28203. * The azimuthal angle (theta) is measured from the positive z-axis.
  28204. */
  28205. class Spherical {
  28206. constructor( radius = 1, phi = 0, theta = 0 ) {
  28207. this.radius = radius;
  28208. this.phi = phi; // polar angle
  28209. this.theta = theta; // azimuthal angle
  28210. return this;
  28211. }
  28212. set( radius, phi, theta ) {
  28213. this.radius = radius;
  28214. this.phi = phi;
  28215. this.theta = theta;
  28216. return this;
  28217. }
  28218. copy( other ) {
  28219. this.radius = other.radius;
  28220. this.phi = other.phi;
  28221. this.theta = other.theta;
  28222. return this;
  28223. }
  28224. // restrict phi to be between EPS and PI-EPS
  28225. makeSafe() {
  28226. const EPS = 0.000001;
  28227. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28228. return this;
  28229. }
  28230. setFromVector3( v ) {
  28231. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28232. }
  28233. setFromCartesianCoords( x, y, z ) {
  28234. this.radius = Math.sqrt( x * x + y * y + z * z );
  28235. if ( this.radius === 0 ) {
  28236. this.theta = 0;
  28237. this.phi = 0;
  28238. } else {
  28239. this.theta = Math.atan2( x, z );
  28240. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28241. }
  28242. return this;
  28243. }
  28244. clone() {
  28245. return new this.constructor().copy( this );
  28246. }
  28247. }
  28248. /**
  28249. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28250. */
  28251. class Cylindrical {
  28252. constructor( radius = 1, theta = 0, y = 0 ) {
  28253. this.radius = radius; // distance from the origin to a point in the x-z plane
  28254. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28255. this.y = y; // height above the x-z plane
  28256. return this;
  28257. }
  28258. set( radius, theta, y ) {
  28259. this.radius = radius;
  28260. this.theta = theta;
  28261. this.y = y;
  28262. return this;
  28263. }
  28264. copy( other ) {
  28265. this.radius = other.radius;
  28266. this.theta = other.theta;
  28267. this.y = other.y;
  28268. return this;
  28269. }
  28270. setFromVector3( v ) {
  28271. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28272. }
  28273. setFromCartesianCoords( x, y, z ) {
  28274. this.radius = Math.sqrt( x * x + z * z );
  28275. this.theta = Math.atan2( x, z );
  28276. this.y = y;
  28277. return this;
  28278. }
  28279. clone() {
  28280. return new this.constructor().copy( this );
  28281. }
  28282. }
  28283. const _vector$4 = /*@__PURE__*/ new Vector2();
  28284. class Box2 {
  28285. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28286. this.isBox2 = true;
  28287. this.min = min;
  28288. this.max = max;
  28289. }
  28290. set( min, max ) {
  28291. this.min.copy( min );
  28292. this.max.copy( max );
  28293. return this;
  28294. }
  28295. setFromPoints( points ) {
  28296. this.makeEmpty();
  28297. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28298. this.expandByPoint( points[ i ] );
  28299. }
  28300. return this;
  28301. }
  28302. setFromCenterAndSize( center, size ) {
  28303. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28304. this.min.copy( center ).sub( halfSize );
  28305. this.max.copy( center ).add( halfSize );
  28306. return this;
  28307. }
  28308. clone() {
  28309. return new this.constructor().copy( this );
  28310. }
  28311. copy( box ) {
  28312. this.min.copy( box.min );
  28313. this.max.copy( box.max );
  28314. return this;
  28315. }
  28316. makeEmpty() {
  28317. this.min.x = this.min.y = + Infinity;
  28318. this.max.x = this.max.y = - Infinity;
  28319. return this;
  28320. }
  28321. isEmpty() {
  28322. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28323. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28324. }
  28325. getCenter( target ) {
  28326. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28327. }
  28328. getSize( target ) {
  28329. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28330. }
  28331. expandByPoint( point ) {
  28332. this.min.min( point );
  28333. this.max.max( point );
  28334. return this;
  28335. }
  28336. expandByVector( vector ) {
  28337. this.min.sub( vector );
  28338. this.max.add( vector );
  28339. return this;
  28340. }
  28341. expandByScalar( scalar ) {
  28342. this.min.addScalar( - scalar );
  28343. this.max.addScalar( scalar );
  28344. return this;
  28345. }
  28346. containsPoint( point ) {
  28347. return point.x < this.min.x || point.x > this.max.x ||
  28348. point.y < this.min.y || point.y > this.max.y ? false : true;
  28349. }
  28350. containsBox( box ) {
  28351. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28352. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28353. }
  28354. getParameter( point, target ) {
  28355. // This can potentially have a divide by zero if the box
  28356. // has a size dimension of 0.
  28357. return target.set(
  28358. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28359. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28360. );
  28361. }
  28362. intersectsBox( box ) {
  28363. // using 4 splitting planes to rule out intersections
  28364. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28365. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28366. }
  28367. clampPoint( point, target ) {
  28368. return target.copy( point ).clamp( this.min, this.max );
  28369. }
  28370. distanceToPoint( point ) {
  28371. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28372. return clampedPoint.sub( point ).length();
  28373. }
  28374. intersect( box ) {
  28375. this.min.max( box.min );
  28376. this.max.min( box.max );
  28377. return this;
  28378. }
  28379. union( box ) {
  28380. this.min.min( box.min );
  28381. this.max.max( box.max );
  28382. return this;
  28383. }
  28384. translate( offset ) {
  28385. this.min.add( offset );
  28386. this.max.add( offset );
  28387. return this;
  28388. }
  28389. equals( box ) {
  28390. return box.min.equals( this.min ) && box.max.equals( this.max );
  28391. }
  28392. }
  28393. const _startP = /*@__PURE__*/ new Vector3();
  28394. const _startEnd = /*@__PURE__*/ new Vector3();
  28395. class Line3 {
  28396. constructor( start = new Vector3(), end = new Vector3() ) {
  28397. this.start = start;
  28398. this.end = end;
  28399. }
  28400. set( start, end ) {
  28401. this.start.copy( start );
  28402. this.end.copy( end );
  28403. return this;
  28404. }
  28405. copy( line ) {
  28406. this.start.copy( line.start );
  28407. this.end.copy( line.end );
  28408. return this;
  28409. }
  28410. getCenter( target ) {
  28411. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28412. }
  28413. delta( target ) {
  28414. return target.subVectors( this.end, this.start );
  28415. }
  28416. distanceSq() {
  28417. return this.start.distanceToSquared( this.end );
  28418. }
  28419. distance() {
  28420. return this.start.distanceTo( this.end );
  28421. }
  28422. at( t, target ) {
  28423. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28424. }
  28425. closestPointToPointParameter( point, clampToLine ) {
  28426. _startP.subVectors( point, this.start );
  28427. _startEnd.subVectors( this.end, this.start );
  28428. const startEnd2 = _startEnd.dot( _startEnd );
  28429. const startEnd_startP = _startEnd.dot( _startP );
  28430. let t = startEnd_startP / startEnd2;
  28431. if ( clampToLine ) {
  28432. t = clamp( t, 0, 1 );
  28433. }
  28434. return t;
  28435. }
  28436. closestPointToPoint( point, clampToLine, target ) {
  28437. const t = this.closestPointToPointParameter( point, clampToLine );
  28438. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28439. }
  28440. applyMatrix4( matrix ) {
  28441. this.start.applyMatrix4( matrix );
  28442. this.end.applyMatrix4( matrix );
  28443. return this;
  28444. }
  28445. equals( line ) {
  28446. return line.start.equals( this.start ) && line.end.equals( this.end );
  28447. }
  28448. clone() {
  28449. return new this.constructor().copy( this );
  28450. }
  28451. }
  28452. const _vector$3 = /*@__PURE__*/ new Vector3();
  28453. class SpotLightHelper extends Object3D {
  28454. constructor( light, color ) {
  28455. super();
  28456. this.light = light;
  28457. this.matrix = light.matrixWorld;
  28458. this.matrixAutoUpdate = false;
  28459. this.color = color;
  28460. this.type = 'SpotLightHelper';
  28461. const geometry = new BufferGeometry();
  28462. const positions = [
  28463. 0, 0, 0, 0, 0, 1,
  28464. 0, 0, 0, 1, 0, 1,
  28465. 0, 0, 0, - 1, 0, 1,
  28466. 0, 0, 0, 0, 1, 1,
  28467. 0, 0, 0, 0, - 1, 1
  28468. ];
  28469. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28470. const p1 = ( i / l ) * Math.PI * 2;
  28471. const p2 = ( j / l ) * Math.PI * 2;
  28472. positions.push(
  28473. Math.cos( p1 ), Math.sin( p1 ), 1,
  28474. Math.cos( p2 ), Math.sin( p2 ), 1
  28475. );
  28476. }
  28477. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28478. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28479. this.cone = new LineSegments( geometry, material );
  28480. this.add( this.cone );
  28481. this.update();
  28482. }
  28483. dispose() {
  28484. this.cone.geometry.dispose();
  28485. this.cone.material.dispose();
  28486. }
  28487. update() {
  28488. this.light.updateWorldMatrix( true, false );
  28489. this.light.target.updateWorldMatrix( true, false );
  28490. const coneLength = this.light.distance ? this.light.distance : 1000;
  28491. const coneWidth = coneLength * Math.tan( this.light.angle );
  28492. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28493. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28494. this.cone.lookAt( _vector$3 );
  28495. if ( this.color !== undefined ) {
  28496. this.cone.material.color.set( this.color );
  28497. } else {
  28498. this.cone.material.color.copy( this.light.color );
  28499. }
  28500. }
  28501. }
  28502. const _vector$2 = /*@__PURE__*/ new Vector3();
  28503. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28504. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28505. class SkeletonHelper extends LineSegments {
  28506. constructor( object ) {
  28507. const bones = getBoneList( object );
  28508. const geometry = new BufferGeometry();
  28509. const vertices = [];
  28510. const colors = [];
  28511. const color1 = new Color( 0, 0, 1 );
  28512. const color2 = new Color( 0, 1, 0 );
  28513. for ( let i = 0; i < bones.length; i ++ ) {
  28514. const bone = bones[ i ];
  28515. if ( bone.parent && bone.parent.isBone ) {
  28516. vertices.push( 0, 0, 0 );
  28517. vertices.push( 0, 0, 0 );
  28518. colors.push( color1.r, color1.g, color1.b );
  28519. colors.push( color2.r, color2.g, color2.b );
  28520. }
  28521. }
  28522. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28523. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28524. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28525. super( geometry, material );
  28526. this.isSkeletonHelper = true;
  28527. this.type = 'SkeletonHelper';
  28528. this.root = object;
  28529. this.bones = bones;
  28530. this.matrix = object.matrixWorld;
  28531. this.matrixAutoUpdate = false;
  28532. }
  28533. updateMatrixWorld( force ) {
  28534. const bones = this.bones;
  28535. const geometry = this.geometry;
  28536. const position = geometry.getAttribute( 'position' );
  28537. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28538. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28539. const bone = bones[ i ];
  28540. if ( bone.parent && bone.parent.isBone ) {
  28541. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28542. _vector$2.setFromMatrixPosition( _boneMatrix );
  28543. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28544. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28545. _vector$2.setFromMatrixPosition( _boneMatrix );
  28546. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28547. j += 2;
  28548. }
  28549. }
  28550. geometry.getAttribute( 'position' ).needsUpdate = true;
  28551. super.updateMatrixWorld( force );
  28552. }
  28553. dispose() {
  28554. this.geometry.dispose();
  28555. this.material.dispose();
  28556. }
  28557. }
  28558. function getBoneList( object ) {
  28559. const boneList = [];
  28560. if ( object.isBone === true ) {
  28561. boneList.push( object );
  28562. }
  28563. for ( let i = 0; i < object.children.length; i ++ ) {
  28564. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28565. }
  28566. return boneList;
  28567. }
  28568. class PointLightHelper extends Mesh {
  28569. constructor( light, sphereSize, color ) {
  28570. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28571. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28572. super( geometry, material );
  28573. this.light = light;
  28574. this.color = color;
  28575. this.type = 'PointLightHelper';
  28576. this.matrix = this.light.matrixWorld;
  28577. this.matrixAutoUpdate = false;
  28578. this.update();
  28579. /*
  28580. // TODO: delete this comment?
  28581. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28582. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28583. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28584. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28585. const d = light.distance;
  28586. if ( d === 0.0 ) {
  28587. this.lightDistance.visible = false;
  28588. } else {
  28589. this.lightDistance.scale.set( d, d, d );
  28590. }
  28591. this.add( this.lightDistance );
  28592. */
  28593. }
  28594. dispose() {
  28595. this.geometry.dispose();
  28596. this.material.dispose();
  28597. }
  28598. update() {
  28599. this.light.updateWorldMatrix( true, false );
  28600. if ( this.color !== undefined ) {
  28601. this.material.color.set( this.color );
  28602. } else {
  28603. this.material.color.copy( this.light.color );
  28604. }
  28605. /*
  28606. const d = this.light.distance;
  28607. if ( d === 0.0 ) {
  28608. this.lightDistance.visible = false;
  28609. } else {
  28610. this.lightDistance.visible = true;
  28611. this.lightDistance.scale.set( d, d, d );
  28612. }
  28613. */
  28614. }
  28615. }
  28616. const _vector$1 = /*@__PURE__*/ new Vector3();
  28617. const _color1 = /*@__PURE__*/ new Color();
  28618. const _color2 = /*@__PURE__*/ new Color();
  28619. class HemisphereLightHelper extends Object3D {
  28620. constructor( light, size, color ) {
  28621. super();
  28622. this.light = light;
  28623. this.matrix = light.matrixWorld;
  28624. this.matrixAutoUpdate = false;
  28625. this.color = color;
  28626. this.type = 'HemisphereLightHelper';
  28627. const geometry = new OctahedronGeometry( size );
  28628. geometry.rotateY( Math.PI * 0.5 );
  28629. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28630. if ( this.color === undefined ) this.material.vertexColors = true;
  28631. const position = geometry.getAttribute( 'position' );
  28632. const colors = new Float32Array( position.count * 3 );
  28633. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28634. this.add( new Mesh( geometry, this.material ) );
  28635. this.update();
  28636. }
  28637. dispose() {
  28638. this.children[ 0 ].geometry.dispose();
  28639. this.children[ 0 ].material.dispose();
  28640. }
  28641. update() {
  28642. const mesh = this.children[ 0 ];
  28643. if ( this.color !== undefined ) {
  28644. this.material.color.set( this.color );
  28645. } else {
  28646. const colors = mesh.geometry.getAttribute( 'color' );
  28647. _color1.copy( this.light.color );
  28648. _color2.copy( this.light.groundColor );
  28649. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28650. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28651. colors.setXYZ( i, color.r, color.g, color.b );
  28652. }
  28653. colors.needsUpdate = true;
  28654. }
  28655. this.light.updateWorldMatrix( true, false );
  28656. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28657. }
  28658. }
  28659. class GridHelper extends LineSegments {
  28660. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28661. color1 = new Color( color1 );
  28662. color2 = new Color( color2 );
  28663. const center = divisions / 2;
  28664. const step = size / divisions;
  28665. const halfSize = size / 2;
  28666. const vertices = [], colors = [];
  28667. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28668. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28669. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28670. const color = i === center ? color1 : color2;
  28671. color.toArray( colors, j ); j += 3;
  28672. color.toArray( colors, j ); j += 3;
  28673. color.toArray( colors, j ); j += 3;
  28674. color.toArray( colors, j ); j += 3;
  28675. }
  28676. const geometry = new BufferGeometry();
  28677. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28678. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28679. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28680. super( geometry, material );
  28681. this.type = 'GridHelper';
  28682. }
  28683. dispose() {
  28684. this.geometry.dispose();
  28685. this.material.dispose();
  28686. }
  28687. }
  28688. class PolarGridHelper extends LineSegments {
  28689. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28690. color1 = new Color( color1 );
  28691. color2 = new Color( color2 );
  28692. const vertices = [];
  28693. const colors = [];
  28694. // create the sectors
  28695. if ( sectors > 1 ) {
  28696. for ( let i = 0; i < sectors; i ++ ) {
  28697. const v = ( i / sectors ) * ( Math.PI * 2 );
  28698. const x = Math.sin( v ) * radius;
  28699. const z = Math.cos( v ) * radius;
  28700. vertices.push( 0, 0, 0 );
  28701. vertices.push( x, 0, z );
  28702. const color = ( i & 1 ) ? color1 : color2;
  28703. colors.push( color.r, color.g, color.b );
  28704. colors.push( color.r, color.g, color.b );
  28705. }
  28706. }
  28707. // create the rings
  28708. for ( let i = 0; i < rings; i ++ ) {
  28709. const color = ( i & 1 ) ? color1 : color2;
  28710. const r = radius - ( radius / rings * i );
  28711. for ( let j = 0; j < divisions; j ++ ) {
  28712. // first vertex
  28713. let v = ( j / divisions ) * ( Math.PI * 2 );
  28714. let x = Math.sin( v ) * r;
  28715. let z = Math.cos( v ) * r;
  28716. vertices.push( x, 0, z );
  28717. colors.push( color.r, color.g, color.b );
  28718. // second vertex
  28719. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28720. x = Math.sin( v ) * r;
  28721. z = Math.cos( v ) * r;
  28722. vertices.push( x, 0, z );
  28723. colors.push( color.r, color.g, color.b );
  28724. }
  28725. }
  28726. const geometry = new BufferGeometry();
  28727. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28728. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28729. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28730. super( geometry, material );
  28731. this.type = 'PolarGridHelper';
  28732. }
  28733. dispose() {
  28734. this.geometry.dispose();
  28735. this.material.dispose();
  28736. }
  28737. }
  28738. const _v1 = /*@__PURE__*/ new Vector3();
  28739. const _v2 = /*@__PURE__*/ new Vector3();
  28740. const _v3 = /*@__PURE__*/ new Vector3();
  28741. class DirectionalLightHelper extends Object3D {
  28742. constructor( light, size, color ) {
  28743. super();
  28744. this.light = light;
  28745. this.matrix = light.matrixWorld;
  28746. this.matrixAutoUpdate = false;
  28747. this.color = color;
  28748. this.type = 'DirectionalLightHelper';
  28749. if ( size === undefined ) size = 1;
  28750. let geometry = new BufferGeometry();
  28751. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28752. - size, size, 0,
  28753. size, size, 0,
  28754. size, - size, 0,
  28755. - size, - size, 0,
  28756. - size, size, 0
  28757. ], 3 ) );
  28758. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28759. this.lightPlane = new Line( geometry, material );
  28760. this.add( this.lightPlane );
  28761. geometry = new BufferGeometry();
  28762. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28763. this.targetLine = new Line( geometry, material );
  28764. this.add( this.targetLine );
  28765. this.update();
  28766. }
  28767. dispose() {
  28768. this.lightPlane.geometry.dispose();
  28769. this.lightPlane.material.dispose();
  28770. this.targetLine.geometry.dispose();
  28771. this.targetLine.material.dispose();
  28772. }
  28773. update() {
  28774. this.light.updateWorldMatrix( true, false );
  28775. this.light.target.updateWorldMatrix( true, false );
  28776. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28777. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28778. _v3.subVectors( _v2, _v1 );
  28779. this.lightPlane.lookAt( _v2 );
  28780. if ( this.color !== undefined ) {
  28781. this.lightPlane.material.color.set( this.color );
  28782. this.targetLine.material.color.set( this.color );
  28783. } else {
  28784. this.lightPlane.material.color.copy( this.light.color );
  28785. this.targetLine.material.color.copy( this.light.color );
  28786. }
  28787. this.targetLine.lookAt( _v2 );
  28788. this.targetLine.scale.z = _v3.length();
  28789. }
  28790. }
  28791. const _vector = /*@__PURE__*/ new Vector3();
  28792. const _camera = /*@__PURE__*/ new Camera();
  28793. /**
  28794. * - shows frustum, line of sight and up of the camera
  28795. * - suitable for fast updates
  28796. * - based on frustum visualization in lightgl.js shadowmap example
  28797. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28798. */
  28799. class CameraHelper extends LineSegments {
  28800. constructor( camera ) {
  28801. const geometry = new BufferGeometry();
  28802. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28803. const vertices = [];
  28804. const colors = [];
  28805. const pointMap = {};
  28806. // near
  28807. addLine( 'n1', 'n2' );
  28808. addLine( 'n2', 'n4' );
  28809. addLine( 'n4', 'n3' );
  28810. addLine( 'n3', 'n1' );
  28811. // far
  28812. addLine( 'f1', 'f2' );
  28813. addLine( 'f2', 'f4' );
  28814. addLine( 'f4', 'f3' );
  28815. addLine( 'f3', 'f1' );
  28816. // sides
  28817. addLine( 'n1', 'f1' );
  28818. addLine( 'n2', 'f2' );
  28819. addLine( 'n3', 'f3' );
  28820. addLine( 'n4', 'f4' );
  28821. // cone
  28822. addLine( 'p', 'n1' );
  28823. addLine( 'p', 'n2' );
  28824. addLine( 'p', 'n3' );
  28825. addLine( 'p', 'n4' );
  28826. // up
  28827. addLine( 'u1', 'u2' );
  28828. addLine( 'u2', 'u3' );
  28829. addLine( 'u3', 'u1' );
  28830. // target
  28831. addLine( 'c', 't' );
  28832. addLine( 'p', 'c' );
  28833. // cross
  28834. addLine( 'cn1', 'cn2' );
  28835. addLine( 'cn3', 'cn4' );
  28836. addLine( 'cf1', 'cf2' );
  28837. addLine( 'cf3', 'cf4' );
  28838. function addLine( a, b ) {
  28839. addPoint( a );
  28840. addPoint( b );
  28841. }
  28842. function addPoint( id ) {
  28843. vertices.push( 0, 0, 0 );
  28844. colors.push( 0, 0, 0 );
  28845. if ( pointMap[ id ] === undefined ) {
  28846. pointMap[ id ] = [];
  28847. }
  28848. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28849. }
  28850. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28851. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28852. super( geometry, material );
  28853. this.type = 'CameraHelper';
  28854. this.camera = camera;
  28855. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28856. this.matrix = camera.matrixWorld;
  28857. this.matrixAutoUpdate = false;
  28858. this.pointMap = pointMap;
  28859. this.update();
  28860. // colors
  28861. const colorFrustum = new Color( 0xffaa00 );
  28862. const colorCone = new Color( 0xff0000 );
  28863. const colorUp = new Color( 0x00aaff );
  28864. const colorTarget = new Color( 0xffffff );
  28865. const colorCross = new Color( 0x333333 );
  28866. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28867. }
  28868. setColors( frustum, cone, up, target, cross ) {
  28869. const geometry = this.geometry;
  28870. const colorAttribute = geometry.getAttribute( 'color' );
  28871. // near
  28872. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  28873. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  28874. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  28875. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  28876. // far
  28877. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  28878. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  28879. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  28880. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  28881. // sides
  28882. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  28883. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  28884. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  28885. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  28886. // cone
  28887. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  28888. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  28889. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  28890. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  28891. // up
  28892. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  28893. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  28894. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  28895. // target
  28896. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  28897. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  28898. // cross
  28899. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  28900. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  28901. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  28902. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  28903. colorAttribute.needsUpdate = true;
  28904. }
  28905. update() {
  28906. const geometry = this.geometry;
  28907. const pointMap = this.pointMap;
  28908. const w = 1, h = 1;
  28909. // we need just camera projection matrix inverse
  28910. // world matrix must be identity
  28911. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28912. // center / target
  28913. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28914. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28915. // near
  28916. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28917. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28918. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28919. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28920. // far
  28921. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28922. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28923. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28924. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28925. // up
  28926. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28927. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28928. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28929. // cross
  28930. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28931. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28932. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28933. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28934. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28935. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28936. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28937. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28938. geometry.getAttribute( 'position' ).needsUpdate = true;
  28939. }
  28940. dispose() {
  28941. this.geometry.dispose();
  28942. this.material.dispose();
  28943. }
  28944. }
  28945. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28946. _vector.set( x, y, z ).unproject( camera );
  28947. const points = pointMap[ point ];
  28948. if ( points !== undefined ) {
  28949. const position = geometry.getAttribute( 'position' );
  28950. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28951. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28952. }
  28953. }
  28954. }
  28955. const _box = /*@__PURE__*/ new Box3();
  28956. class BoxHelper extends LineSegments {
  28957. constructor( object, color = 0xffff00 ) {
  28958. 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 ] );
  28959. const positions = new Float32Array( 8 * 3 );
  28960. const geometry = new BufferGeometry();
  28961. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28962. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28963. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28964. this.object = object;
  28965. this.type = 'BoxHelper';
  28966. this.matrixAutoUpdate = false;
  28967. this.update();
  28968. }
  28969. update( object ) {
  28970. if ( object !== undefined ) {
  28971. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28972. }
  28973. if ( this.object !== undefined ) {
  28974. _box.setFromObject( this.object );
  28975. }
  28976. if ( _box.isEmpty() ) return;
  28977. const min = _box.min;
  28978. const max = _box.max;
  28979. /*
  28980. 5____4
  28981. 1/___0/|
  28982. | 6__|_7
  28983. 2/___3/
  28984. 0: max.x, max.y, max.z
  28985. 1: min.x, max.y, max.z
  28986. 2: min.x, min.y, max.z
  28987. 3: max.x, min.y, max.z
  28988. 4: max.x, max.y, min.z
  28989. 5: min.x, max.y, min.z
  28990. 6: min.x, min.y, min.z
  28991. 7: max.x, min.y, min.z
  28992. */
  28993. const position = this.geometry.attributes.position;
  28994. const array = position.array;
  28995. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28996. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28997. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28998. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28999. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29000. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29001. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29002. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29003. position.needsUpdate = true;
  29004. this.geometry.computeBoundingSphere();
  29005. }
  29006. setFromObject( object ) {
  29007. this.object = object;
  29008. this.update();
  29009. return this;
  29010. }
  29011. copy( source, recursive ) {
  29012. super.copy( source, recursive );
  29013. this.object = source.object;
  29014. return this;
  29015. }
  29016. dispose() {
  29017. this.geometry.dispose();
  29018. this.material.dispose();
  29019. }
  29020. }
  29021. class Box3Helper extends LineSegments {
  29022. constructor( box, color = 0xffff00 ) {
  29023. 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 ] );
  29024. 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 ];
  29025. const geometry = new BufferGeometry();
  29026. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29027. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29028. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29029. this.box = box;
  29030. this.type = 'Box3Helper';
  29031. this.geometry.computeBoundingSphere();
  29032. }
  29033. updateMatrixWorld( force ) {
  29034. const box = this.box;
  29035. if ( box.isEmpty() ) return;
  29036. box.getCenter( this.position );
  29037. box.getSize( this.scale );
  29038. this.scale.multiplyScalar( 0.5 );
  29039. super.updateMatrixWorld( force );
  29040. }
  29041. dispose() {
  29042. this.geometry.dispose();
  29043. this.material.dispose();
  29044. }
  29045. }
  29046. class PlaneHelper extends Line {
  29047. constructor( plane, size = 1, hex = 0xffff00 ) {
  29048. const color = hex;
  29049. 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 ];
  29050. const geometry = new BufferGeometry();
  29051. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29052. geometry.computeBoundingSphere();
  29053. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29054. this.type = 'PlaneHelper';
  29055. this.plane = plane;
  29056. this.size = size;
  29057. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29058. const geometry2 = new BufferGeometry();
  29059. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29060. geometry2.computeBoundingSphere();
  29061. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29062. }
  29063. updateMatrixWorld( force ) {
  29064. this.position.set( 0, 0, 0 );
  29065. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29066. this.lookAt( this.plane.normal );
  29067. this.translateZ( - this.plane.constant );
  29068. super.updateMatrixWorld( force );
  29069. }
  29070. dispose() {
  29071. this.geometry.dispose();
  29072. this.material.dispose();
  29073. this.children[ 0 ].geometry.dispose();
  29074. this.children[ 0 ].material.dispose();
  29075. }
  29076. }
  29077. const _axis = /*@__PURE__*/ new Vector3();
  29078. let _lineGeometry, _coneGeometry;
  29079. class ArrowHelper extends Object3D {
  29080. // dir is assumed to be normalized
  29081. 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 ) {
  29082. super();
  29083. this.type = 'ArrowHelper';
  29084. if ( _lineGeometry === undefined ) {
  29085. _lineGeometry = new BufferGeometry();
  29086. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29087. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29088. _coneGeometry.translate( 0, - 0.5, 0 );
  29089. }
  29090. this.position.copy( origin );
  29091. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29092. this.line.matrixAutoUpdate = false;
  29093. this.add( this.line );
  29094. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29095. this.cone.matrixAutoUpdate = false;
  29096. this.add( this.cone );
  29097. this.setDirection( dir );
  29098. this.setLength( length, headLength, headWidth );
  29099. }
  29100. setDirection( dir ) {
  29101. // dir is assumed to be normalized
  29102. if ( dir.y > 0.99999 ) {
  29103. this.quaternion.set( 0, 0, 0, 1 );
  29104. } else if ( dir.y < - 0.99999 ) {
  29105. this.quaternion.set( 1, 0, 0, 0 );
  29106. } else {
  29107. _axis.set( dir.z, 0, - dir.x ).normalize();
  29108. const radians = Math.acos( dir.y );
  29109. this.quaternion.setFromAxisAngle( _axis, radians );
  29110. }
  29111. }
  29112. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29113. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29114. this.line.updateMatrix();
  29115. this.cone.scale.set( headWidth, headLength, headWidth );
  29116. this.cone.position.y = length;
  29117. this.cone.updateMatrix();
  29118. }
  29119. setColor( color ) {
  29120. this.line.material.color.set( color );
  29121. this.cone.material.color.set( color );
  29122. }
  29123. copy( source ) {
  29124. super.copy( source, false );
  29125. this.line.copy( source.line );
  29126. this.cone.copy( source.cone );
  29127. return this;
  29128. }
  29129. dispose() {
  29130. this.line.geometry.dispose();
  29131. this.line.material.dispose();
  29132. this.cone.geometry.dispose();
  29133. this.cone.material.dispose();
  29134. }
  29135. }
  29136. class AxesHelper extends LineSegments {
  29137. constructor( size = 1 ) {
  29138. const vertices = [
  29139. 0, 0, 0, size, 0, 0,
  29140. 0, 0, 0, 0, size, 0,
  29141. 0, 0, 0, 0, 0, size
  29142. ];
  29143. const colors = [
  29144. 1, 0, 0, 1, 0.6, 0,
  29145. 0, 1, 0, 0.6, 1, 0,
  29146. 0, 0, 1, 0, 0.6, 1
  29147. ];
  29148. const geometry = new BufferGeometry();
  29149. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29150. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29151. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29152. super( geometry, material );
  29153. this.type = 'AxesHelper';
  29154. }
  29155. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29156. const color = new Color();
  29157. const array = this.geometry.attributes.color.array;
  29158. color.set( xAxisColor );
  29159. color.toArray( array, 0 );
  29160. color.toArray( array, 3 );
  29161. color.set( yAxisColor );
  29162. color.toArray( array, 6 );
  29163. color.toArray( array, 9 );
  29164. color.set( zAxisColor );
  29165. color.toArray( array, 12 );
  29166. color.toArray( array, 15 );
  29167. this.geometry.attributes.color.needsUpdate = true;
  29168. return this;
  29169. }
  29170. dispose() {
  29171. this.geometry.dispose();
  29172. this.material.dispose();
  29173. }
  29174. }
  29175. class ShapePath {
  29176. constructor() {
  29177. this.type = 'ShapePath';
  29178. this.color = new Color();
  29179. this.subPaths = [];
  29180. this.currentPath = null;
  29181. }
  29182. moveTo( x, y ) {
  29183. this.currentPath = new Path();
  29184. this.subPaths.push( this.currentPath );
  29185. this.currentPath.moveTo( x, y );
  29186. return this;
  29187. }
  29188. lineTo( x, y ) {
  29189. this.currentPath.lineTo( x, y );
  29190. return this;
  29191. }
  29192. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29193. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29194. return this;
  29195. }
  29196. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29197. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29198. return this;
  29199. }
  29200. splineThru( pts ) {
  29201. this.currentPath.splineThru( pts );
  29202. return this;
  29203. }
  29204. toShapes( isCCW ) {
  29205. function toShapesNoHoles( inSubpaths ) {
  29206. const shapes = [];
  29207. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29208. const tmpPath = inSubpaths[ i ];
  29209. const tmpShape = new Shape();
  29210. tmpShape.curves = tmpPath.curves;
  29211. shapes.push( tmpShape );
  29212. }
  29213. return shapes;
  29214. }
  29215. function isPointInsidePolygon( inPt, inPolygon ) {
  29216. const polyLen = inPolygon.length;
  29217. // inPt on polygon contour => immediate success or
  29218. // toggling of inside/outside at every single! intersection point of an edge
  29219. // with the horizontal line through inPt, left of inPt
  29220. // not counting lowerY endpoints of edges and whole edges on that line
  29221. let inside = false;
  29222. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29223. let edgeLowPt = inPolygon[ p ];
  29224. let edgeHighPt = inPolygon[ q ];
  29225. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29226. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29227. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29228. // not parallel
  29229. if ( edgeDy < 0 ) {
  29230. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29231. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29232. }
  29233. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29234. if ( inPt.y === edgeLowPt.y ) {
  29235. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29236. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29237. } else {
  29238. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29239. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29240. if ( perpEdge < 0 ) continue;
  29241. inside = ! inside; // true intersection left of inPt
  29242. }
  29243. } else {
  29244. // parallel or collinear
  29245. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29246. // edge lies on the same horizontal line as inPt
  29247. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29248. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29249. // continue;
  29250. }
  29251. }
  29252. return inside;
  29253. }
  29254. const isClockWise = ShapeUtils.isClockWise;
  29255. const subPaths = this.subPaths;
  29256. if ( subPaths.length === 0 ) return [];
  29257. let solid, tmpPath, tmpShape;
  29258. const shapes = [];
  29259. if ( subPaths.length === 1 ) {
  29260. tmpPath = subPaths[ 0 ];
  29261. tmpShape = new Shape();
  29262. tmpShape.curves = tmpPath.curves;
  29263. shapes.push( tmpShape );
  29264. return shapes;
  29265. }
  29266. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29267. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29268. // console.log("Holes first", holesFirst);
  29269. const betterShapeHoles = [];
  29270. const newShapes = [];
  29271. let newShapeHoles = [];
  29272. let mainIdx = 0;
  29273. let tmpPoints;
  29274. newShapes[ mainIdx ] = undefined;
  29275. newShapeHoles[ mainIdx ] = [];
  29276. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29277. tmpPath = subPaths[ i ];
  29278. tmpPoints = tmpPath.getPoints();
  29279. solid = isClockWise( tmpPoints );
  29280. solid = isCCW ? ! solid : solid;
  29281. if ( solid ) {
  29282. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29283. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29284. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29285. if ( holesFirst ) mainIdx ++;
  29286. newShapeHoles[ mainIdx ] = [];
  29287. //console.log('cw', i);
  29288. } else {
  29289. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29290. //console.log('ccw', i);
  29291. }
  29292. }
  29293. // only Holes? -> probably all Shapes with wrong orientation
  29294. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29295. if ( newShapes.length > 1 ) {
  29296. let ambiguous = false;
  29297. let toChange = 0;
  29298. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29299. betterShapeHoles[ sIdx ] = [];
  29300. }
  29301. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29302. const sho = newShapeHoles[ sIdx ];
  29303. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29304. const ho = sho[ hIdx ];
  29305. let hole_unassigned = true;
  29306. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29307. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29308. if ( sIdx !== s2Idx ) toChange ++;
  29309. if ( hole_unassigned ) {
  29310. hole_unassigned = false;
  29311. betterShapeHoles[ s2Idx ].push( ho );
  29312. } else {
  29313. ambiguous = true;
  29314. }
  29315. }
  29316. }
  29317. if ( hole_unassigned ) {
  29318. betterShapeHoles[ sIdx ].push( ho );
  29319. }
  29320. }
  29321. }
  29322. if ( toChange > 0 && ambiguous === false ) {
  29323. newShapeHoles = betterShapeHoles;
  29324. }
  29325. }
  29326. let tmpHoles;
  29327. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29328. tmpShape = newShapes[ i ].s;
  29329. shapes.push( tmpShape );
  29330. tmpHoles = newShapeHoles[ i ];
  29331. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29332. tmpShape.holes.push( tmpHoles[ j ].h );
  29333. }
  29334. }
  29335. //console.log("shape", shapes);
  29336. return shapes;
  29337. }
  29338. }
  29339. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29340. const _tables = /*@__PURE__*/ _generateTables();
  29341. function _generateTables() {
  29342. // float32 to float16 helpers
  29343. const buffer = new ArrayBuffer( 4 );
  29344. const floatView = new Float32Array( buffer );
  29345. const uint32View = new Uint32Array( buffer );
  29346. const baseTable = new Uint32Array( 512 );
  29347. const shiftTable = new Uint32Array( 512 );
  29348. for ( let i = 0; i < 256; ++ i ) {
  29349. const e = i - 127;
  29350. // very small number (0, -0)
  29351. if ( e < - 27 ) {
  29352. baseTable[ i ] = 0x0000;
  29353. baseTable[ i | 0x100 ] = 0x8000;
  29354. shiftTable[ i ] = 24;
  29355. shiftTable[ i | 0x100 ] = 24;
  29356. // small number (denorm)
  29357. } else if ( e < - 14 ) {
  29358. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29359. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29360. shiftTable[ i ] = - e - 1;
  29361. shiftTable[ i | 0x100 ] = - e - 1;
  29362. // normal number
  29363. } else if ( e <= 15 ) {
  29364. baseTable[ i ] = ( e + 15 ) << 10;
  29365. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29366. shiftTable[ i ] = 13;
  29367. shiftTable[ i | 0x100 ] = 13;
  29368. // large number (Infinity, -Infinity)
  29369. } else if ( e < 128 ) {
  29370. baseTable[ i ] = 0x7c00;
  29371. baseTable[ i | 0x100 ] = 0xfc00;
  29372. shiftTable[ i ] = 24;
  29373. shiftTable[ i | 0x100 ] = 24;
  29374. // stay (NaN, Infinity, -Infinity)
  29375. } else {
  29376. baseTable[ i ] = 0x7c00;
  29377. baseTable[ i | 0x100 ] = 0xfc00;
  29378. shiftTable[ i ] = 13;
  29379. shiftTable[ i | 0x100 ] = 13;
  29380. }
  29381. }
  29382. // float16 to float32 helpers
  29383. const mantissaTable = new Uint32Array( 2048 );
  29384. const exponentTable = new Uint32Array( 64 );
  29385. const offsetTable = new Uint32Array( 64 );
  29386. for ( let i = 1; i < 1024; ++ i ) {
  29387. let m = i << 13; // zero pad mantissa bits
  29388. let e = 0; // zero exponent
  29389. // normalized
  29390. while ( ( m & 0x00800000 ) === 0 ) {
  29391. m <<= 1;
  29392. e -= 0x00800000; // decrement exponent
  29393. }
  29394. m &= ~ 0x00800000; // clear leading 1 bit
  29395. e += 0x38800000; // adjust bias
  29396. mantissaTable[ i ] = m | e;
  29397. }
  29398. for ( let i = 1024; i < 2048; ++ i ) {
  29399. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29400. }
  29401. for ( let i = 1; i < 31; ++ i ) {
  29402. exponentTable[ i ] = i << 23;
  29403. }
  29404. exponentTable[ 31 ] = 0x47800000;
  29405. exponentTable[ 32 ] = 0x80000000;
  29406. for ( let i = 33; i < 63; ++ i ) {
  29407. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29408. }
  29409. exponentTable[ 63 ] = 0xc7800000;
  29410. for ( let i = 1; i < 64; ++ i ) {
  29411. if ( i !== 32 ) {
  29412. offsetTable[ i ] = 1024;
  29413. }
  29414. }
  29415. return {
  29416. floatView: floatView,
  29417. uint32View: uint32View,
  29418. baseTable: baseTable,
  29419. shiftTable: shiftTable,
  29420. mantissaTable: mantissaTable,
  29421. exponentTable: exponentTable,
  29422. offsetTable: offsetTable
  29423. };
  29424. }
  29425. // float32 to float16
  29426. function toHalfFloat( val ) {
  29427. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29428. val = clamp( val, - 65504, 65504 );
  29429. _tables.floatView[ 0 ] = val;
  29430. const f = _tables.uint32View[ 0 ];
  29431. const e = ( f >> 23 ) & 0x1ff;
  29432. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29433. }
  29434. // float16 to float32
  29435. function fromHalfFloat( val ) {
  29436. const m = val >> 10;
  29437. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29438. return _tables.floatView[ 0 ];
  29439. }
  29440. var DataUtils = /*#__PURE__*/Object.freeze({
  29441. __proto__: null,
  29442. fromHalfFloat: fromHalfFloat,
  29443. toHalfFloat: toHalfFloat
  29444. });
  29445. // r144
  29446. class BoxBufferGeometry extends BoxGeometry {
  29447. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29448. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29449. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29450. }
  29451. }
  29452. // r144
  29453. class CapsuleBufferGeometry extends CapsuleGeometry {
  29454. constructor( radius, length, capSegments, radialSegments ) {
  29455. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29456. super( radius, length, capSegments, radialSegments );
  29457. }
  29458. }
  29459. // r144
  29460. class CircleBufferGeometry extends CircleGeometry {
  29461. constructor( radius, segments, thetaStart, thetaLength ) {
  29462. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29463. super( radius, segments, thetaStart, thetaLength );
  29464. }
  29465. }
  29466. // r144
  29467. class ConeBufferGeometry extends ConeGeometry {
  29468. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29469. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29470. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29471. }
  29472. }
  29473. // r144
  29474. class CylinderBufferGeometry extends CylinderGeometry {
  29475. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29476. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29477. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29478. }
  29479. }
  29480. // r144
  29481. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29482. constructor( radius, detail ) {
  29483. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29484. super( radius, detail );
  29485. }
  29486. }
  29487. // r144
  29488. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29489. constructor( shapes, options ) {
  29490. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29491. super( shapes, options );
  29492. }
  29493. }
  29494. // r144
  29495. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29496. constructor( radius, detail ) {
  29497. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29498. super( radius, detail );
  29499. }
  29500. }
  29501. // r144
  29502. class LatheBufferGeometry extends LatheGeometry {
  29503. constructor( points, segments, phiStart, phiLength ) {
  29504. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29505. super( points, segments, phiStart, phiLength );
  29506. }
  29507. }
  29508. // r144
  29509. class OctahedronBufferGeometry extends OctahedronGeometry {
  29510. constructor( radius, detail ) {
  29511. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29512. super( radius, detail );
  29513. }
  29514. }
  29515. // r144
  29516. class PlaneBufferGeometry extends PlaneGeometry {
  29517. constructor( width, height, widthSegments, heightSegments ) {
  29518. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29519. super( width, height, widthSegments, heightSegments );
  29520. }
  29521. }
  29522. // r144
  29523. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29524. constructor( vertices, indices, radius, detail ) {
  29525. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29526. super( vertices, indices, radius, detail );
  29527. }
  29528. }
  29529. // r144
  29530. class RingBufferGeometry extends RingGeometry {
  29531. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29532. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29533. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29534. }
  29535. }
  29536. // r144
  29537. class ShapeBufferGeometry extends ShapeGeometry {
  29538. constructor( shapes, curveSegments ) {
  29539. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29540. super( shapes, curveSegments );
  29541. }
  29542. }
  29543. // r144
  29544. class SphereBufferGeometry extends SphereGeometry {
  29545. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29546. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29547. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29548. }
  29549. }
  29550. // r144
  29551. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29552. constructor( radius, detail ) {
  29553. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29554. super( radius, detail );
  29555. }
  29556. }
  29557. // r144
  29558. class TorusBufferGeometry extends TorusGeometry {
  29559. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29560. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29561. super( radius, tube, radialSegments, tubularSegments, arc );
  29562. }
  29563. }
  29564. // r144
  29565. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29566. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29567. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29568. super( radius, tube, tubularSegments, radialSegments, p, q );
  29569. }
  29570. }
  29571. // r144
  29572. class TubeBufferGeometry extends TubeGeometry {
  29573. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29574. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29575. super( path, tubularSegments, radius, radialSegments, closed );
  29576. }
  29577. }
  29578. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29579. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29580. revision: REVISION,
  29581. } } ) );
  29582. }
  29583. if ( typeof window !== 'undefined' ) {
  29584. if ( window.__THREE__ ) {
  29585. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29586. } else {
  29587. window.__THREE__ = REVISION;
  29588. }
  29589. }
  29590. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29591. exports.AddEquation = AddEquation;
  29592. exports.AddOperation = AddOperation;
  29593. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29594. exports.AdditiveBlending = AdditiveBlending;
  29595. exports.AlphaFormat = AlphaFormat;
  29596. exports.AlwaysDepth = AlwaysDepth;
  29597. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29598. exports.AmbientLight = AmbientLight;
  29599. exports.AmbientLightProbe = AmbientLightProbe;
  29600. exports.AnimationClip = AnimationClip;
  29601. exports.AnimationLoader = AnimationLoader;
  29602. exports.AnimationMixer = AnimationMixer;
  29603. exports.AnimationObjectGroup = AnimationObjectGroup;
  29604. exports.AnimationUtils = AnimationUtils;
  29605. exports.ArcCurve = ArcCurve;
  29606. exports.ArrayCamera = ArrayCamera;
  29607. exports.ArrowHelper = ArrowHelper;
  29608. exports.Audio = Audio;
  29609. exports.AudioAnalyser = AudioAnalyser;
  29610. exports.AudioContext = AudioContext;
  29611. exports.AudioListener = AudioListener;
  29612. exports.AudioLoader = AudioLoader;
  29613. exports.AxesHelper = AxesHelper;
  29614. exports.BackSide = BackSide;
  29615. exports.BasicDepthPacking = BasicDepthPacking;
  29616. exports.BasicShadowMap = BasicShadowMap;
  29617. exports.Bone = Bone;
  29618. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29619. exports.Box2 = Box2;
  29620. exports.Box3 = Box3;
  29621. exports.Box3Helper = Box3Helper;
  29622. exports.BoxBufferGeometry = BoxBufferGeometry;
  29623. exports.BoxGeometry = BoxGeometry;
  29624. exports.BoxHelper = BoxHelper;
  29625. exports.BufferAttribute = BufferAttribute;
  29626. exports.BufferGeometry = BufferGeometry;
  29627. exports.BufferGeometryLoader = BufferGeometryLoader;
  29628. exports.ByteType = ByteType;
  29629. exports.Cache = Cache;
  29630. exports.Camera = Camera;
  29631. exports.CameraHelper = CameraHelper;
  29632. exports.CanvasTexture = CanvasTexture;
  29633. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  29634. exports.CapsuleGeometry = CapsuleGeometry;
  29635. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29636. exports.CineonToneMapping = CineonToneMapping;
  29637. exports.CircleBufferGeometry = CircleBufferGeometry;
  29638. exports.CircleGeometry = CircleGeometry;
  29639. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29640. exports.Clock = Clock;
  29641. exports.Color = Color;
  29642. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29643. exports.ColorManagement = ColorManagement;
  29644. exports.CompressedArrayTexture = CompressedArrayTexture;
  29645. exports.CompressedTexture = CompressedTexture;
  29646. exports.CompressedTextureLoader = CompressedTextureLoader;
  29647. exports.ConeBufferGeometry = ConeBufferGeometry;
  29648. exports.ConeGeometry = ConeGeometry;
  29649. exports.CubeCamera = CubeCamera;
  29650. exports.CubeReflectionMapping = CubeReflectionMapping;
  29651. exports.CubeRefractionMapping = CubeRefractionMapping;
  29652. exports.CubeTexture = CubeTexture;
  29653. exports.CubeTextureLoader = CubeTextureLoader;
  29654. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29655. exports.CubicBezierCurve = CubicBezierCurve;
  29656. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29657. exports.CubicInterpolant = CubicInterpolant;
  29658. exports.CullFaceBack = CullFaceBack;
  29659. exports.CullFaceFront = CullFaceFront;
  29660. exports.CullFaceFrontBack = CullFaceFrontBack;
  29661. exports.CullFaceNone = CullFaceNone;
  29662. exports.Curve = Curve;
  29663. exports.CurvePath = CurvePath;
  29664. exports.CustomBlending = CustomBlending;
  29665. exports.CustomToneMapping = CustomToneMapping;
  29666. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  29667. exports.CylinderGeometry = CylinderGeometry;
  29668. exports.Cylindrical = Cylindrical;
  29669. exports.Data3DTexture = Data3DTexture;
  29670. exports.DataArrayTexture = DataArrayTexture;
  29671. exports.DataTexture = DataTexture;
  29672. exports.DataTextureLoader = DataTextureLoader;
  29673. exports.DataUtils = DataUtils;
  29674. exports.DecrementStencilOp = DecrementStencilOp;
  29675. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29676. exports.DefaultLoadingManager = DefaultLoadingManager;
  29677. exports.DepthFormat = DepthFormat;
  29678. exports.DepthStencilFormat = DepthStencilFormat;
  29679. exports.DepthTexture = DepthTexture;
  29680. exports.DirectionalLight = DirectionalLight;
  29681. exports.DirectionalLightHelper = DirectionalLightHelper;
  29682. exports.DiscreteInterpolant = DiscreteInterpolant;
  29683. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  29684. exports.DodecahedronGeometry = DodecahedronGeometry;
  29685. exports.DoubleSide = DoubleSide;
  29686. exports.DstAlphaFactor = DstAlphaFactor;
  29687. exports.DstColorFactor = DstColorFactor;
  29688. exports.DynamicCopyUsage = DynamicCopyUsage;
  29689. exports.DynamicDrawUsage = DynamicDrawUsage;
  29690. exports.DynamicReadUsage = DynamicReadUsage;
  29691. exports.EdgesGeometry = EdgesGeometry;
  29692. exports.EllipseCurve = EllipseCurve;
  29693. exports.EqualDepth = EqualDepth;
  29694. exports.EqualStencilFunc = EqualStencilFunc;
  29695. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29696. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29697. exports.Euler = Euler;
  29698. exports.EventDispatcher = EventDispatcher;
  29699. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  29700. exports.ExtrudeGeometry = ExtrudeGeometry;
  29701. exports.FileLoader = FileLoader;
  29702. exports.Float16BufferAttribute = Float16BufferAttribute;
  29703. exports.Float32BufferAttribute = Float32BufferAttribute;
  29704. exports.Float64BufferAttribute = Float64BufferAttribute;
  29705. exports.FloatType = FloatType;
  29706. exports.Fog = Fog;
  29707. exports.FogExp2 = FogExp2;
  29708. exports.FramebufferTexture = FramebufferTexture;
  29709. exports.FrontSide = FrontSide;
  29710. exports.Frustum = Frustum;
  29711. exports.GLBufferAttribute = GLBufferAttribute;
  29712. exports.GLSL1 = GLSL1;
  29713. exports.GLSL3 = GLSL3;
  29714. exports.GreaterDepth = GreaterDepth;
  29715. exports.GreaterEqualDepth = GreaterEqualDepth;
  29716. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29717. exports.GreaterStencilFunc = GreaterStencilFunc;
  29718. exports.GridHelper = GridHelper;
  29719. exports.Group = Group;
  29720. exports.HalfFloatType = HalfFloatType;
  29721. exports.HemisphereLight = HemisphereLight;
  29722. exports.HemisphereLightHelper = HemisphereLightHelper;
  29723. exports.HemisphereLightProbe = HemisphereLightProbe;
  29724. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  29725. exports.IcosahedronGeometry = IcosahedronGeometry;
  29726. exports.ImageBitmapLoader = ImageBitmapLoader;
  29727. exports.ImageLoader = ImageLoader;
  29728. exports.ImageUtils = ImageUtils;
  29729. exports.IncrementStencilOp = IncrementStencilOp;
  29730. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29731. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29732. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29733. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29734. exports.InstancedMesh = InstancedMesh;
  29735. exports.Int16BufferAttribute = Int16BufferAttribute;
  29736. exports.Int32BufferAttribute = Int32BufferAttribute;
  29737. exports.Int8BufferAttribute = Int8BufferAttribute;
  29738. exports.IntType = IntType;
  29739. exports.InterleavedBuffer = InterleavedBuffer;
  29740. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29741. exports.Interpolant = Interpolant;
  29742. exports.InterpolateDiscrete = InterpolateDiscrete;
  29743. exports.InterpolateLinear = InterpolateLinear;
  29744. exports.InterpolateSmooth = InterpolateSmooth;
  29745. exports.InvertStencilOp = InvertStencilOp;
  29746. exports.KeepStencilOp = KeepStencilOp;
  29747. exports.KeyframeTrack = KeyframeTrack;
  29748. exports.LOD = LOD;
  29749. exports.LatheBufferGeometry = LatheBufferGeometry;
  29750. exports.LatheGeometry = LatheGeometry;
  29751. exports.Layers = Layers;
  29752. exports.LessDepth = LessDepth;
  29753. exports.LessEqualDepth = LessEqualDepth;
  29754. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29755. exports.LessStencilFunc = LessStencilFunc;
  29756. exports.Light = Light;
  29757. exports.LightProbe = LightProbe;
  29758. exports.Line = Line;
  29759. exports.Line3 = Line3;
  29760. exports.LineBasicMaterial = LineBasicMaterial;
  29761. exports.LineCurve = LineCurve;
  29762. exports.LineCurve3 = LineCurve3;
  29763. exports.LineDashedMaterial = LineDashedMaterial;
  29764. exports.LineLoop = LineLoop;
  29765. exports.LineSegments = LineSegments;
  29766. exports.LinearEncoding = LinearEncoding;
  29767. exports.LinearFilter = LinearFilter;
  29768. exports.LinearInterpolant = LinearInterpolant;
  29769. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29770. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29771. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29772. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29773. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  29774. exports.LinearToneMapping = LinearToneMapping;
  29775. exports.Loader = Loader;
  29776. exports.LoaderUtils = LoaderUtils;
  29777. exports.LoadingManager = LoadingManager;
  29778. exports.LoopOnce = LoopOnce;
  29779. exports.LoopPingPong = LoopPingPong;
  29780. exports.LoopRepeat = LoopRepeat;
  29781. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29782. exports.LuminanceFormat = LuminanceFormat;
  29783. exports.MOUSE = MOUSE;
  29784. exports.Material = Material;
  29785. exports.MaterialLoader = MaterialLoader;
  29786. exports.MathUtils = MathUtils;
  29787. exports.Matrix3 = Matrix3;
  29788. exports.Matrix4 = Matrix4;
  29789. exports.MaxEquation = MaxEquation;
  29790. exports.Mesh = Mesh;
  29791. exports.MeshBasicMaterial = MeshBasicMaterial;
  29792. exports.MeshDepthMaterial = MeshDepthMaterial;
  29793. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29794. exports.MeshLambertMaterial = MeshLambertMaterial;
  29795. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29796. exports.MeshNormalMaterial = MeshNormalMaterial;
  29797. exports.MeshPhongMaterial = MeshPhongMaterial;
  29798. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29799. exports.MeshStandardMaterial = MeshStandardMaterial;
  29800. exports.MeshToonMaterial = MeshToonMaterial;
  29801. exports.MinEquation = MinEquation;
  29802. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29803. exports.MixOperation = MixOperation;
  29804. exports.MultiplyBlending = MultiplyBlending;
  29805. exports.MultiplyOperation = MultiplyOperation;
  29806. exports.NearestFilter = NearestFilter;
  29807. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29808. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29809. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29810. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29811. exports.NeverDepth = NeverDepth;
  29812. exports.NeverStencilFunc = NeverStencilFunc;
  29813. exports.NoBlending = NoBlending;
  29814. exports.NoColorSpace = NoColorSpace;
  29815. exports.NoToneMapping = NoToneMapping;
  29816. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29817. exports.NormalBlending = NormalBlending;
  29818. exports.NotEqualDepth = NotEqualDepth;
  29819. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29820. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29821. exports.Object3D = Object3D;
  29822. exports.ObjectLoader = ObjectLoader;
  29823. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29824. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  29825. exports.OctahedronGeometry = OctahedronGeometry;
  29826. exports.OneFactor = OneFactor;
  29827. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29828. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29829. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29830. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29831. exports.OrthographicCamera = OrthographicCamera;
  29832. exports.PCFShadowMap = PCFShadowMap;
  29833. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29834. exports.PMREMGenerator = PMREMGenerator;
  29835. exports.Path = Path;
  29836. exports.PerspectiveCamera = PerspectiveCamera;
  29837. exports.Plane = Plane;
  29838. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  29839. exports.PlaneGeometry = PlaneGeometry;
  29840. exports.PlaneHelper = PlaneHelper;
  29841. exports.PointLight = PointLight;
  29842. exports.PointLightHelper = PointLightHelper;
  29843. exports.Points = Points;
  29844. exports.PointsMaterial = PointsMaterial;
  29845. exports.PolarGridHelper = PolarGridHelper;
  29846. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  29847. exports.PolyhedronGeometry = PolyhedronGeometry;
  29848. exports.PositionalAudio = PositionalAudio;
  29849. exports.PropertyBinding = PropertyBinding;
  29850. exports.PropertyMixer = PropertyMixer;
  29851. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29852. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29853. exports.Quaternion = Quaternion;
  29854. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29855. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29856. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  29857. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  29858. exports.REVISION = REVISION;
  29859. exports.RGBADepthPacking = RGBADepthPacking;
  29860. exports.RGBAFormat = RGBAFormat;
  29861. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29862. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29863. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29864. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29865. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29866. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29867. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29868. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29869. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29870. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29871. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29872. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29873. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29874. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29875. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29876. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29877. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29878. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29879. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29880. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29881. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29882. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29883. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29884. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29885. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29886. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29887. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29888. exports.RGFormat = RGFormat;
  29889. exports.RGIntegerFormat = RGIntegerFormat;
  29890. exports.RawShaderMaterial = RawShaderMaterial;
  29891. exports.Ray = Ray;
  29892. exports.Raycaster = Raycaster;
  29893. exports.RectAreaLight = RectAreaLight;
  29894. exports.RedFormat = RedFormat;
  29895. exports.RedIntegerFormat = RedIntegerFormat;
  29896. exports.ReinhardToneMapping = ReinhardToneMapping;
  29897. exports.RepeatWrapping = RepeatWrapping;
  29898. exports.ReplaceStencilOp = ReplaceStencilOp;
  29899. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29900. exports.RingBufferGeometry = RingBufferGeometry;
  29901. exports.RingGeometry = RingGeometry;
  29902. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  29903. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  29904. exports.SRGBColorSpace = SRGBColorSpace;
  29905. exports.Scene = Scene;
  29906. exports.ShaderChunk = ShaderChunk;
  29907. exports.ShaderLib = ShaderLib;
  29908. exports.ShaderMaterial = ShaderMaterial;
  29909. exports.ShadowMaterial = ShadowMaterial;
  29910. exports.Shape = Shape;
  29911. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29912. exports.ShapeGeometry = ShapeGeometry;
  29913. exports.ShapePath = ShapePath;
  29914. exports.ShapeUtils = ShapeUtils;
  29915. exports.ShortType = ShortType;
  29916. exports.Skeleton = Skeleton;
  29917. exports.SkeletonHelper = SkeletonHelper;
  29918. exports.SkinnedMesh = SkinnedMesh;
  29919. exports.Source = Source;
  29920. exports.Sphere = Sphere;
  29921. exports.SphereBufferGeometry = SphereBufferGeometry;
  29922. exports.SphereGeometry = SphereGeometry;
  29923. exports.Spherical = Spherical;
  29924. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29925. exports.SplineCurve = SplineCurve;
  29926. exports.SpotLight = SpotLight;
  29927. exports.SpotLightHelper = SpotLightHelper;
  29928. exports.Sprite = Sprite;
  29929. exports.SpriteMaterial = SpriteMaterial;
  29930. exports.SrcAlphaFactor = SrcAlphaFactor;
  29931. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29932. exports.SrcColorFactor = SrcColorFactor;
  29933. exports.StaticCopyUsage = StaticCopyUsage;
  29934. exports.StaticDrawUsage = StaticDrawUsage;
  29935. exports.StaticReadUsage = StaticReadUsage;
  29936. exports.StereoCamera = StereoCamera;
  29937. exports.StreamCopyUsage = StreamCopyUsage;
  29938. exports.StreamDrawUsage = StreamDrawUsage;
  29939. exports.StreamReadUsage = StreamReadUsage;
  29940. exports.StringKeyframeTrack = StringKeyframeTrack;
  29941. exports.SubtractEquation = SubtractEquation;
  29942. exports.SubtractiveBlending = SubtractiveBlending;
  29943. exports.TOUCH = TOUCH;
  29944. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29945. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29946. exports.TetrahedronGeometry = TetrahedronGeometry;
  29947. exports.Texture = Texture;
  29948. exports.TextureLoader = TextureLoader;
  29949. exports.TorusBufferGeometry = TorusBufferGeometry;
  29950. exports.TorusGeometry = TorusGeometry;
  29951. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29952. exports.TorusKnotGeometry = TorusKnotGeometry;
  29953. exports.Triangle = Triangle;
  29954. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29955. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29956. exports.TrianglesDrawMode = TrianglesDrawMode;
  29957. exports.TubeBufferGeometry = TubeBufferGeometry;
  29958. exports.TubeGeometry = TubeGeometry;
  29959. exports.TwoPassDoubleSide = TwoPassDoubleSide;
  29960. exports.UVMapping = UVMapping;
  29961. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29962. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29963. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29964. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29965. exports.Uniform = Uniform;
  29966. exports.UniformsGroup = UniformsGroup;
  29967. exports.UniformsLib = UniformsLib;
  29968. exports.UniformsUtils = UniformsUtils;
  29969. exports.UnsignedByteType = UnsignedByteType;
  29970. exports.UnsignedInt248Type = UnsignedInt248Type;
  29971. exports.UnsignedIntType = UnsignedIntType;
  29972. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29973. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29974. exports.UnsignedShortType = UnsignedShortType;
  29975. exports.VSMShadowMap = VSMShadowMap;
  29976. exports.Vector2 = Vector2;
  29977. exports.Vector3 = Vector3;
  29978. exports.Vector4 = Vector4;
  29979. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29980. exports.VideoTexture = VideoTexture;
  29981. exports.WebGL1Renderer = WebGL1Renderer;
  29982. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  29983. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  29984. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29985. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29986. exports.WebGLRenderTarget = WebGLRenderTarget;
  29987. exports.WebGLRenderer = WebGLRenderer;
  29988. exports.WebGLUtils = WebGLUtils;
  29989. exports.WireframeGeometry = WireframeGeometry;
  29990. exports.WrapAroundEnding = WrapAroundEnding;
  29991. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29992. exports.ZeroFactor = ZeroFactor;
  29993. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29994. exports.ZeroStencilOp = ZeroStencilOp;
  29995. exports._SRGBAFormat = _SRGBAFormat;
  29996. exports.sRGBEncoding = sRGBEncoding;