three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '145';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const NeverDepth = 0;
  43. const AlwaysDepth = 1;
  44. const LessDepth = 2;
  45. const LessEqualDepth = 3;
  46. const EqualDepth = 4;
  47. const GreaterEqualDepth = 5;
  48. const GreaterDepth = 6;
  49. const NotEqualDepth = 7;
  50. const MultiplyOperation = 0;
  51. const MixOperation = 1;
  52. const AddOperation = 2;
  53. const NoToneMapping = 0;
  54. const LinearToneMapping = 1;
  55. const ReinhardToneMapping = 2;
  56. const CineonToneMapping = 3;
  57. const ACESFilmicToneMapping = 4;
  58. const CustomToneMapping = 5;
  59. const UVMapping = 300;
  60. const CubeReflectionMapping = 301;
  61. const CubeRefractionMapping = 302;
  62. const EquirectangularReflectionMapping = 303;
  63. const EquirectangularRefractionMapping = 304;
  64. const CubeUVReflectionMapping = 306;
  65. const RepeatWrapping = 1000;
  66. const ClampToEdgeWrapping = 1001;
  67. const MirroredRepeatWrapping = 1002;
  68. const NearestFilter = 1003;
  69. const NearestMipmapNearestFilter = 1004;
  70. const NearestMipMapNearestFilter = 1004;
  71. const NearestMipmapLinearFilter = 1005;
  72. const NearestMipMapLinearFilter = 1005;
  73. const LinearFilter = 1006;
  74. const LinearMipmapNearestFilter = 1007;
  75. const LinearMipMapNearestFilter = 1007;
  76. const LinearMipmapLinearFilter = 1008;
  77. const LinearMipMapLinearFilter = 1008;
  78. const UnsignedByteType = 1009;
  79. const ByteType = 1010;
  80. const ShortType = 1011;
  81. const UnsignedShortType = 1012;
  82. const IntType = 1013;
  83. const UnsignedIntType = 1014;
  84. const FloatType = 1015;
  85. const HalfFloatType = 1016;
  86. const UnsignedShort4444Type = 1017;
  87. const UnsignedShort5551Type = 1018;
  88. const UnsignedInt248Type = 1020;
  89. const AlphaFormat = 1021;
  90. const RGBFormat = 1022; // @deprecated since r137
  91. const RGBAFormat = 1023;
  92. const LuminanceFormat = 1024;
  93. const LuminanceAlphaFormat = 1025;
  94. const DepthFormat = 1026;
  95. const DepthStencilFormat = 1027;
  96. const RedFormat = 1028;
  97. const RedIntegerFormat = 1029;
  98. const RGFormat = 1030;
  99. const RGIntegerFormat = 1031;
  100. const RGBAIntegerFormat = 1033;
  101. const RGB_S3TC_DXT1_Format = 33776;
  102. const RGBA_S3TC_DXT1_Format = 33777;
  103. const RGBA_S3TC_DXT3_Format = 33778;
  104. const RGBA_S3TC_DXT5_Format = 33779;
  105. const RGB_PVRTC_4BPPV1_Format = 35840;
  106. const RGB_PVRTC_2BPPV1_Format = 35841;
  107. const RGBA_PVRTC_4BPPV1_Format = 35842;
  108. const RGBA_PVRTC_2BPPV1_Format = 35843;
  109. const RGB_ETC1_Format = 36196;
  110. const RGB_ETC2_Format = 37492;
  111. const RGBA_ETC2_EAC_Format = 37496;
  112. const RGBA_ASTC_4x4_Format = 37808;
  113. const RGBA_ASTC_5x4_Format = 37809;
  114. const RGBA_ASTC_5x5_Format = 37810;
  115. const RGBA_ASTC_6x5_Format = 37811;
  116. const RGBA_ASTC_6x6_Format = 37812;
  117. const RGBA_ASTC_8x5_Format = 37813;
  118. const RGBA_ASTC_8x6_Format = 37814;
  119. const RGBA_ASTC_8x8_Format = 37815;
  120. const RGBA_ASTC_10x5_Format = 37816;
  121. const RGBA_ASTC_10x6_Format = 37817;
  122. const RGBA_ASTC_10x8_Format = 37818;
  123. const RGBA_ASTC_10x10_Format = 37819;
  124. const RGBA_ASTC_12x10_Format = 37820;
  125. const RGBA_ASTC_12x12_Format = 37821;
  126. const RGBA_BPTC_Format = 36492;
  127. const LoopOnce = 2200;
  128. const LoopRepeat = 2201;
  129. const LoopPingPong = 2202;
  130. const InterpolateDiscrete = 2300;
  131. const InterpolateLinear = 2301;
  132. const InterpolateSmooth = 2302;
  133. const ZeroCurvatureEnding = 2400;
  134. const ZeroSlopeEnding = 2401;
  135. const WrapAroundEnding = 2402;
  136. const NormalAnimationBlendMode = 2500;
  137. const AdditiveAnimationBlendMode = 2501;
  138. const TrianglesDrawMode = 0;
  139. const TriangleStripDrawMode = 1;
  140. const TriangleFanDrawMode = 2;
  141. const LinearEncoding = 3000;
  142. const sRGBEncoding = 3001;
  143. const BasicDepthPacking = 3200;
  144. const RGBADepthPacking = 3201;
  145. const TangentSpaceNormalMap = 0;
  146. const ObjectSpaceNormalMap = 1;
  147. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  148. const NoColorSpace = '';
  149. const SRGBColorSpace = 'srgb';
  150. const LinearSRGBColorSpace = 'srgb-linear';
  151. const ZeroStencilOp = 0;
  152. const KeepStencilOp = 7680;
  153. const ReplaceStencilOp = 7681;
  154. const IncrementStencilOp = 7682;
  155. const DecrementStencilOp = 7683;
  156. const IncrementWrapStencilOp = 34055;
  157. const DecrementWrapStencilOp = 34056;
  158. const InvertStencilOp = 5386;
  159. const NeverStencilFunc = 512;
  160. const LessStencilFunc = 513;
  161. const EqualStencilFunc = 514;
  162. const LessEqualStencilFunc = 515;
  163. const GreaterStencilFunc = 516;
  164. const NotEqualStencilFunc = 517;
  165. const GreaterEqualStencilFunc = 518;
  166. const AlwaysStencilFunc = 519;
  167. const StaticDrawUsage = 35044;
  168. const DynamicDrawUsage = 35048;
  169. const StreamDrawUsage = 35040;
  170. const StaticReadUsage = 35045;
  171. const DynamicReadUsage = 35049;
  172. const StreamReadUsage = 35041;
  173. const StaticCopyUsage = 35046;
  174. const DynamicCopyUsage = 35050;
  175. const StreamCopyUsage = 35042;
  176. const GLSL1 = '100';
  177. const GLSL3 = '300 es';
  178. const _SRGBAFormat = 1035; // fallback for WebGL 1
  179. /**
  180. * https://github.com/mrdoob/eventdispatcher.js/
  181. */
  182. class EventDispatcher {
  183. addEventListener( type, listener ) {
  184. if ( this._listeners === undefined ) this._listeners = {};
  185. const listeners = this._listeners;
  186. if ( listeners[ type ] === undefined ) {
  187. listeners[ type ] = [];
  188. }
  189. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  190. listeners[ type ].push( listener );
  191. }
  192. }
  193. hasEventListener( type, listener ) {
  194. if ( this._listeners === undefined ) return false;
  195. const listeners = this._listeners;
  196. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  197. }
  198. removeEventListener( type, listener ) {
  199. if ( this._listeners === undefined ) return;
  200. const listeners = this._listeners;
  201. const listenerArray = listeners[ type ];
  202. if ( listenerArray !== undefined ) {
  203. const index = listenerArray.indexOf( listener );
  204. if ( index !== - 1 ) {
  205. listenerArray.splice( index, 1 );
  206. }
  207. }
  208. }
  209. dispatchEvent( event ) {
  210. if ( this._listeners === undefined ) return;
  211. const listeners = this._listeners;
  212. const listenerArray = listeners[ event.type ];
  213. if ( listenerArray !== undefined ) {
  214. event.target = this;
  215. // Make a copy, in case listeners are removed while iterating.
  216. const array = listenerArray.slice( 0 );
  217. for ( let i = 0, l = array.length; i < l; i ++ ) {
  218. array[ i ].call( this, event );
  219. }
  220. event.target = null;
  221. }
  222. }
  223. }
  224. 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' ];
  225. let _seed = 1234567;
  226. const DEG2RAD = Math.PI / 180;
  227. const RAD2DEG = 180 / Math.PI;
  228. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  229. function generateUUID() {
  230. const d0 = Math.random() * 0xffffffff | 0;
  231. const d1 = Math.random() * 0xffffffff | 0;
  232. const d2 = Math.random() * 0xffffffff | 0;
  233. const d3 = Math.random() * 0xffffffff | 0;
  234. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  235. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  236. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  237. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  238. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  239. return uuid.toLowerCase();
  240. }
  241. function clamp( value, min, max ) {
  242. return Math.max( min, Math.min( max, value ) );
  243. }
  244. // compute euclidean modulo of m % n
  245. // https://en.wikipedia.org/wiki/Modulo_operation
  246. function euclideanModulo( n, m ) {
  247. return ( ( n % m ) + m ) % m;
  248. }
  249. // Linear mapping from range <a1, a2> to range <b1, b2>
  250. function mapLinear( x, a1, a2, b1, b2 ) {
  251. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  252. }
  253. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  254. function inverseLerp( x, y, value ) {
  255. if ( x !== y ) {
  256. return ( value - x ) / ( y - x );
  257. } else {
  258. return 0;
  259. }
  260. }
  261. // https://en.wikipedia.org/wiki/Linear_interpolation
  262. function lerp( x, y, t ) {
  263. return ( 1 - t ) * x + t * y;
  264. }
  265. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  266. function damp( x, y, lambda, dt ) {
  267. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  268. }
  269. // https://www.desmos.com/calculator/vcsjnyz7x4
  270. function pingpong( x, length = 1 ) {
  271. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  272. }
  273. // http://en.wikipedia.org/wiki/Smoothstep
  274. function smoothstep( x, min, max ) {
  275. if ( x <= min ) return 0;
  276. if ( x >= max ) return 1;
  277. x = ( x - min ) / ( max - min );
  278. return x * x * ( 3 - 2 * x );
  279. }
  280. function smootherstep( x, min, max ) {
  281. if ( x <= min ) return 0;
  282. if ( x >= max ) return 1;
  283. x = ( x - min ) / ( max - min );
  284. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  285. }
  286. // Random integer from <low, high> interval
  287. function randInt( low, high ) {
  288. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  289. }
  290. // Random float from <low, high> interval
  291. function randFloat( low, high ) {
  292. return low + Math.random() * ( high - low );
  293. }
  294. // Random float from <-range/2, range/2> interval
  295. function randFloatSpread( range ) {
  296. return range * ( 0.5 - Math.random() );
  297. }
  298. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  299. function seededRandom( s ) {
  300. if ( s !== undefined ) _seed = s;
  301. // Mulberry32 generator
  302. let t = _seed += 0x6D2B79F5;
  303. t = Math.imul( t ^ t >>> 15, t | 1 );
  304. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  305. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  306. }
  307. function degToRad( degrees ) {
  308. return degrees * DEG2RAD;
  309. }
  310. function radToDeg( radians ) {
  311. return radians * RAD2DEG;
  312. }
  313. function isPowerOfTwo( value ) {
  314. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  315. }
  316. function ceilPowerOfTwo( value ) {
  317. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  318. }
  319. function floorPowerOfTwo( value ) {
  320. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  321. }
  322. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  323. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  324. // rotations are applied to the axes in the order specified by 'order'
  325. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  326. // angles are in radians
  327. const cos = Math.cos;
  328. const sin = Math.sin;
  329. const c2 = cos( b / 2 );
  330. const s2 = sin( b / 2 );
  331. const c13 = cos( ( a + c ) / 2 );
  332. const s13 = sin( ( a + c ) / 2 );
  333. const c1_3 = cos( ( a - c ) / 2 );
  334. const s1_3 = sin( ( a - c ) / 2 );
  335. const c3_1 = cos( ( c - a ) / 2 );
  336. const s3_1 = sin( ( c - a ) / 2 );
  337. switch ( order ) {
  338. case 'XYX':
  339. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  340. break;
  341. case 'YZY':
  342. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  343. break;
  344. case 'ZXZ':
  345. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  346. break;
  347. case 'XZX':
  348. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  349. break;
  350. case 'YXY':
  351. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  352. break;
  353. case 'ZYZ':
  354. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  355. break;
  356. default:
  357. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  358. }
  359. }
  360. function denormalize( value, array ) {
  361. switch ( array.constructor ) {
  362. case Float32Array:
  363. return value;
  364. case Uint16Array:
  365. return value / 65535.0;
  366. case Uint8Array:
  367. return value / 255.0;
  368. case Int16Array:
  369. return Math.max( value / 32767.0, - 1.0 );
  370. case Int8Array:
  371. return Math.max( value / 127.0, - 1.0 );
  372. default:
  373. throw new Error( 'Invalid component type.' );
  374. }
  375. }
  376. function normalize( value, array ) {
  377. switch ( array.constructor ) {
  378. case Float32Array:
  379. return value;
  380. case Uint16Array:
  381. return Math.round( value * 65535.0 );
  382. case Uint8Array:
  383. return Math.round( value * 255.0 );
  384. case Int16Array:
  385. return Math.round( value * 32767.0 );
  386. case Int8Array:
  387. return Math.round( value * 127.0 );
  388. default:
  389. throw new Error( 'Invalid component type.' );
  390. }
  391. }
  392. var MathUtils = /*#__PURE__*/Object.freeze({
  393. __proto__: null,
  394. DEG2RAD: DEG2RAD,
  395. RAD2DEG: RAD2DEG,
  396. generateUUID: generateUUID,
  397. clamp: clamp,
  398. euclideanModulo: euclideanModulo,
  399. mapLinear: mapLinear,
  400. inverseLerp: inverseLerp,
  401. lerp: lerp,
  402. damp: damp,
  403. pingpong: pingpong,
  404. smoothstep: smoothstep,
  405. smootherstep: smootherstep,
  406. randInt: randInt,
  407. randFloat: randFloat,
  408. randFloatSpread: randFloatSpread,
  409. seededRandom: seededRandom,
  410. degToRad: degToRad,
  411. radToDeg: radToDeg,
  412. isPowerOfTwo: isPowerOfTwo,
  413. ceilPowerOfTwo: ceilPowerOfTwo,
  414. floorPowerOfTwo: floorPowerOfTwo,
  415. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  416. normalize: normalize,
  417. denormalize: denormalize
  418. });
  419. class Vector2 {
  420. constructor( x = 0, y = 0 ) {
  421. Vector2.prototype.isVector2 = true;
  422. this.x = x;
  423. this.y = y;
  424. }
  425. get width() {
  426. return this.x;
  427. }
  428. set width( value ) {
  429. this.x = value;
  430. }
  431. get height() {
  432. return this.y;
  433. }
  434. set height( value ) {
  435. this.y = value;
  436. }
  437. set( x, y ) {
  438. this.x = x;
  439. this.y = y;
  440. return this;
  441. }
  442. setScalar( scalar ) {
  443. this.x = scalar;
  444. this.y = scalar;
  445. return this;
  446. }
  447. setX( x ) {
  448. this.x = x;
  449. return this;
  450. }
  451. setY( y ) {
  452. this.y = y;
  453. return this;
  454. }
  455. setComponent( index, value ) {
  456. switch ( index ) {
  457. case 0: this.x = value; break;
  458. case 1: this.y = value; break;
  459. default: throw new Error( 'index is out of range: ' + index );
  460. }
  461. return this;
  462. }
  463. getComponent( index ) {
  464. switch ( index ) {
  465. case 0: return this.x;
  466. case 1: return this.y;
  467. default: throw new Error( 'index is out of range: ' + index );
  468. }
  469. }
  470. clone() {
  471. return new this.constructor( this.x, this.y );
  472. }
  473. copy( v ) {
  474. this.x = v.x;
  475. this.y = v.y;
  476. return this;
  477. }
  478. add( v ) {
  479. this.x += v.x;
  480. this.y += v.y;
  481. return this;
  482. }
  483. addScalar( s ) {
  484. this.x += s;
  485. this.y += s;
  486. return this;
  487. }
  488. addVectors( a, b ) {
  489. this.x = a.x + b.x;
  490. this.y = a.y + b.y;
  491. return this;
  492. }
  493. addScaledVector( v, s ) {
  494. this.x += v.x * s;
  495. this.y += v.y * s;
  496. return this;
  497. }
  498. sub( v ) {
  499. this.x -= v.x;
  500. this.y -= v.y;
  501. return this;
  502. }
  503. subScalar( s ) {
  504. this.x -= s;
  505. this.y -= s;
  506. return this;
  507. }
  508. subVectors( a, b ) {
  509. this.x = a.x - b.x;
  510. this.y = a.y - b.y;
  511. return this;
  512. }
  513. multiply( v ) {
  514. this.x *= v.x;
  515. this.y *= v.y;
  516. return this;
  517. }
  518. multiplyScalar( scalar ) {
  519. this.x *= scalar;
  520. this.y *= scalar;
  521. return this;
  522. }
  523. divide( v ) {
  524. this.x /= v.x;
  525. this.y /= v.y;
  526. return this;
  527. }
  528. divideScalar( scalar ) {
  529. return this.multiplyScalar( 1 / scalar );
  530. }
  531. applyMatrix3( m ) {
  532. const x = this.x, y = this.y;
  533. const e = m.elements;
  534. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  535. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  536. return this;
  537. }
  538. min( v ) {
  539. this.x = Math.min( this.x, v.x );
  540. this.y = Math.min( this.y, v.y );
  541. return this;
  542. }
  543. max( v ) {
  544. this.x = Math.max( this.x, v.x );
  545. this.y = Math.max( this.y, v.y );
  546. return this;
  547. }
  548. clamp( min, max ) {
  549. // assumes min < max, componentwise
  550. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  551. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  552. return this;
  553. }
  554. clampScalar( minVal, maxVal ) {
  555. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  556. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  557. return this;
  558. }
  559. clampLength( min, max ) {
  560. const length = this.length();
  561. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  562. }
  563. floor() {
  564. this.x = Math.floor( this.x );
  565. this.y = Math.floor( this.y );
  566. return this;
  567. }
  568. ceil() {
  569. this.x = Math.ceil( this.x );
  570. this.y = Math.ceil( this.y );
  571. return this;
  572. }
  573. round() {
  574. this.x = Math.round( this.x );
  575. this.y = Math.round( this.y );
  576. return this;
  577. }
  578. roundToZero() {
  579. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  580. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  581. return this;
  582. }
  583. negate() {
  584. this.x = - this.x;
  585. this.y = - this.y;
  586. return this;
  587. }
  588. dot( v ) {
  589. return this.x * v.x + this.y * v.y;
  590. }
  591. cross( v ) {
  592. return this.x * v.y - this.y * v.x;
  593. }
  594. lengthSq() {
  595. return this.x * this.x + this.y * this.y;
  596. }
  597. length() {
  598. return Math.sqrt( this.x * this.x + this.y * this.y );
  599. }
  600. manhattanLength() {
  601. return Math.abs( this.x ) + Math.abs( this.y );
  602. }
  603. normalize() {
  604. return this.divideScalar( this.length() || 1 );
  605. }
  606. angle() {
  607. // computes the angle in radians with respect to the positive x-axis
  608. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  609. return angle;
  610. }
  611. distanceTo( v ) {
  612. return Math.sqrt( this.distanceToSquared( v ) );
  613. }
  614. distanceToSquared( v ) {
  615. const dx = this.x - v.x, dy = this.y - v.y;
  616. return dx * dx + dy * dy;
  617. }
  618. manhattanDistanceTo( v ) {
  619. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  620. }
  621. setLength( length ) {
  622. return this.normalize().multiplyScalar( length );
  623. }
  624. lerp( v, alpha ) {
  625. this.x += ( v.x - this.x ) * alpha;
  626. this.y += ( v.y - this.y ) * alpha;
  627. return this;
  628. }
  629. lerpVectors( v1, v2, alpha ) {
  630. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  631. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  632. return this;
  633. }
  634. equals( v ) {
  635. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  636. }
  637. fromArray( array, offset = 0 ) {
  638. this.x = array[ offset ];
  639. this.y = array[ offset + 1 ];
  640. return this;
  641. }
  642. toArray( array = [], offset = 0 ) {
  643. array[ offset ] = this.x;
  644. array[ offset + 1 ] = this.y;
  645. return array;
  646. }
  647. fromBufferAttribute( attribute, index ) {
  648. this.x = attribute.getX( index );
  649. this.y = attribute.getY( index );
  650. return this;
  651. }
  652. rotateAround( center, angle ) {
  653. const c = Math.cos( angle ), s = Math.sin( angle );
  654. const x = this.x - center.x;
  655. const y = this.y - center.y;
  656. this.x = x * c - y * s + center.x;
  657. this.y = x * s + y * c + center.y;
  658. return this;
  659. }
  660. random() {
  661. this.x = Math.random();
  662. this.y = Math.random();
  663. return this;
  664. }
  665. *[ Symbol.iterator ]() {
  666. yield this.x;
  667. yield this.y;
  668. }
  669. }
  670. class Matrix3 {
  671. constructor() {
  672. Matrix3.prototype.isMatrix3 = true;
  673. this.elements = [
  674. 1, 0, 0,
  675. 0, 1, 0,
  676. 0, 0, 1
  677. ];
  678. }
  679. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  680. const te = this.elements;
  681. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  682. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  683. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  684. return this;
  685. }
  686. identity() {
  687. this.set(
  688. 1, 0, 0,
  689. 0, 1, 0,
  690. 0, 0, 1
  691. );
  692. return this;
  693. }
  694. copy( m ) {
  695. const te = this.elements;
  696. const me = m.elements;
  697. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  698. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  699. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  700. return this;
  701. }
  702. extractBasis( xAxis, yAxis, zAxis ) {
  703. xAxis.setFromMatrix3Column( this, 0 );
  704. yAxis.setFromMatrix3Column( this, 1 );
  705. zAxis.setFromMatrix3Column( this, 2 );
  706. return this;
  707. }
  708. setFromMatrix4( m ) {
  709. const me = m.elements;
  710. this.set(
  711. me[ 0 ], me[ 4 ], me[ 8 ],
  712. me[ 1 ], me[ 5 ], me[ 9 ],
  713. me[ 2 ], me[ 6 ], me[ 10 ]
  714. );
  715. return this;
  716. }
  717. multiply( m ) {
  718. return this.multiplyMatrices( this, m );
  719. }
  720. premultiply( m ) {
  721. return this.multiplyMatrices( m, this );
  722. }
  723. multiplyMatrices( a, b ) {
  724. const ae = a.elements;
  725. const be = b.elements;
  726. const te = this.elements;
  727. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  728. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  729. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  730. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  731. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  732. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  733. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  734. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  735. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  736. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  737. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  738. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  739. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  740. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  741. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  742. return this;
  743. }
  744. multiplyScalar( s ) {
  745. const te = this.elements;
  746. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  747. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  748. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  749. return this;
  750. }
  751. determinant() {
  752. const te = this.elements;
  753. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  754. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  755. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  756. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  757. }
  758. invert() {
  759. const te = this.elements,
  760. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  761. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  762. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  763. t11 = n33 * n22 - n32 * n23,
  764. t12 = n32 * n13 - n33 * n12,
  765. t13 = n23 * n12 - n22 * n13,
  766. det = n11 * t11 + n21 * t12 + n31 * t13;
  767. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  768. const detInv = 1 / det;
  769. te[ 0 ] = t11 * detInv;
  770. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  771. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  772. te[ 3 ] = t12 * detInv;
  773. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  774. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  775. te[ 6 ] = t13 * detInv;
  776. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  777. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  778. return this;
  779. }
  780. transpose() {
  781. let tmp;
  782. const m = this.elements;
  783. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  784. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  785. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  786. return this;
  787. }
  788. getNormalMatrix( matrix4 ) {
  789. return this.setFromMatrix4( matrix4 ).invert().transpose();
  790. }
  791. transposeIntoArray( r ) {
  792. const m = this.elements;
  793. r[ 0 ] = m[ 0 ];
  794. r[ 1 ] = m[ 3 ];
  795. r[ 2 ] = m[ 6 ];
  796. r[ 3 ] = m[ 1 ];
  797. r[ 4 ] = m[ 4 ];
  798. r[ 5 ] = m[ 7 ];
  799. r[ 6 ] = m[ 2 ];
  800. r[ 7 ] = m[ 5 ];
  801. r[ 8 ] = m[ 8 ];
  802. return this;
  803. }
  804. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  805. const c = Math.cos( rotation );
  806. const s = Math.sin( rotation );
  807. this.set(
  808. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  809. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  810. 0, 0, 1
  811. );
  812. return this;
  813. }
  814. scale( sx, sy ) {
  815. const te = this.elements;
  816. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  817. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  818. return this;
  819. }
  820. rotate( theta ) {
  821. const c = Math.cos( theta );
  822. const s = Math.sin( theta );
  823. const te = this.elements;
  824. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  825. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  826. te[ 0 ] = c * a11 + s * a21;
  827. te[ 3 ] = c * a12 + s * a22;
  828. te[ 6 ] = c * a13 + s * a23;
  829. te[ 1 ] = - s * a11 + c * a21;
  830. te[ 4 ] = - s * a12 + c * a22;
  831. te[ 7 ] = - s * a13 + c * a23;
  832. return this;
  833. }
  834. translate( tx, ty ) {
  835. const te = this.elements;
  836. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  837. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  838. return this;
  839. }
  840. equals( matrix ) {
  841. const te = this.elements;
  842. const me = matrix.elements;
  843. for ( let i = 0; i < 9; i ++ ) {
  844. if ( te[ i ] !== me[ i ] ) return false;
  845. }
  846. return true;
  847. }
  848. fromArray( array, offset = 0 ) {
  849. for ( let i = 0; i < 9; i ++ ) {
  850. this.elements[ i ] = array[ i + offset ];
  851. }
  852. return this;
  853. }
  854. toArray( array = [], offset = 0 ) {
  855. const te = this.elements;
  856. array[ offset ] = te[ 0 ];
  857. array[ offset + 1 ] = te[ 1 ];
  858. array[ offset + 2 ] = te[ 2 ];
  859. array[ offset + 3 ] = te[ 3 ];
  860. array[ offset + 4 ] = te[ 4 ];
  861. array[ offset + 5 ] = te[ 5 ];
  862. array[ offset + 6 ] = te[ 6 ];
  863. array[ offset + 7 ] = te[ 7 ];
  864. array[ offset + 8 ] = te[ 8 ];
  865. return array;
  866. }
  867. clone() {
  868. return new this.constructor().fromArray( this.elements );
  869. }
  870. }
  871. function arrayNeedsUint32( array ) {
  872. // assumes larger values usually on last
  873. for ( let i = array.length - 1; i >= 0; -- i ) {
  874. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  875. }
  876. return false;
  877. }
  878. const TYPED_ARRAYS = {
  879. Int8Array: Int8Array,
  880. Uint8Array: Uint8Array,
  881. Uint8ClampedArray: Uint8ClampedArray,
  882. Int16Array: Int16Array,
  883. Uint16Array: Uint16Array,
  884. Int32Array: Int32Array,
  885. Uint32Array: Uint32Array,
  886. Float32Array: Float32Array,
  887. Float64Array: Float64Array
  888. };
  889. function getTypedArray( type, buffer ) {
  890. return new TYPED_ARRAYS[ type ]( buffer );
  891. }
  892. function createElementNS( name ) {
  893. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  894. }
  895. function SRGBToLinear( c ) {
  896. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  897. }
  898. function LinearToSRGB( c ) {
  899. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  900. }
  901. // JavaScript RGB-to-RGB transforms, defined as
  902. // FN[InputColorSpace][OutputColorSpace] callback functions.
  903. const FN = {
  904. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  905. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  906. };
  907. const ColorManagement = {
  908. legacyMode: true,
  909. get workingColorSpace() {
  910. return LinearSRGBColorSpace;
  911. },
  912. set workingColorSpace( colorSpace ) {
  913. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  914. },
  915. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  916. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  917. return color;
  918. }
  919. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  920. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  921. color.r = fn( color.r );
  922. color.g = fn( color.g );
  923. color.b = fn( color.b );
  924. return color;
  925. }
  926. throw new Error( 'Unsupported color space conversion.' );
  927. },
  928. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  929. return this.convert( color, this.workingColorSpace, targetColorSpace );
  930. },
  931. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  932. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  933. },
  934. };
  935. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  936. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  937. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  938. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  939. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  940. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  941. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  942. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  943. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  944. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  945. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  946. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  947. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  948. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  949. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  950. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  951. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  952. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  953. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  954. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  955. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  956. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  957. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  958. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  959. const _rgb = { r: 0, g: 0, b: 0 };
  960. const _hslA = { h: 0, s: 0, l: 0 };
  961. const _hslB = { h: 0, s: 0, l: 0 };
  962. function hue2rgb( p, q, t ) {
  963. if ( t < 0 ) t += 1;
  964. if ( t > 1 ) t -= 1;
  965. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  966. if ( t < 1 / 2 ) return q;
  967. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  968. return p;
  969. }
  970. function toComponents( source, target ) {
  971. target.r = source.r;
  972. target.g = source.g;
  973. target.b = source.b;
  974. return target;
  975. }
  976. class Color {
  977. constructor( r, g, b ) {
  978. this.isColor = true;
  979. this.r = 1;
  980. this.g = 1;
  981. this.b = 1;
  982. if ( g === undefined && b === undefined ) {
  983. // r is THREE.Color, hex or string
  984. return this.set( r );
  985. }
  986. return this.setRGB( r, g, b );
  987. }
  988. set( value ) {
  989. if ( value && value.isColor ) {
  990. this.copy( value );
  991. } else if ( typeof value === 'number' ) {
  992. this.setHex( value );
  993. } else if ( typeof value === 'string' ) {
  994. this.setStyle( value );
  995. }
  996. return this;
  997. }
  998. setScalar( scalar ) {
  999. this.r = scalar;
  1000. this.g = scalar;
  1001. this.b = scalar;
  1002. return this;
  1003. }
  1004. setHex( hex, colorSpace = SRGBColorSpace ) {
  1005. hex = Math.floor( hex );
  1006. this.r = ( hex >> 16 & 255 ) / 255;
  1007. this.g = ( hex >> 8 & 255 ) / 255;
  1008. this.b = ( hex & 255 ) / 255;
  1009. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1010. return this;
  1011. }
  1012. setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) {
  1013. this.r = r;
  1014. this.g = g;
  1015. this.b = b;
  1016. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1017. return this;
  1018. }
  1019. setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) {
  1020. // h,s,l ranges are in 0.0 - 1.0
  1021. h = euclideanModulo( h, 1 );
  1022. s = clamp( s, 0, 1 );
  1023. l = clamp( l, 0, 1 );
  1024. if ( s === 0 ) {
  1025. this.r = this.g = this.b = l;
  1026. } else {
  1027. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1028. const q = ( 2 * l ) - p;
  1029. this.r = hue2rgb( q, p, h + 1 / 3 );
  1030. this.g = hue2rgb( q, p, h );
  1031. this.b = hue2rgb( q, p, h - 1 / 3 );
  1032. }
  1033. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1034. return this;
  1035. }
  1036. setStyle( style, colorSpace = SRGBColorSpace ) {
  1037. function handleAlpha( string ) {
  1038. if ( string === undefined ) return;
  1039. if ( parseFloat( string ) < 1 ) {
  1040. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1041. }
  1042. }
  1043. let m;
  1044. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1045. // rgb / hsl
  1046. let color;
  1047. const name = m[ 1 ];
  1048. const components = m[ 2 ];
  1049. switch ( name ) {
  1050. case 'rgb':
  1051. case 'rgba':
  1052. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1053. // rgb(255,0,0) rgba(255,0,0,0.5)
  1054. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1055. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1056. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1057. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1058. handleAlpha( color[ 4 ] );
  1059. return this;
  1060. }
  1061. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1062. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1063. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1064. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1065. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1066. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1067. handleAlpha( color[ 4 ] );
  1068. return this;
  1069. }
  1070. break;
  1071. case 'hsl':
  1072. case 'hsla':
  1073. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1074. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1075. const h = parseFloat( color[ 1 ] ) / 360;
  1076. const s = parseFloat( color[ 2 ] ) / 100;
  1077. const l = parseFloat( color[ 3 ] ) / 100;
  1078. handleAlpha( color[ 4 ] );
  1079. return this.setHSL( h, s, l, colorSpace );
  1080. }
  1081. break;
  1082. }
  1083. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1084. // hex color
  1085. const hex = m[ 1 ];
  1086. const size = hex.length;
  1087. if ( size === 3 ) {
  1088. // #ff0
  1089. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1090. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1091. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1092. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1093. return this;
  1094. } else if ( size === 6 ) {
  1095. // #ff0000
  1096. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1097. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1098. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1099. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1100. return this;
  1101. }
  1102. }
  1103. if ( style && style.length > 0 ) {
  1104. return this.setColorName( style, colorSpace );
  1105. }
  1106. return this;
  1107. }
  1108. setColorName( style, colorSpace = SRGBColorSpace ) {
  1109. // color keywords
  1110. const hex = _colorKeywords[ style.toLowerCase() ];
  1111. if ( hex !== undefined ) {
  1112. // red
  1113. this.setHex( hex, colorSpace );
  1114. } else {
  1115. // unknown color
  1116. console.warn( 'THREE.Color: Unknown color ' + style );
  1117. }
  1118. return this;
  1119. }
  1120. clone() {
  1121. return new this.constructor( this.r, this.g, this.b );
  1122. }
  1123. copy( color ) {
  1124. this.r = color.r;
  1125. this.g = color.g;
  1126. this.b = color.b;
  1127. return this;
  1128. }
  1129. copySRGBToLinear( color ) {
  1130. this.r = SRGBToLinear( color.r );
  1131. this.g = SRGBToLinear( color.g );
  1132. this.b = SRGBToLinear( color.b );
  1133. return this;
  1134. }
  1135. copyLinearToSRGB( color ) {
  1136. this.r = LinearToSRGB( color.r );
  1137. this.g = LinearToSRGB( color.g );
  1138. this.b = LinearToSRGB( color.b );
  1139. return this;
  1140. }
  1141. convertSRGBToLinear() {
  1142. this.copySRGBToLinear( this );
  1143. return this;
  1144. }
  1145. convertLinearToSRGB() {
  1146. this.copyLinearToSRGB( this );
  1147. return this;
  1148. }
  1149. getHex( colorSpace = SRGBColorSpace ) {
  1150. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1151. return clamp( _rgb.r * 255, 0, 255 ) << 16 ^ clamp( _rgb.g * 255, 0, 255 ) << 8 ^ clamp( _rgb.b * 255, 0, 255 ) << 0;
  1152. }
  1153. getHexString( colorSpace = SRGBColorSpace ) {
  1154. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1155. }
  1156. getHSL( target, colorSpace = LinearSRGBColorSpace ) {
  1157. // h,s,l ranges are in 0.0 - 1.0
  1158. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1159. const r = _rgb.r, g = _rgb.g, b = _rgb.b;
  1160. const max = Math.max( r, g, b );
  1161. const min = Math.min( r, g, b );
  1162. let hue, saturation;
  1163. const lightness = ( min + max ) / 2.0;
  1164. if ( min === max ) {
  1165. hue = 0;
  1166. saturation = 0;
  1167. } else {
  1168. const delta = max - min;
  1169. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1170. switch ( max ) {
  1171. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1172. case g: hue = ( b - r ) / delta + 2; break;
  1173. case b: hue = ( r - g ) / delta + 4; break;
  1174. }
  1175. hue /= 6;
  1176. }
  1177. target.h = hue;
  1178. target.s = saturation;
  1179. target.l = lightness;
  1180. return target;
  1181. }
  1182. getRGB( target, colorSpace = LinearSRGBColorSpace ) {
  1183. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1184. target.r = _rgb.r;
  1185. target.g = _rgb.g;
  1186. target.b = _rgb.b;
  1187. return target;
  1188. }
  1189. getStyle( colorSpace = SRGBColorSpace ) {
  1190. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1191. if ( colorSpace !== SRGBColorSpace ) {
  1192. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1193. return `color(${ colorSpace } ${ _rgb.r } ${ _rgb.g } ${ _rgb.b })`;
  1194. }
  1195. return `rgb(${( _rgb.r * 255 ) | 0},${( _rgb.g * 255 ) | 0},${( _rgb.b * 255 ) | 0})`;
  1196. }
  1197. offsetHSL( h, s, l ) {
  1198. this.getHSL( _hslA );
  1199. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1200. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1201. return this;
  1202. }
  1203. add( color ) {
  1204. this.r += color.r;
  1205. this.g += color.g;
  1206. this.b += color.b;
  1207. return this;
  1208. }
  1209. addColors( color1, color2 ) {
  1210. this.r = color1.r + color2.r;
  1211. this.g = color1.g + color2.g;
  1212. this.b = color1.b + color2.b;
  1213. return this;
  1214. }
  1215. addScalar( s ) {
  1216. this.r += s;
  1217. this.g += s;
  1218. this.b += s;
  1219. return this;
  1220. }
  1221. sub( color ) {
  1222. this.r = Math.max( 0, this.r - color.r );
  1223. this.g = Math.max( 0, this.g - color.g );
  1224. this.b = Math.max( 0, this.b - color.b );
  1225. return this;
  1226. }
  1227. multiply( color ) {
  1228. this.r *= color.r;
  1229. this.g *= color.g;
  1230. this.b *= color.b;
  1231. return this;
  1232. }
  1233. multiplyScalar( s ) {
  1234. this.r *= s;
  1235. this.g *= s;
  1236. this.b *= s;
  1237. return this;
  1238. }
  1239. lerp( color, alpha ) {
  1240. this.r += ( color.r - this.r ) * alpha;
  1241. this.g += ( color.g - this.g ) * alpha;
  1242. this.b += ( color.b - this.b ) * alpha;
  1243. return this;
  1244. }
  1245. lerpColors( color1, color2, alpha ) {
  1246. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1247. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1248. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1249. return this;
  1250. }
  1251. lerpHSL( color, alpha ) {
  1252. this.getHSL( _hslA );
  1253. color.getHSL( _hslB );
  1254. const h = lerp( _hslA.h, _hslB.h, alpha );
  1255. const s = lerp( _hslA.s, _hslB.s, alpha );
  1256. const l = lerp( _hslA.l, _hslB.l, alpha );
  1257. this.setHSL( h, s, l );
  1258. return this;
  1259. }
  1260. equals( c ) {
  1261. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1262. }
  1263. fromArray( array, offset = 0 ) {
  1264. this.r = array[ offset ];
  1265. this.g = array[ offset + 1 ];
  1266. this.b = array[ offset + 2 ];
  1267. return this;
  1268. }
  1269. toArray( array = [], offset = 0 ) {
  1270. array[ offset ] = this.r;
  1271. array[ offset + 1 ] = this.g;
  1272. array[ offset + 2 ] = this.b;
  1273. return array;
  1274. }
  1275. fromBufferAttribute( attribute, index ) {
  1276. this.r = attribute.getX( index );
  1277. this.g = attribute.getY( index );
  1278. this.b = attribute.getZ( index );
  1279. return this;
  1280. }
  1281. toJSON() {
  1282. return this.getHex();
  1283. }
  1284. *[ Symbol.iterator ]() {
  1285. yield this.r;
  1286. yield this.g;
  1287. yield this.b;
  1288. }
  1289. }
  1290. Color.NAMES = _colorKeywords;
  1291. let _canvas;
  1292. class ImageUtils {
  1293. static getDataURL( image ) {
  1294. if ( /^data:/i.test( image.src ) ) {
  1295. return image.src;
  1296. }
  1297. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1298. return image.src;
  1299. }
  1300. let canvas;
  1301. if ( image instanceof HTMLCanvasElement ) {
  1302. canvas = image;
  1303. } else {
  1304. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1305. _canvas.width = image.width;
  1306. _canvas.height = image.height;
  1307. const context = _canvas.getContext( '2d' );
  1308. if ( image instanceof ImageData ) {
  1309. context.putImageData( image, 0, 0 );
  1310. } else {
  1311. context.drawImage( image, 0, 0, image.width, image.height );
  1312. }
  1313. canvas = _canvas;
  1314. }
  1315. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1316. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1317. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1318. } else {
  1319. return canvas.toDataURL( 'image/png' );
  1320. }
  1321. }
  1322. static sRGBToLinear( image ) {
  1323. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1324. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1325. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1326. const canvas = createElementNS( 'canvas' );
  1327. canvas.width = image.width;
  1328. canvas.height = image.height;
  1329. const context = canvas.getContext( '2d' );
  1330. context.drawImage( image, 0, 0, image.width, image.height );
  1331. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1332. const data = imageData.data;
  1333. for ( let i = 0; i < data.length; i ++ ) {
  1334. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1335. }
  1336. context.putImageData( imageData, 0, 0 );
  1337. return canvas;
  1338. } else if ( image.data ) {
  1339. const data = image.data.slice( 0 );
  1340. for ( let i = 0; i < data.length; i ++ ) {
  1341. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1342. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1343. } else {
  1344. // assuming float
  1345. data[ i ] = SRGBToLinear( data[ i ] );
  1346. }
  1347. }
  1348. return {
  1349. data: data,
  1350. width: image.width,
  1351. height: image.height
  1352. };
  1353. } else {
  1354. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1355. return image;
  1356. }
  1357. }
  1358. }
  1359. class Source {
  1360. constructor( data = null ) {
  1361. this.isSource = true;
  1362. this.uuid = generateUUID();
  1363. this.data = data;
  1364. this.version = 0;
  1365. }
  1366. set needsUpdate( value ) {
  1367. if ( value === true ) this.version ++;
  1368. }
  1369. toJSON( meta ) {
  1370. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1371. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1372. return meta.images[ this.uuid ];
  1373. }
  1374. const output = {
  1375. uuid: this.uuid,
  1376. url: ''
  1377. };
  1378. const data = this.data;
  1379. if ( data !== null ) {
  1380. let url;
  1381. if ( Array.isArray( data ) ) {
  1382. // cube texture
  1383. url = [];
  1384. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1385. if ( data[ i ].isDataTexture ) {
  1386. url.push( serializeImage( data[ i ].image ) );
  1387. } else {
  1388. url.push( serializeImage( data[ i ] ) );
  1389. }
  1390. }
  1391. } else {
  1392. // texture
  1393. url = serializeImage( data );
  1394. }
  1395. output.url = url;
  1396. }
  1397. if ( ! isRootObject ) {
  1398. meta.images[ this.uuid ] = output;
  1399. }
  1400. return output;
  1401. }
  1402. }
  1403. function serializeImage( image ) {
  1404. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1405. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1406. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1407. // default images
  1408. return ImageUtils.getDataURL( image );
  1409. } else {
  1410. if ( image.data ) {
  1411. // images of DataTexture
  1412. return {
  1413. data: Array.from( image.data ),
  1414. width: image.width,
  1415. height: image.height,
  1416. type: image.data.constructor.name
  1417. };
  1418. } else {
  1419. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1420. return {};
  1421. }
  1422. }
  1423. }
  1424. let textureId = 0;
  1425. class Texture extends EventDispatcher {
  1426. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {
  1427. super();
  1428. this.isTexture = true;
  1429. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1430. this.uuid = generateUUID();
  1431. this.name = '';
  1432. this.source = new Source( image );
  1433. this.mipmaps = [];
  1434. this.mapping = mapping;
  1435. this.wrapS = wrapS;
  1436. this.wrapT = wrapT;
  1437. this.magFilter = magFilter;
  1438. this.minFilter = minFilter;
  1439. this.anisotropy = anisotropy;
  1440. this.format = format;
  1441. this.internalFormat = null;
  1442. this.type = type;
  1443. this.offset = new Vector2( 0, 0 );
  1444. this.repeat = new Vector2( 1, 1 );
  1445. this.center = new Vector2( 0, 0 );
  1446. this.rotation = 0;
  1447. this.matrixAutoUpdate = true;
  1448. this.matrix = new Matrix3();
  1449. this.generateMipmaps = true;
  1450. this.premultiplyAlpha = false;
  1451. this.flipY = true;
  1452. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1453. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1454. //
  1455. // Also changing the encoding after already used by a Material will not automatically make the Material
  1456. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1457. this.encoding = encoding;
  1458. this.userData = {};
  1459. this.version = 0;
  1460. this.onUpdate = null;
  1461. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1462. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1463. }
  1464. get image() {
  1465. return this.source.data;
  1466. }
  1467. set image( value ) {
  1468. this.source.data = value;
  1469. }
  1470. updateMatrix() {
  1471. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1472. }
  1473. clone() {
  1474. return new this.constructor().copy( this );
  1475. }
  1476. copy( source ) {
  1477. this.name = source.name;
  1478. this.source = source.source;
  1479. this.mipmaps = source.mipmaps.slice( 0 );
  1480. this.mapping = source.mapping;
  1481. this.wrapS = source.wrapS;
  1482. this.wrapT = source.wrapT;
  1483. this.magFilter = source.magFilter;
  1484. this.minFilter = source.minFilter;
  1485. this.anisotropy = source.anisotropy;
  1486. this.format = source.format;
  1487. this.internalFormat = source.internalFormat;
  1488. this.type = source.type;
  1489. this.offset.copy( source.offset );
  1490. this.repeat.copy( source.repeat );
  1491. this.center.copy( source.center );
  1492. this.rotation = source.rotation;
  1493. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1494. this.matrix.copy( source.matrix );
  1495. this.generateMipmaps = source.generateMipmaps;
  1496. this.premultiplyAlpha = source.premultiplyAlpha;
  1497. this.flipY = source.flipY;
  1498. this.unpackAlignment = source.unpackAlignment;
  1499. this.encoding = source.encoding;
  1500. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1501. this.needsUpdate = true;
  1502. return this;
  1503. }
  1504. toJSON( meta ) {
  1505. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1506. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1507. return meta.textures[ this.uuid ];
  1508. }
  1509. const output = {
  1510. metadata: {
  1511. version: 4.5,
  1512. type: 'Texture',
  1513. generator: 'Texture.toJSON'
  1514. },
  1515. uuid: this.uuid,
  1516. name: this.name,
  1517. image: this.source.toJSON( meta ).uuid,
  1518. mapping: this.mapping,
  1519. repeat: [ this.repeat.x, this.repeat.y ],
  1520. offset: [ this.offset.x, this.offset.y ],
  1521. center: [ this.center.x, this.center.y ],
  1522. rotation: this.rotation,
  1523. wrap: [ this.wrapS, this.wrapT ],
  1524. format: this.format,
  1525. type: this.type,
  1526. encoding: this.encoding,
  1527. minFilter: this.minFilter,
  1528. magFilter: this.magFilter,
  1529. anisotropy: this.anisotropy,
  1530. flipY: this.flipY,
  1531. premultiplyAlpha: this.premultiplyAlpha,
  1532. unpackAlignment: this.unpackAlignment
  1533. };
  1534. if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData;
  1535. if ( ! isRootObject ) {
  1536. meta.textures[ this.uuid ] = output;
  1537. }
  1538. return output;
  1539. }
  1540. dispose() {
  1541. this.dispatchEvent( { type: 'dispose' } );
  1542. }
  1543. transformUv( uv ) {
  1544. if ( this.mapping !== UVMapping ) return uv;
  1545. uv.applyMatrix3( this.matrix );
  1546. if ( uv.x < 0 || uv.x > 1 ) {
  1547. switch ( this.wrapS ) {
  1548. case RepeatWrapping:
  1549. uv.x = uv.x - Math.floor( uv.x );
  1550. break;
  1551. case ClampToEdgeWrapping:
  1552. uv.x = uv.x < 0 ? 0 : 1;
  1553. break;
  1554. case MirroredRepeatWrapping:
  1555. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1556. uv.x = Math.ceil( uv.x ) - uv.x;
  1557. } else {
  1558. uv.x = uv.x - Math.floor( uv.x );
  1559. }
  1560. break;
  1561. }
  1562. }
  1563. if ( uv.y < 0 || uv.y > 1 ) {
  1564. switch ( this.wrapT ) {
  1565. case RepeatWrapping:
  1566. uv.y = uv.y - Math.floor( uv.y );
  1567. break;
  1568. case ClampToEdgeWrapping:
  1569. uv.y = uv.y < 0 ? 0 : 1;
  1570. break;
  1571. case MirroredRepeatWrapping:
  1572. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1573. uv.y = Math.ceil( uv.y ) - uv.y;
  1574. } else {
  1575. uv.y = uv.y - Math.floor( uv.y );
  1576. }
  1577. break;
  1578. }
  1579. }
  1580. if ( this.flipY ) {
  1581. uv.y = 1 - uv.y;
  1582. }
  1583. return uv;
  1584. }
  1585. set needsUpdate( value ) {
  1586. if ( value === true ) {
  1587. this.version ++;
  1588. this.source.needsUpdate = true;
  1589. }
  1590. }
  1591. }
  1592. Texture.DEFAULT_IMAGE = null;
  1593. Texture.DEFAULT_MAPPING = UVMapping;
  1594. class Vector4 {
  1595. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1596. Vector4.prototype.isVector4 = true;
  1597. this.x = x;
  1598. this.y = y;
  1599. this.z = z;
  1600. this.w = w;
  1601. }
  1602. get width() {
  1603. return this.z;
  1604. }
  1605. set width( value ) {
  1606. this.z = value;
  1607. }
  1608. get height() {
  1609. return this.w;
  1610. }
  1611. set height( value ) {
  1612. this.w = value;
  1613. }
  1614. set( x, y, z, w ) {
  1615. this.x = x;
  1616. this.y = y;
  1617. this.z = z;
  1618. this.w = w;
  1619. return this;
  1620. }
  1621. setScalar( scalar ) {
  1622. this.x = scalar;
  1623. this.y = scalar;
  1624. this.z = scalar;
  1625. this.w = scalar;
  1626. return this;
  1627. }
  1628. setX( x ) {
  1629. this.x = x;
  1630. return this;
  1631. }
  1632. setY( y ) {
  1633. this.y = y;
  1634. return this;
  1635. }
  1636. setZ( z ) {
  1637. this.z = z;
  1638. return this;
  1639. }
  1640. setW( w ) {
  1641. this.w = w;
  1642. return this;
  1643. }
  1644. setComponent( index, value ) {
  1645. switch ( index ) {
  1646. case 0: this.x = value; break;
  1647. case 1: this.y = value; break;
  1648. case 2: this.z = value; break;
  1649. case 3: this.w = value; break;
  1650. default: throw new Error( 'index is out of range: ' + index );
  1651. }
  1652. return this;
  1653. }
  1654. getComponent( index ) {
  1655. switch ( index ) {
  1656. case 0: return this.x;
  1657. case 1: return this.y;
  1658. case 2: return this.z;
  1659. case 3: return this.w;
  1660. default: throw new Error( 'index is out of range: ' + index );
  1661. }
  1662. }
  1663. clone() {
  1664. return new this.constructor( this.x, this.y, this.z, this.w );
  1665. }
  1666. copy( v ) {
  1667. this.x = v.x;
  1668. this.y = v.y;
  1669. this.z = v.z;
  1670. this.w = ( v.w !== undefined ) ? v.w : 1;
  1671. return this;
  1672. }
  1673. add( v ) {
  1674. this.x += v.x;
  1675. this.y += v.y;
  1676. this.z += v.z;
  1677. this.w += v.w;
  1678. return this;
  1679. }
  1680. addScalar( s ) {
  1681. this.x += s;
  1682. this.y += s;
  1683. this.z += s;
  1684. this.w += s;
  1685. return this;
  1686. }
  1687. addVectors( a, b ) {
  1688. this.x = a.x + b.x;
  1689. this.y = a.y + b.y;
  1690. this.z = a.z + b.z;
  1691. this.w = a.w + b.w;
  1692. return this;
  1693. }
  1694. addScaledVector( v, s ) {
  1695. this.x += v.x * s;
  1696. this.y += v.y * s;
  1697. this.z += v.z * s;
  1698. this.w += v.w * s;
  1699. return this;
  1700. }
  1701. sub( v ) {
  1702. this.x -= v.x;
  1703. this.y -= v.y;
  1704. this.z -= v.z;
  1705. this.w -= v.w;
  1706. return this;
  1707. }
  1708. subScalar( s ) {
  1709. this.x -= s;
  1710. this.y -= s;
  1711. this.z -= s;
  1712. this.w -= s;
  1713. return this;
  1714. }
  1715. subVectors( a, b ) {
  1716. this.x = a.x - b.x;
  1717. this.y = a.y - b.y;
  1718. this.z = a.z - b.z;
  1719. this.w = a.w - b.w;
  1720. return this;
  1721. }
  1722. multiply( v ) {
  1723. this.x *= v.x;
  1724. this.y *= v.y;
  1725. this.z *= v.z;
  1726. this.w *= v.w;
  1727. return this;
  1728. }
  1729. multiplyScalar( scalar ) {
  1730. this.x *= scalar;
  1731. this.y *= scalar;
  1732. this.z *= scalar;
  1733. this.w *= scalar;
  1734. return this;
  1735. }
  1736. applyMatrix4( m ) {
  1737. const x = this.x, y = this.y, z = this.z, w = this.w;
  1738. const e = m.elements;
  1739. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1740. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1741. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1742. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1743. return this;
  1744. }
  1745. divideScalar( scalar ) {
  1746. return this.multiplyScalar( 1 / scalar );
  1747. }
  1748. setAxisAngleFromQuaternion( q ) {
  1749. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1750. // q is assumed to be normalized
  1751. this.w = 2 * Math.acos( q.w );
  1752. const s = Math.sqrt( 1 - q.w * q.w );
  1753. if ( s < 0.0001 ) {
  1754. this.x = 1;
  1755. this.y = 0;
  1756. this.z = 0;
  1757. } else {
  1758. this.x = q.x / s;
  1759. this.y = q.y / s;
  1760. this.z = q.z / s;
  1761. }
  1762. return this;
  1763. }
  1764. setAxisAngleFromRotationMatrix( m ) {
  1765. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1766. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1767. let angle, x, y, z; // variables for result
  1768. const epsilon = 0.01, // margin to allow for rounding errors
  1769. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1770. te = m.elements,
  1771. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1772. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1773. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1774. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1775. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1776. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1777. // singularity found
  1778. // first check for identity matrix which must have +1 for all terms
  1779. // in leading diagonal and zero in other terms
  1780. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1781. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1782. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1783. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1784. // this singularity is identity matrix so angle = 0
  1785. this.set( 1, 0, 0, 0 );
  1786. return this; // zero angle, arbitrary axis
  1787. }
  1788. // otherwise this singularity is angle = 180
  1789. angle = Math.PI;
  1790. const xx = ( m11 + 1 ) / 2;
  1791. const yy = ( m22 + 1 ) / 2;
  1792. const zz = ( m33 + 1 ) / 2;
  1793. const xy = ( m12 + m21 ) / 4;
  1794. const xz = ( m13 + m31 ) / 4;
  1795. const yz = ( m23 + m32 ) / 4;
  1796. if ( ( xx > yy ) && ( xx > zz ) ) {
  1797. // m11 is the largest diagonal term
  1798. if ( xx < epsilon ) {
  1799. x = 0;
  1800. y = 0.707106781;
  1801. z = 0.707106781;
  1802. } else {
  1803. x = Math.sqrt( xx );
  1804. y = xy / x;
  1805. z = xz / x;
  1806. }
  1807. } else if ( yy > zz ) {
  1808. // m22 is the largest diagonal term
  1809. if ( yy < epsilon ) {
  1810. x = 0.707106781;
  1811. y = 0;
  1812. z = 0.707106781;
  1813. } else {
  1814. y = Math.sqrt( yy );
  1815. x = xy / y;
  1816. z = yz / y;
  1817. }
  1818. } else {
  1819. // m33 is the largest diagonal term so base result on this
  1820. if ( zz < epsilon ) {
  1821. x = 0.707106781;
  1822. y = 0.707106781;
  1823. z = 0;
  1824. } else {
  1825. z = Math.sqrt( zz );
  1826. x = xz / z;
  1827. y = yz / z;
  1828. }
  1829. }
  1830. this.set( x, y, z, angle );
  1831. return this; // return 180 deg rotation
  1832. }
  1833. // as we have reached here there are no singularities so we can handle normally
  1834. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1835. ( m13 - m31 ) * ( m13 - m31 ) +
  1836. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1837. if ( Math.abs( s ) < 0.001 ) s = 1;
  1838. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1839. // caught by singularity test above, but I've left it in just in case
  1840. this.x = ( m32 - m23 ) / s;
  1841. this.y = ( m13 - m31 ) / s;
  1842. this.z = ( m21 - m12 ) / s;
  1843. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1844. return this;
  1845. }
  1846. min( v ) {
  1847. this.x = Math.min( this.x, v.x );
  1848. this.y = Math.min( this.y, v.y );
  1849. this.z = Math.min( this.z, v.z );
  1850. this.w = Math.min( this.w, v.w );
  1851. return this;
  1852. }
  1853. max( v ) {
  1854. this.x = Math.max( this.x, v.x );
  1855. this.y = Math.max( this.y, v.y );
  1856. this.z = Math.max( this.z, v.z );
  1857. this.w = Math.max( this.w, v.w );
  1858. return this;
  1859. }
  1860. clamp( min, max ) {
  1861. // assumes min < max, componentwise
  1862. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1863. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1864. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1865. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1866. return this;
  1867. }
  1868. clampScalar( minVal, maxVal ) {
  1869. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1870. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1871. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1872. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1873. return this;
  1874. }
  1875. clampLength( min, max ) {
  1876. const length = this.length();
  1877. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1878. }
  1879. floor() {
  1880. this.x = Math.floor( this.x );
  1881. this.y = Math.floor( this.y );
  1882. this.z = Math.floor( this.z );
  1883. this.w = Math.floor( this.w );
  1884. return this;
  1885. }
  1886. ceil() {
  1887. this.x = Math.ceil( this.x );
  1888. this.y = Math.ceil( this.y );
  1889. this.z = Math.ceil( this.z );
  1890. this.w = Math.ceil( this.w );
  1891. return this;
  1892. }
  1893. round() {
  1894. this.x = Math.round( this.x );
  1895. this.y = Math.round( this.y );
  1896. this.z = Math.round( this.z );
  1897. this.w = Math.round( this.w );
  1898. return this;
  1899. }
  1900. roundToZero() {
  1901. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1902. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1903. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1904. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1905. return this;
  1906. }
  1907. negate() {
  1908. this.x = - this.x;
  1909. this.y = - this.y;
  1910. this.z = - this.z;
  1911. this.w = - this.w;
  1912. return this;
  1913. }
  1914. dot( v ) {
  1915. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1916. }
  1917. lengthSq() {
  1918. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1919. }
  1920. length() {
  1921. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1922. }
  1923. manhattanLength() {
  1924. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1925. }
  1926. normalize() {
  1927. return this.divideScalar( this.length() || 1 );
  1928. }
  1929. setLength( length ) {
  1930. return this.normalize().multiplyScalar( length );
  1931. }
  1932. lerp( v, alpha ) {
  1933. this.x += ( v.x - this.x ) * alpha;
  1934. this.y += ( v.y - this.y ) * alpha;
  1935. this.z += ( v.z - this.z ) * alpha;
  1936. this.w += ( v.w - this.w ) * alpha;
  1937. return this;
  1938. }
  1939. lerpVectors( v1, v2, alpha ) {
  1940. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1941. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1942. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1943. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1944. return this;
  1945. }
  1946. equals( v ) {
  1947. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1948. }
  1949. fromArray( array, offset = 0 ) {
  1950. this.x = array[ offset ];
  1951. this.y = array[ offset + 1 ];
  1952. this.z = array[ offset + 2 ];
  1953. this.w = array[ offset + 3 ];
  1954. return this;
  1955. }
  1956. toArray( array = [], offset = 0 ) {
  1957. array[ offset ] = this.x;
  1958. array[ offset + 1 ] = this.y;
  1959. array[ offset + 2 ] = this.z;
  1960. array[ offset + 3 ] = this.w;
  1961. return array;
  1962. }
  1963. fromBufferAttribute( attribute, index ) {
  1964. this.x = attribute.getX( index );
  1965. this.y = attribute.getY( index );
  1966. this.z = attribute.getZ( index );
  1967. this.w = attribute.getW( index );
  1968. return this;
  1969. }
  1970. random() {
  1971. this.x = Math.random();
  1972. this.y = Math.random();
  1973. this.z = Math.random();
  1974. this.w = Math.random();
  1975. return this;
  1976. }
  1977. *[ Symbol.iterator ]() {
  1978. yield this.x;
  1979. yield this.y;
  1980. yield this.z;
  1981. yield this.w;
  1982. }
  1983. }
  1984. /*
  1985. In options, we can specify:
  1986. * Texture parameters for an auto-generated target texture
  1987. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1988. */
  1989. class WebGLRenderTarget extends EventDispatcher {
  1990. constructor( width, height, options = {} ) {
  1991. super();
  1992. this.isWebGLRenderTarget = true;
  1993. this.width = width;
  1994. this.height = height;
  1995. this.depth = 1;
  1996. this.scissor = new Vector4( 0, 0, width, height );
  1997. this.scissorTest = false;
  1998. this.viewport = new Vector4( 0, 0, width, height );
  1999. const image = { width: width, height: height, depth: 1 };
  2000. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2001. this.texture.isRenderTargetTexture = true;
  2002. this.texture.flipY = false;
  2003. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2004. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2005. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2006. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2007. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2008. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2009. this.samples = options.samples !== undefined ? options.samples : 0;
  2010. }
  2011. setSize( width, height, depth = 1 ) {
  2012. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2013. this.width = width;
  2014. this.height = height;
  2015. this.depth = depth;
  2016. this.texture.image.width = width;
  2017. this.texture.image.height = height;
  2018. this.texture.image.depth = depth;
  2019. this.dispose();
  2020. }
  2021. this.viewport.set( 0, 0, width, height );
  2022. this.scissor.set( 0, 0, width, height );
  2023. }
  2024. clone() {
  2025. return new this.constructor().copy( this );
  2026. }
  2027. copy( source ) {
  2028. this.width = source.width;
  2029. this.height = source.height;
  2030. this.depth = source.depth;
  2031. this.viewport.copy( source.viewport );
  2032. this.texture = source.texture.clone();
  2033. this.texture.isRenderTargetTexture = true;
  2034. // ensure image object is not shared, see #20328
  2035. const image = Object.assign( {}, source.texture.image );
  2036. this.texture.source = new Source( image );
  2037. this.depthBuffer = source.depthBuffer;
  2038. this.stencilBuffer = source.stencilBuffer;
  2039. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2040. this.samples = source.samples;
  2041. return this;
  2042. }
  2043. dispose() {
  2044. this.dispatchEvent( { type: 'dispose' } );
  2045. }
  2046. }
  2047. class DataArrayTexture extends Texture {
  2048. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2049. super( null );
  2050. this.isDataArrayTexture = true;
  2051. this.image = { data, width, height, depth };
  2052. this.magFilter = NearestFilter;
  2053. this.minFilter = NearestFilter;
  2054. this.wrapR = ClampToEdgeWrapping;
  2055. this.generateMipmaps = false;
  2056. this.flipY = false;
  2057. this.unpackAlignment = 1;
  2058. }
  2059. }
  2060. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2061. constructor( width, height, depth ) {
  2062. super( width, height );
  2063. this.isWebGLArrayRenderTarget = true;
  2064. this.depth = depth;
  2065. this.texture = new DataArrayTexture( null, width, height, depth );
  2066. this.texture.isRenderTargetTexture = true;
  2067. }
  2068. }
  2069. class Data3DTexture extends Texture {
  2070. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2071. // We're going to add .setXXX() methods for setting properties later.
  2072. // Users can still set in DataTexture3D directly.
  2073. //
  2074. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2075. // texture.anisotropy = 16;
  2076. //
  2077. // See #14839
  2078. super( null );
  2079. this.isData3DTexture = true;
  2080. this.image = { data, width, height, depth };
  2081. this.magFilter = NearestFilter;
  2082. this.minFilter = NearestFilter;
  2083. this.wrapR = ClampToEdgeWrapping;
  2084. this.generateMipmaps = false;
  2085. this.flipY = false;
  2086. this.unpackAlignment = 1;
  2087. }
  2088. }
  2089. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2090. constructor( width, height, depth ) {
  2091. super( width, height );
  2092. this.isWebGL3DRenderTarget = true;
  2093. this.depth = depth;
  2094. this.texture = new Data3DTexture( null, width, height, depth );
  2095. this.texture.isRenderTargetTexture = true;
  2096. }
  2097. }
  2098. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2099. constructor( width, height, count, options = {} ) {
  2100. super( width, height, options );
  2101. this.isWebGLMultipleRenderTargets = true;
  2102. const texture = this.texture;
  2103. this.texture = [];
  2104. for ( let i = 0; i < count; i ++ ) {
  2105. this.texture[ i ] = texture.clone();
  2106. this.texture[ i ].isRenderTargetTexture = true;
  2107. }
  2108. }
  2109. setSize( width, height, depth = 1 ) {
  2110. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2111. this.width = width;
  2112. this.height = height;
  2113. this.depth = depth;
  2114. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2115. this.texture[ i ].image.width = width;
  2116. this.texture[ i ].image.height = height;
  2117. this.texture[ i ].image.depth = depth;
  2118. }
  2119. this.dispose();
  2120. }
  2121. this.viewport.set( 0, 0, width, height );
  2122. this.scissor.set( 0, 0, width, height );
  2123. return this;
  2124. }
  2125. copy( source ) {
  2126. this.dispose();
  2127. this.width = source.width;
  2128. this.height = source.height;
  2129. this.depth = source.depth;
  2130. this.viewport.set( 0, 0, this.width, this.height );
  2131. this.scissor.set( 0, 0, this.width, this.height );
  2132. this.depthBuffer = source.depthBuffer;
  2133. this.stencilBuffer = source.stencilBuffer;
  2134. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2135. this.texture.length = 0;
  2136. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2137. this.texture[ i ] = source.texture[ i ].clone();
  2138. this.texture[ i ].isRenderTargetTexture = true;
  2139. }
  2140. return this;
  2141. }
  2142. }
  2143. class Quaternion {
  2144. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2145. this.isQuaternion = true;
  2146. this._x = x;
  2147. this._y = y;
  2148. this._z = z;
  2149. this._w = w;
  2150. }
  2151. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2152. // fuzz-free, array-based Quaternion SLERP operation
  2153. let x0 = src0[ srcOffset0 + 0 ],
  2154. y0 = src0[ srcOffset0 + 1 ],
  2155. z0 = src0[ srcOffset0 + 2 ],
  2156. w0 = src0[ srcOffset0 + 3 ];
  2157. const x1 = src1[ srcOffset1 + 0 ],
  2158. y1 = src1[ srcOffset1 + 1 ],
  2159. z1 = src1[ srcOffset1 + 2 ],
  2160. w1 = src1[ srcOffset1 + 3 ];
  2161. if ( t === 0 ) {
  2162. dst[ dstOffset + 0 ] = x0;
  2163. dst[ dstOffset + 1 ] = y0;
  2164. dst[ dstOffset + 2 ] = z0;
  2165. dst[ dstOffset + 3 ] = w0;
  2166. return;
  2167. }
  2168. if ( t === 1 ) {
  2169. dst[ dstOffset + 0 ] = x1;
  2170. dst[ dstOffset + 1 ] = y1;
  2171. dst[ dstOffset + 2 ] = z1;
  2172. dst[ dstOffset + 3 ] = w1;
  2173. return;
  2174. }
  2175. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2176. let s = 1 - t;
  2177. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2178. dir = ( cos >= 0 ? 1 : - 1 ),
  2179. sqrSin = 1 - cos * cos;
  2180. // Skip the Slerp for tiny steps to avoid numeric problems:
  2181. if ( sqrSin > Number.EPSILON ) {
  2182. const sin = Math.sqrt( sqrSin ),
  2183. len = Math.atan2( sin, cos * dir );
  2184. s = Math.sin( s * len ) / sin;
  2185. t = Math.sin( t * len ) / sin;
  2186. }
  2187. const tDir = t * dir;
  2188. x0 = x0 * s + x1 * tDir;
  2189. y0 = y0 * s + y1 * tDir;
  2190. z0 = z0 * s + z1 * tDir;
  2191. w0 = w0 * s + w1 * tDir;
  2192. // Normalize in case we just did a lerp:
  2193. if ( s === 1 - t ) {
  2194. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2195. x0 *= f;
  2196. y0 *= f;
  2197. z0 *= f;
  2198. w0 *= f;
  2199. }
  2200. }
  2201. dst[ dstOffset ] = x0;
  2202. dst[ dstOffset + 1 ] = y0;
  2203. dst[ dstOffset + 2 ] = z0;
  2204. dst[ dstOffset + 3 ] = w0;
  2205. }
  2206. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2207. const x0 = src0[ srcOffset0 ];
  2208. const y0 = src0[ srcOffset0 + 1 ];
  2209. const z0 = src0[ srcOffset0 + 2 ];
  2210. const w0 = src0[ srcOffset0 + 3 ];
  2211. const x1 = src1[ srcOffset1 ];
  2212. const y1 = src1[ srcOffset1 + 1 ];
  2213. const z1 = src1[ srcOffset1 + 2 ];
  2214. const w1 = src1[ srcOffset1 + 3 ];
  2215. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2216. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2217. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2218. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2219. return dst;
  2220. }
  2221. get x() {
  2222. return this._x;
  2223. }
  2224. set x( value ) {
  2225. this._x = value;
  2226. this._onChangeCallback();
  2227. }
  2228. get y() {
  2229. return this._y;
  2230. }
  2231. set y( value ) {
  2232. this._y = value;
  2233. this._onChangeCallback();
  2234. }
  2235. get z() {
  2236. return this._z;
  2237. }
  2238. set z( value ) {
  2239. this._z = value;
  2240. this._onChangeCallback();
  2241. }
  2242. get w() {
  2243. return this._w;
  2244. }
  2245. set w( value ) {
  2246. this._w = value;
  2247. this._onChangeCallback();
  2248. }
  2249. set( x, y, z, w ) {
  2250. this._x = x;
  2251. this._y = y;
  2252. this._z = z;
  2253. this._w = w;
  2254. this._onChangeCallback();
  2255. return this;
  2256. }
  2257. clone() {
  2258. return new this.constructor( this._x, this._y, this._z, this._w );
  2259. }
  2260. copy( quaternion ) {
  2261. this._x = quaternion.x;
  2262. this._y = quaternion.y;
  2263. this._z = quaternion.z;
  2264. this._w = quaternion.w;
  2265. this._onChangeCallback();
  2266. return this;
  2267. }
  2268. setFromEuler( euler, update ) {
  2269. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2270. // http://www.mathworks.com/matlabcentral/fileexchange/
  2271. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2272. // content/SpinCalc.m
  2273. const cos = Math.cos;
  2274. const sin = Math.sin;
  2275. const c1 = cos( x / 2 );
  2276. const c2 = cos( y / 2 );
  2277. const c3 = cos( z / 2 );
  2278. const s1 = sin( x / 2 );
  2279. const s2 = sin( y / 2 );
  2280. const s3 = sin( z / 2 );
  2281. switch ( order ) {
  2282. case 'XYZ':
  2283. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2284. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2285. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2286. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2287. break;
  2288. case 'YXZ':
  2289. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2290. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2291. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2292. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2293. break;
  2294. case 'ZXY':
  2295. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2296. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2297. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2298. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2299. break;
  2300. case 'ZYX':
  2301. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2302. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2303. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2304. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2305. break;
  2306. case 'YZX':
  2307. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2308. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2309. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2310. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2311. break;
  2312. case 'XZY':
  2313. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2314. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2315. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2316. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2317. break;
  2318. default:
  2319. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2320. }
  2321. if ( update !== false ) this._onChangeCallback();
  2322. return this;
  2323. }
  2324. setFromAxisAngle( axis, angle ) {
  2325. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2326. // assumes axis is normalized
  2327. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2328. this._x = axis.x * s;
  2329. this._y = axis.y * s;
  2330. this._z = axis.z * s;
  2331. this._w = Math.cos( halfAngle );
  2332. this._onChangeCallback();
  2333. return this;
  2334. }
  2335. setFromRotationMatrix( m ) {
  2336. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2337. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2338. const te = m.elements,
  2339. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2340. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2341. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2342. trace = m11 + m22 + m33;
  2343. if ( trace > 0 ) {
  2344. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2345. this._w = 0.25 / s;
  2346. this._x = ( m32 - m23 ) * s;
  2347. this._y = ( m13 - m31 ) * s;
  2348. this._z = ( m21 - m12 ) * s;
  2349. } else if ( m11 > m22 && m11 > m33 ) {
  2350. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2351. this._w = ( m32 - m23 ) / s;
  2352. this._x = 0.25 * s;
  2353. this._y = ( m12 + m21 ) / s;
  2354. this._z = ( m13 + m31 ) / s;
  2355. } else if ( m22 > m33 ) {
  2356. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2357. this._w = ( m13 - m31 ) / s;
  2358. this._x = ( m12 + m21 ) / s;
  2359. this._y = 0.25 * s;
  2360. this._z = ( m23 + m32 ) / s;
  2361. } else {
  2362. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2363. this._w = ( m21 - m12 ) / s;
  2364. this._x = ( m13 + m31 ) / s;
  2365. this._y = ( m23 + m32 ) / s;
  2366. this._z = 0.25 * s;
  2367. }
  2368. this._onChangeCallback();
  2369. return this;
  2370. }
  2371. setFromUnitVectors( vFrom, vTo ) {
  2372. // assumes direction vectors vFrom and vTo are normalized
  2373. let r = vFrom.dot( vTo ) + 1;
  2374. if ( r < Number.EPSILON ) {
  2375. // vFrom and vTo point in opposite directions
  2376. r = 0;
  2377. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2378. this._x = - vFrom.y;
  2379. this._y = vFrom.x;
  2380. this._z = 0;
  2381. this._w = r;
  2382. } else {
  2383. this._x = 0;
  2384. this._y = - vFrom.z;
  2385. this._z = vFrom.y;
  2386. this._w = r;
  2387. }
  2388. } else {
  2389. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2390. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2391. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2392. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2393. this._w = r;
  2394. }
  2395. return this.normalize();
  2396. }
  2397. angleTo( q ) {
  2398. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2399. }
  2400. rotateTowards( q, step ) {
  2401. const angle = this.angleTo( q );
  2402. if ( angle === 0 ) return this;
  2403. const t = Math.min( 1, step / angle );
  2404. this.slerp( q, t );
  2405. return this;
  2406. }
  2407. identity() {
  2408. return this.set( 0, 0, 0, 1 );
  2409. }
  2410. invert() {
  2411. // quaternion is assumed to have unit length
  2412. return this.conjugate();
  2413. }
  2414. conjugate() {
  2415. this._x *= - 1;
  2416. this._y *= - 1;
  2417. this._z *= - 1;
  2418. this._onChangeCallback();
  2419. return this;
  2420. }
  2421. dot( v ) {
  2422. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2423. }
  2424. lengthSq() {
  2425. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2426. }
  2427. length() {
  2428. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2429. }
  2430. normalize() {
  2431. let l = this.length();
  2432. if ( l === 0 ) {
  2433. this._x = 0;
  2434. this._y = 0;
  2435. this._z = 0;
  2436. this._w = 1;
  2437. } else {
  2438. l = 1 / l;
  2439. this._x = this._x * l;
  2440. this._y = this._y * l;
  2441. this._z = this._z * l;
  2442. this._w = this._w * l;
  2443. }
  2444. this._onChangeCallback();
  2445. return this;
  2446. }
  2447. multiply( q ) {
  2448. return this.multiplyQuaternions( this, q );
  2449. }
  2450. premultiply( q ) {
  2451. return this.multiplyQuaternions( q, this );
  2452. }
  2453. multiplyQuaternions( a, b ) {
  2454. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2455. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2456. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2457. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2458. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2459. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2460. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2461. this._onChangeCallback();
  2462. return this;
  2463. }
  2464. slerp( qb, t ) {
  2465. if ( t === 0 ) return this;
  2466. if ( t === 1 ) return this.copy( qb );
  2467. const x = this._x, y = this._y, z = this._z, w = this._w;
  2468. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2469. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2470. if ( cosHalfTheta < 0 ) {
  2471. this._w = - qb._w;
  2472. this._x = - qb._x;
  2473. this._y = - qb._y;
  2474. this._z = - qb._z;
  2475. cosHalfTheta = - cosHalfTheta;
  2476. } else {
  2477. this.copy( qb );
  2478. }
  2479. if ( cosHalfTheta >= 1.0 ) {
  2480. this._w = w;
  2481. this._x = x;
  2482. this._y = y;
  2483. this._z = z;
  2484. return this;
  2485. }
  2486. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2487. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2488. const s = 1 - t;
  2489. this._w = s * w + t * this._w;
  2490. this._x = s * x + t * this._x;
  2491. this._y = s * y + t * this._y;
  2492. this._z = s * z + t * this._z;
  2493. this.normalize();
  2494. this._onChangeCallback();
  2495. return this;
  2496. }
  2497. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2498. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2499. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2500. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2501. this._w = ( w * ratioA + this._w * ratioB );
  2502. this._x = ( x * ratioA + this._x * ratioB );
  2503. this._y = ( y * ratioA + this._y * ratioB );
  2504. this._z = ( z * ratioA + this._z * ratioB );
  2505. this._onChangeCallback();
  2506. return this;
  2507. }
  2508. slerpQuaternions( qa, qb, t ) {
  2509. return this.copy( qa ).slerp( qb, t );
  2510. }
  2511. random() {
  2512. // Derived from http://planning.cs.uiuc.edu/node198.html
  2513. // Note, this source uses w, x, y, z ordering,
  2514. // so we swap the order below.
  2515. const u1 = Math.random();
  2516. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2517. const sqrtu1 = Math.sqrt( u1 );
  2518. const u2 = 2 * Math.PI * Math.random();
  2519. const u3 = 2 * Math.PI * Math.random();
  2520. return this.set(
  2521. sqrt1u1 * Math.cos( u2 ),
  2522. sqrtu1 * Math.sin( u3 ),
  2523. sqrtu1 * Math.cos( u3 ),
  2524. sqrt1u1 * Math.sin( u2 ),
  2525. );
  2526. }
  2527. equals( quaternion ) {
  2528. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2529. }
  2530. fromArray( array, offset = 0 ) {
  2531. this._x = array[ offset ];
  2532. this._y = array[ offset + 1 ];
  2533. this._z = array[ offset + 2 ];
  2534. this._w = array[ offset + 3 ];
  2535. this._onChangeCallback();
  2536. return this;
  2537. }
  2538. toArray( array = [], offset = 0 ) {
  2539. array[ offset ] = this._x;
  2540. array[ offset + 1 ] = this._y;
  2541. array[ offset + 2 ] = this._z;
  2542. array[ offset + 3 ] = this._w;
  2543. return array;
  2544. }
  2545. fromBufferAttribute( attribute, index ) {
  2546. this._x = attribute.getX( index );
  2547. this._y = attribute.getY( index );
  2548. this._z = attribute.getZ( index );
  2549. this._w = attribute.getW( index );
  2550. return this;
  2551. }
  2552. _onChange( callback ) {
  2553. this._onChangeCallback = callback;
  2554. return this;
  2555. }
  2556. _onChangeCallback() {}
  2557. *[ Symbol.iterator ]() {
  2558. yield this._x;
  2559. yield this._y;
  2560. yield this._z;
  2561. yield this._w;
  2562. }
  2563. }
  2564. class Vector3 {
  2565. constructor( x = 0, y = 0, z = 0 ) {
  2566. Vector3.prototype.isVector3 = true;
  2567. this.x = x;
  2568. this.y = y;
  2569. this.z = z;
  2570. }
  2571. set( x, y, z ) {
  2572. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2573. this.x = x;
  2574. this.y = y;
  2575. this.z = z;
  2576. return this;
  2577. }
  2578. setScalar( scalar ) {
  2579. this.x = scalar;
  2580. this.y = scalar;
  2581. this.z = scalar;
  2582. return this;
  2583. }
  2584. setX( x ) {
  2585. this.x = x;
  2586. return this;
  2587. }
  2588. setY( y ) {
  2589. this.y = y;
  2590. return this;
  2591. }
  2592. setZ( z ) {
  2593. this.z = z;
  2594. return this;
  2595. }
  2596. setComponent( index, value ) {
  2597. switch ( index ) {
  2598. case 0: this.x = value; break;
  2599. case 1: this.y = value; break;
  2600. case 2: this.z = value; break;
  2601. default: throw new Error( 'index is out of range: ' + index );
  2602. }
  2603. return this;
  2604. }
  2605. getComponent( index ) {
  2606. switch ( index ) {
  2607. case 0: return this.x;
  2608. case 1: return this.y;
  2609. case 2: return this.z;
  2610. default: throw new Error( 'index is out of range: ' + index );
  2611. }
  2612. }
  2613. clone() {
  2614. return new this.constructor( this.x, this.y, this.z );
  2615. }
  2616. copy( v ) {
  2617. this.x = v.x;
  2618. this.y = v.y;
  2619. this.z = v.z;
  2620. return this;
  2621. }
  2622. add( v ) {
  2623. this.x += v.x;
  2624. this.y += v.y;
  2625. this.z += v.z;
  2626. return this;
  2627. }
  2628. addScalar( s ) {
  2629. this.x += s;
  2630. this.y += s;
  2631. this.z += s;
  2632. return this;
  2633. }
  2634. addVectors( a, b ) {
  2635. this.x = a.x + b.x;
  2636. this.y = a.y + b.y;
  2637. this.z = a.z + b.z;
  2638. return this;
  2639. }
  2640. addScaledVector( v, s ) {
  2641. this.x += v.x * s;
  2642. this.y += v.y * s;
  2643. this.z += v.z * s;
  2644. return this;
  2645. }
  2646. sub( v ) {
  2647. this.x -= v.x;
  2648. this.y -= v.y;
  2649. this.z -= v.z;
  2650. return this;
  2651. }
  2652. subScalar( s ) {
  2653. this.x -= s;
  2654. this.y -= s;
  2655. this.z -= s;
  2656. return this;
  2657. }
  2658. subVectors( a, b ) {
  2659. this.x = a.x - b.x;
  2660. this.y = a.y - b.y;
  2661. this.z = a.z - b.z;
  2662. return this;
  2663. }
  2664. multiply( v ) {
  2665. this.x *= v.x;
  2666. this.y *= v.y;
  2667. this.z *= v.z;
  2668. return this;
  2669. }
  2670. multiplyScalar( scalar ) {
  2671. this.x *= scalar;
  2672. this.y *= scalar;
  2673. this.z *= scalar;
  2674. return this;
  2675. }
  2676. multiplyVectors( a, b ) {
  2677. this.x = a.x * b.x;
  2678. this.y = a.y * b.y;
  2679. this.z = a.z * b.z;
  2680. return this;
  2681. }
  2682. applyEuler( euler ) {
  2683. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2684. }
  2685. applyAxisAngle( axis, angle ) {
  2686. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2687. }
  2688. applyMatrix3( m ) {
  2689. const x = this.x, y = this.y, z = this.z;
  2690. const e = m.elements;
  2691. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2692. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2693. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2694. return this;
  2695. }
  2696. applyNormalMatrix( m ) {
  2697. return this.applyMatrix3( m ).normalize();
  2698. }
  2699. applyMatrix4( m ) {
  2700. const x = this.x, y = this.y, z = this.z;
  2701. const e = m.elements;
  2702. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2703. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2704. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2705. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2706. return this;
  2707. }
  2708. applyQuaternion( q ) {
  2709. const x = this.x, y = this.y, z = this.z;
  2710. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2711. // calculate quat * vector
  2712. const ix = qw * x + qy * z - qz * y;
  2713. const iy = qw * y + qz * x - qx * z;
  2714. const iz = qw * z + qx * y - qy * x;
  2715. const iw = - qx * x - qy * y - qz * z;
  2716. // calculate result * inverse quat
  2717. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2718. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2719. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2720. return this;
  2721. }
  2722. project( camera ) {
  2723. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2724. }
  2725. unproject( camera ) {
  2726. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2727. }
  2728. transformDirection( m ) {
  2729. // input: THREE.Matrix4 affine matrix
  2730. // vector interpreted as a direction
  2731. const x = this.x, y = this.y, z = this.z;
  2732. const e = m.elements;
  2733. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2734. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2735. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2736. return this.normalize();
  2737. }
  2738. divide( v ) {
  2739. this.x /= v.x;
  2740. this.y /= v.y;
  2741. this.z /= v.z;
  2742. return this;
  2743. }
  2744. divideScalar( scalar ) {
  2745. return this.multiplyScalar( 1 / scalar );
  2746. }
  2747. min( v ) {
  2748. this.x = Math.min( this.x, v.x );
  2749. this.y = Math.min( this.y, v.y );
  2750. this.z = Math.min( this.z, v.z );
  2751. return this;
  2752. }
  2753. max( v ) {
  2754. this.x = Math.max( this.x, v.x );
  2755. this.y = Math.max( this.y, v.y );
  2756. this.z = Math.max( this.z, v.z );
  2757. return this;
  2758. }
  2759. clamp( min, max ) {
  2760. // assumes min < max, componentwise
  2761. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2762. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2763. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2764. return this;
  2765. }
  2766. clampScalar( minVal, maxVal ) {
  2767. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2768. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2769. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2770. return this;
  2771. }
  2772. clampLength( min, max ) {
  2773. const length = this.length();
  2774. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2775. }
  2776. floor() {
  2777. this.x = Math.floor( this.x );
  2778. this.y = Math.floor( this.y );
  2779. this.z = Math.floor( this.z );
  2780. return this;
  2781. }
  2782. ceil() {
  2783. this.x = Math.ceil( this.x );
  2784. this.y = Math.ceil( this.y );
  2785. this.z = Math.ceil( this.z );
  2786. return this;
  2787. }
  2788. round() {
  2789. this.x = Math.round( this.x );
  2790. this.y = Math.round( this.y );
  2791. this.z = Math.round( this.z );
  2792. return this;
  2793. }
  2794. roundToZero() {
  2795. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2796. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2797. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2798. return this;
  2799. }
  2800. negate() {
  2801. this.x = - this.x;
  2802. this.y = - this.y;
  2803. this.z = - this.z;
  2804. return this;
  2805. }
  2806. dot( v ) {
  2807. return this.x * v.x + this.y * v.y + this.z * v.z;
  2808. }
  2809. // TODO lengthSquared?
  2810. lengthSq() {
  2811. return this.x * this.x + this.y * this.y + this.z * this.z;
  2812. }
  2813. length() {
  2814. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2815. }
  2816. manhattanLength() {
  2817. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2818. }
  2819. normalize() {
  2820. return this.divideScalar( this.length() || 1 );
  2821. }
  2822. setLength( length ) {
  2823. return this.normalize().multiplyScalar( length );
  2824. }
  2825. lerp( v, alpha ) {
  2826. this.x += ( v.x - this.x ) * alpha;
  2827. this.y += ( v.y - this.y ) * alpha;
  2828. this.z += ( v.z - this.z ) * alpha;
  2829. return this;
  2830. }
  2831. lerpVectors( v1, v2, alpha ) {
  2832. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2833. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2834. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2835. return this;
  2836. }
  2837. cross( v ) {
  2838. return this.crossVectors( this, v );
  2839. }
  2840. crossVectors( a, b ) {
  2841. const ax = a.x, ay = a.y, az = a.z;
  2842. const bx = b.x, by = b.y, bz = b.z;
  2843. this.x = ay * bz - az * by;
  2844. this.y = az * bx - ax * bz;
  2845. this.z = ax * by - ay * bx;
  2846. return this;
  2847. }
  2848. projectOnVector( v ) {
  2849. const denominator = v.lengthSq();
  2850. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2851. const scalar = v.dot( this ) / denominator;
  2852. return this.copy( v ).multiplyScalar( scalar );
  2853. }
  2854. projectOnPlane( planeNormal ) {
  2855. _vector$c.copy( this ).projectOnVector( planeNormal );
  2856. return this.sub( _vector$c );
  2857. }
  2858. reflect( normal ) {
  2859. // reflect incident vector off plane orthogonal to normal
  2860. // normal is assumed to have unit length
  2861. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2862. }
  2863. angleTo( v ) {
  2864. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2865. if ( denominator === 0 ) return Math.PI / 2;
  2866. const theta = this.dot( v ) / denominator;
  2867. // clamp, to handle numerical problems
  2868. return Math.acos( clamp( theta, - 1, 1 ) );
  2869. }
  2870. distanceTo( v ) {
  2871. return Math.sqrt( this.distanceToSquared( v ) );
  2872. }
  2873. distanceToSquared( v ) {
  2874. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2875. return dx * dx + dy * dy + dz * dz;
  2876. }
  2877. manhattanDistanceTo( v ) {
  2878. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2879. }
  2880. setFromSpherical( s ) {
  2881. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2882. }
  2883. setFromSphericalCoords( radius, phi, theta ) {
  2884. const sinPhiRadius = Math.sin( phi ) * radius;
  2885. this.x = sinPhiRadius * Math.sin( theta );
  2886. this.y = Math.cos( phi ) * radius;
  2887. this.z = sinPhiRadius * Math.cos( theta );
  2888. return this;
  2889. }
  2890. setFromCylindrical( c ) {
  2891. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2892. }
  2893. setFromCylindricalCoords( radius, theta, y ) {
  2894. this.x = radius * Math.sin( theta );
  2895. this.y = y;
  2896. this.z = radius * Math.cos( theta );
  2897. return this;
  2898. }
  2899. setFromMatrixPosition( m ) {
  2900. const e = m.elements;
  2901. this.x = e[ 12 ];
  2902. this.y = e[ 13 ];
  2903. this.z = e[ 14 ];
  2904. return this;
  2905. }
  2906. setFromMatrixScale( m ) {
  2907. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2908. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2909. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2910. this.x = sx;
  2911. this.y = sy;
  2912. this.z = sz;
  2913. return this;
  2914. }
  2915. setFromMatrixColumn( m, index ) {
  2916. return this.fromArray( m.elements, index * 4 );
  2917. }
  2918. setFromMatrix3Column( m, index ) {
  2919. return this.fromArray( m.elements, index * 3 );
  2920. }
  2921. setFromEuler( e ) {
  2922. this.x = e._x;
  2923. this.y = e._y;
  2924. this.z = e._z;
  2925. return this;
  2926. }
  2927. equals( v ) {
  2928. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2929. }
  2930. fromArray( array, offset = 0 ) {
  2931. this.x = array[ offset ];
  2932. this.y = array[ offset + 1 ];
  2933. this.z = array[ offset + 2 ];
  2934. return this;
  2935. }
  2936. toArray( array = [], offset = 0 ) {
  2937. array[ offset ] = this.x;
  2938. array[ offset + 1 ] = this.y;
  2939. array[ offset + 2 ] = this.z;
  2940. return array;
  2941. }
  2942. fromBufferAttribute( attribute, index ) {
  2943. this.x = attribute.getX( index );
  2944. this.y = attribute.getY( index );
  2945. this.z = attribute.getZ( index );
  2946. return this;
  2947. }
  2948. random() {
  2949. this.x = Math.random();
  2950. this.y = Math.random();
  2951. this.z = Math.random();
  2952. return this;
  2953. }
  2954. randomDirection() {
  2955. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2956. const u = ( Math.random() - 0.5 ) * 2;
  2957. const t = Math.random() * Math.PI * 2;
  2958. const f = Math.sqrt( 1 - u ** 2 );
  2959. this.x = f * Math.cos( t );
  2960. this.y = f * Math.sin( t );
  2961. this.z = u;
  2962. return this;
  2963. }
  2964. *[ Symbol.iterator ]() {
  2965. yield this.x;
  2966. yield this.y;
  2967. yield this.z;
  2968. }
  2969. }
  2970. const _vector$c = /*@__PURE__*/ new Vector3();
  2971. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2972. class Box3 {
  2973. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2974. this.isBox3 = true;
  2975. this.min = min;
  2976. this.max = max;
  2977. }
  2978. set( min, max ) {
  2979. this.min.copy( min );
  2980. this.max.copy( max );
  2981. return this;
  2982. }
  2983. setFromArray( array ) {
  2984. let minX = + Infinity;
  2985. let minY = + Infinity;
  2986. let minZ = + Infinity;
  2987. let maxX = - Infinity;
  2988. let maxY = - Infinity;
  2989. let maxZ = - Infinity;
  2990. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2991. const x = array[ i ];
  2992. const y = array[ i + 1 ];
  2993. const z = array[ i + 2 ];
  2994. if ( x < minX ) minX = x;
  2995. if ( y < minY ) minY = y;
  2996. if ( z < minZ ) minZ = z;
  2997. if ( x > maxX ) maxX = x;
  2998. if ( y > maxY ) maxY = y;
  2999. if ( z > maxZ ) maxZ = z;
  3000. }
  3001. this.min.set( minX, minY, minZ );
  3002. this.max.set( maxX, maxY, maxZ );
  3003. return this;
  3004. }
  3005. setFromBufferAttribute( attribute ) {
  3006. let minX = + Infinity;
  3007. let minY = + Infinity;
  3008. let minZ = + Infinity;
  3009. let maxX = - Infinity;
  3010. let maxY = - Infinity;
  3011. let maxZ = - Infinity;
  3012. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3013. const x = attribute.getX( i );
  3014. const y = attribute.getY( i );
  3015. const z = attribute.getZ( i );
  3016. if ( x < minX ) minX = x;
  3017. if ( y < minY ) minY = y;
  3018. if ( z < minZ ) minZ = z;
  3019. if ( x > maxX ) maxX = x;
  3020. if ( y > maxY ) maxY = y;
  3021. if ( z > maxZ ) maxZ = z;
  3022. }
  3023. this.min.set( minX, minY, minZ );
  3024. this.max.set( maxX, maxY, maxZ );
  3025. return this;
  3026. }
  3027. setFromPoints( points ) {
  3028. this.makeEmpty();
  3029. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3030. this.expandByPoint( points[ i ] );
  3031. }
  3032. return this;
  3033. }
  3034. setFromCenterAndSize( center, size ) {
  3035. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3036. this.min.copy( center ).sub( halfSize );
  3037. this.max.copy( center ).add( halfSize );
  3038. return this;
  3039. }
  3040. setFromObject( object, precise = false ) {
  3041. this.makeEmpty();
  3042. return this.expandByObject( object, precise );
  3043. }
  3044. clone() {
  3045. return new this.constructor().copy( this );
  3046. }
  3047. copy( box ) {
  3048. this.min.copy( box.min );
  3049. this.max.copy( box.max );
  3050. return this;
  3051. }
  3052. makeEmpty() {
  3053. this.min.x = this.min.y = this.min.z = + Infinity;
  3054. this.max.x = this.max.y = this.max.z = - Infinity;
  3055. return this;
  3056. }
  3057. isEmpty() {
  3058. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3059. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3060. }
  3061. getCenter( target ) {
  3062. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3063. }
  3064. getSize( target ) {
  3065. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3066. }
  3067. expandByPoint( point ) {
  3068. this.min.min( point );
  3069. this.max.max( point );
  3070. return this;
  3071. }
  3072. expandByVector( vector ) {
  3073. this.min.sub( vector );
  3074. this.max.add( vector );
  3075. return this;
  3076. }
  3077. expandByScalar( scalar ) {
  3078. this.min.addScalar( - scalar );
  3079. this.max.addScalar( scalar );
  3080. return this;
  3081. }
  3082. expandByObject( object, precise = false ) {
  3083. // Computes the world-axis-aligned bounding box of an object (including its children),
  3084. // accounting for both the object's, and children's, world transforms
  3085. object.updateWorldMatrix( false, false );
  3086. const geometry = object.geometry;
  3087. if ( geometry !== undefined ) {
  3088. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3089. const position = geometry.attributes.position;
  3090. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3091. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3092. this.expandByPoint( _vector$b );
  3093. }
  3094. } else {
  3095. if ( geometry.boundingBox === null ) {
  3096. geometry.computeBoundingBox();
  3097. }
  3098. _box$3.copy( geometry.boundingBox );
  3099. _box$3.applyMatrix4( object.matrixWorld );
  3100. this.union( _box$3 );
  3101. }
  3102. }
  3103. const children = object.children;
  3104. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3105. this.expandByObject( children[ i ], precise );
  3106. }
  3107. return this;
  3108. }
  3109. containsPoint( point ) {
  3110. return point.x < this.min.x || point.x > this.max.x ||
  3111. point.y < this.min.y || point.y > this.max.y ||
  3112. point.z < this.min.z || point.z > this.max.z ? false : true;
  3113. }
  3114. containsBox( box ) {
  3115. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3116. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3117. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3118. }
  3119. getParameter( point, target ) {
  3120. // This can potentially have a divide by zero if the box
  3121. // has a size dimension of 0.
  3122. return target.set(
  3123. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3124. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3125. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3126. );
  3127. }
  3128. intersectsBox( box ) {
  3129. // using 6 splitting planes to rule out intersections.
  3130. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3131. box.max.y < this.min.y || box.min.y > this.max.y ||
  3132. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3133. }
  3134. intersectsSphere( sphere ) {
  3135. // Find the point on the AABB closest to the sphere center.
  3136. this.clampPoint( sphere.center, _vector$b );
  3137. // If that point is inside the sphere, the AABB and sphere intersect.
  3138. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3139. }
  3140. intersectsPlane( plane ) {
  3141. // We compute the minimum and maximum dot product values. If those values
  3142. // are on the same side (back or front) of the plane, then there is no intersection.
  3143. let min, max;
  3144. if ( plane.normal.x > 0 ) {
  3145. min = plane.normal.x * this.min.x;
  3146. max = plane.normal.x * this.max.x;
  3147. } else {
  3148. min = plane.normal.x * this.max.x;
  3149. max = plane.normal.x * this.min.x;
  3150. }
  3151. if ( plane.normal.y > 0 ) {
  3152. min += plane.normal.y * this.min.y;
  3153. max += plane.normal.y * this.max.y;
  3154. } else {
  3155. min += plane.normal.y * this.max.y;
  3156. max += plane.normal.y * this.min.y;
  3157. }
  3158. if ( plane.normal.z > 0 ) {
  3159. min += plane.normal.z * this.min.z;
  3160. max += plane.normal.z * this.max.z;
  3161. } else {
  3162. min += plane.normal.z * this.max.z;
  3163. max += plane.normal.z * this.min.z;
  3164. }
  3165. return ( min <= - plane.constant && max >= - plane.constant );
  3166. }
  3167. intersectsTriangle( triangle ) {
  3168. if ( this.isEmpty() ) {
  3169. return false;
  3170. }
  3171. // compute box center and extents
  3172. this.getCenter( _center );
  3173. _extents.subVectors( this.max, _center );
  3174. // translate triangle to aabb origin
  3175. _v0$2.subVectors( triangle.a, _center );
  3176. _v1$7.subVectors( triangle.b, _center );
  3177. _v2$3.subVectors( triangle.c, _center );
  3178. // compute edge vectors for triangle
  3179. _f0.subVectors( _v1$7, _v0$2 );
  3180. _f1.subVectors( _v2$3, _v1$7 );
  3181. _f2.subVectors( _v0$2, _v2$3 );
  3182. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3183. // 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
  3184. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3185. let axes = [
  3186. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3187. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3188. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3189. ];
  3190. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3191. return false;
  3192. }
  3193. // test 3 face normals from the aabb
  3194. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3195. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3196. return false;
  3197. }
  3198. // finally testing the face normal of the triangle
  3199. // use already existing triangle edge vectors here
  3200. _triangleNormal.crossVectors( _f0, _f1 );
  3201. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3202. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  3203. }
  3204. clampPoint( point, target ) {
  3205. return target.copy( point ).clamp( this.min, this.max );
  3206. }
  3207. distanceToPoint( point ) {
  3208. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3209. return clampedPoint.sub( point ).length();
  3210. }
  3211. getBoundingSphere( target ) {
  3212. this.getCenter( target.center );
  3213. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3214. return target;
  3215. }
  3216. intersect( box ) {
  3217. this.min.max( box.min );
  3218. this.max.min( box.max );
  3219. // 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.
  3220. if ( this.isEmpty() ) this.makeEmpty();
  3221. return this;
  3222. }
  3223. union( box ) {
  3224. this.min.min( box.min );
  3225. this.max.max( box.max );
  3226. return this;
  3227. }
  3228. applyMatrix4( matrix ) {
  3229. // transform of empty box is an empty box.
  3230. if ( this.isEmpty() ) return this;
  3231. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3232. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3233. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3234. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3235. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3236. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3237. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3238. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3239. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3240. this.setFromPoints( _points );
  3241. return this;
  3242. }
  3243. translate( offset ) {
  3244. this.min.add( offset );
  3245. this.max.add( offset );
  3246. return this;
  3247. }
  3248. equals( box ) {
  3249. return box.min.equals( this.min ) && box.max.equals( this.max );
  3250. }
  3251. }
  3252. const _points = [
  3253. /*@__PURE__*/ new Vector3(),
  3254. /*@__PURE__*/ new Vector3(),
  3255. /*@__PURE__*/ new Vector3(),
  3256. /*@__PURE__*/ new Vector3(),
  3257. /*@__PURE__*/ new Vector3(),
  3258. /*@__PURE__*/ new Vector3(),
  3259. /*@__PURE__*/ new Vector3(),
  3260. /*@__PURE__*/ new Vector3()
  3261. ];
  3262. const _vector$b = /*@__PURE__*/ new Vector3();
  3263. const _box$3 = /*@__PURE__*/ new Box3();
  3264. // triangle centered vertices
  3265. const _v0$2 = /*@__PURE__*/ new Vector3();
  3266. const _v1$7 = /*@__PURE__*/ new Vector3();
  3267. const _v2$3 = /*@__PURE__*/ new Vector3();
  3268. // triangle edge vectors
  3269. const _f0 = /*@__PURE__*/ new Vector3();
  3270. const _f1 = /*@__PURE__*/ new Vector3();
  3271. const _f2 = /*@__PURE__*/ new Vector3();
  3272. const _center = /*@__PURE__*/ new Vector3();
  3273. const _extents = /*@__PURE__*/ new Vector3();
  3274. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3275. const _testAxis = /*@__PURE__*/ new Vector3();
  3276. function satForAxes( axes, v0, v1, v2, extents ) {
  3277. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3278. _testAxis.fromArray( axes, i );
  3279. // project the aabb onto the separating axis
  3280. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3281. // project all 3 vertices of the triangle onto the separating axis
  3282. const p0 = v0.dot( _testAxis );
  3283. const p1 = v1.dot( _testAxis );
  3284. const p2 = v2.dot( _testAxis );
  3285. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3286. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3287. // points of the projected triangle are outside the projected half-length of the aabb
  3288. // the axis is separating and we can exit
  3289. return false;
  3290. }
  3291. }
  3292. return true;
  3293. }
  3294. const _box$2 = /*@__PURE__*/ new Box3();
  3295. const _v1$6 = /*@__PURE__*/ new Vector3();
  3296. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  3297. const _toPoint = /*@__PURE__*/ new Vector3();
  3298. class Sphere {
  3299. constructor( center = new Vector3(), radius = - 1 ) {
  3300. this.center = center;
  3301. this.radius = radius;
  3302. }
  3303. set( center, radius ) {
  3304. this.center.copy( center );
  3305. this.radius = radius;
  3306. return this;
  3307. }
  3308. setFromPoints( points, optionalCenter ) {
  3309. const center = this.center;
  3310. if ( optionalCenter !== undefined ) {
  3311. center.copy( optionalCenter );
  3312. } else {
  3313. _box$2.setFromPoints( points ).getCenter( center );
  3314. }
  3315. let maxRadiusSq = 0;
  3316. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3317. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3318. }
  3319. this.radius = Math.sqrt( maxRadiusSq );
  3320. return this;
  3321. }
  3322. copy( sphere ) {
  3323. this.center.copy( sphere.center );
  3324. this.radius = sphere.radius;
  3325. return this;
  3326. }
  3327. isEmpty() {
  3328. return ( this.radius < 0 );
  3329. }
  3330. makeEmpty() {
  3331. this.center.set( 0, 0, 0 );
  3332. this.radius = - 1;
  3333. return this;
  3334. }
  3335. containsPoint( point ) {
  3336. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3337. }
  3338. distanceToPoint( point ) {
  3339. return ( point.distanceTo( this.center ) - this.radius );
  3340. }
  3341. intersectsSphere( sphere ) {
  3342. const radiusSum = this.radius + sphere.radius;
  3343. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3344. }
  3345. intersectsBox( box ) {
  3346. return box.intersectsSphere( this );
  3347. }
  3348. intersectsPlane( plane ) {
  3349. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3350. }
  3351. clampPoint( point, target ) {
  3352. const deltaLengthSq = this.center.distanceToSquared( point );
  3353. target.copy( point );
  3354. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3355. target.sub( this.center ).normalize();
  3356. target.multiplyScalar( this.radius ).add( this.center );
  3357. }
  3358. return target;
  3359. }
  3360. getBoundingBox( target ) {
  3361. if ( this.isEmpty() ) {
  3362. // Empty sphere produces empty bounding box
  3363. target.makeEmpty();
  3364. return target;
  3365. }
  3366. target.set( this.center, this.center );
  3367. target.expandByScalar( this.radius );
  3368. return target;
  3369. }
  3370. applyMatrix4( matrix ) {
  3371. this.center.applyMatrix4( matrix );
  3372. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3373. return this;
  3374. }
  3375. translate( offset ) {
  3376. this.center.add( offset );
  3377. return this;
  3378. }
  3379. expandByPoint( point ) {
  3380. if ( this.isEmpty() ) {
  3381. this.center.copy( point );
  3382. this.radius = 0;
  3383. return this;
  3384. }
  3385. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3386. _toPoint.subVectors( point, this.center );
  3387. const lengthSq = _toPoint.lengthSq();
  3388. if ( lengthSq > ( this.radius * this.radius ) ) {
  3389. const length = Math.sqrt( lengthSq );
  3390. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  3391. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3392. // and the other half to position. This gives a tighter enclosure, instead of if
  3393. // the whole missing distance were just added to radius.
  3394. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  3395. this.radius += missingRadiusHalf;
  3396. }
  3397. return this;
  3398. }
  3399. union( sphere ) {
  3400. // handle empty sphere cases
  3401. if ( sphere.isEmpty() ) {
  3402. return this;
  3403. } else if ( this.isEmpty() ) {
  3404. this.copy( sphere );
  3405. return this;
  3406. }
  3407. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3408. // To enclose another sphere into this sphere, we only need to enclose two points:
  3409. // 1) Enclose the farthest point on the other sphere into this sphere.
  3410. // 2) Enclose the opposite point of the farthest point into this sphere.
  3411. if ( this.center.equals( sphere.center ) === true ) {
  3412. _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius );
  3413. } else {
  3414. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  3415. }
  3416. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  3417. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  3418. return this;
  3419. }
  3420. equals( sphere ) {
  3421. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3422. }
  3423. clone() {
  3424. return new this.constructor().copy( this );
  3425. }
  3426. }
  3427. const _vector$a = /*@__PURE__*/ new Vector3();
  3428. const _segCenter = /*@__PURE__*/ new Vector3();
  3429. const _segDir = /*@__PURE__*/ new Vector3();
  3430. const _diff = /*@__PURE__*/ new Vector3();
  3431. const _edge1 = /*@__PURE__*/ new Vector3();
  3432. const _edge2 = /*@__PURE__*/ new Vector3();
  3433. const _normal$1 = /*@__PURE__*/ new Vector3();
  3434. class Ray {
  3435. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3436. this.origin = origin;
  3437. this.direction = direction;
  3438. }
  3439. set( origin, direction ) {
  3440. this.origin.copy( origin );
  3441. this.direction.copy( direction );
  3442. return this;
  3443. }
  3444. copy( ray ) {
  3445. this.origin.copy( ray.origin );
  3446. this.direction.copy( ray.direction );
  3447. return this;
  3448. }
  3449. at( t, target ) {
  3450. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3451. }
  3452. lookAt( v ) {
  3453. this.direction.copy( v ).sub( this.origin ).normalize();
  3454. return this;
  3455. }
  3456. recast( t ) {
  3457. this.origin.copy( this.at( t, _vector$a ) );
  3458. return this;
  3459. }
  3460. closestPointToPoint( point, target ) {
  3461. target.subVectors( point, this.origin );
  3462. const directionDistance = target.dot( this.direction );
  3463. if ( directionDistance < 0 ) {
  3464. return target.copy( this.origin );
  3465. }
  3466. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3467. }
  3468. distanceToPoint( point ) {
  3469. return Math.sqrt( this.distanceSqToPoint( point ) );
  3470. }
  3471. distanceSqToPoint( point ) {
  3472. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3473. // point behind the ray
  3474. if ( directionDistance < 0 ) {
  3475. return this.origin.distanceToSquared( point );
  3476. }
  3477. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3478. return _vector$a.distanceToSquared( point );
  3479. }
  3480. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3481. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3482. // It returns the min distance between the ray and the segment
  3483. // defined by v0 and v1
  3484. // It can also set two optional targets :
  3485. // - The closest point on the ray
  3486. // - The closest point on the segment
  3487. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3488. _segDir.copy( v1 ).sub( v0 ).normalize();
  3489. _diff.copy( this.origin ).sub( _segCenter );
  3490. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3491. const a01 = - this.direction.dot( _segDir );
  3492. const b0 = _diff.dot( this.direction );
  3493. const b1 = - _diff.dot( _segDir );
  3494. const c = _diff.lengthSq();
  3495. const det = Math.abs( 1 - a01 * a01 );
  3496. let s0, s1, sqrDist, extDet;
  3497. if ( det > 0 ) {
  3498. // The ray and segment are not parallel.
  3499. s0 = a01 * b1 - b0;
  3500. s1 = a01 * b0 - b1;
  3501. extDet = segExtent * det;
  3502. if ( s0 >= 0 ) {
  3503. if ( s1 >= - extDet ) {
  3504. if ( s1 <= extDet ) {
  3505. // region 0
  3506. // Minimum at interior points of ray and segment.
  3507. const invDet = 1 / det;
  3508. s0 *= invDet;
  3509. s1 *= invDet;
  3510. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3511. } else {
  3512. // region 1
  3513. s1 = segExtent;
  3514. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3515. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3516. }
  3517. } else {
  3518. // region 5
  3519. s1 = - segExtent;
  3520. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3521. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3522. }
  3523. } else {
  3524. if ( s1 <= - extDet ) {
  3525. // region 4
  3526. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3527. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3528. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3529. } else if ( s1 <= extDet ) {
  3530. // region 3
  3531. s0 = 0;
  3532. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3533. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3534. } else {
  3535. // region 2
  3536. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3537. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3538. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3539. }
  3540. }
  3541. } else {
  3542. // Ray and segment are parallel.
  3543. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3544. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3545. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3546. }
  3547. if ( optionalPointOnRay ) {
  3548. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3549. }
  3550. if ( optionalPointOnSegment ) {
  3551. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3552. }
  3553. return sqrDist;
  3554. }
  3555. intersectSphere( sphere, target ) {
  3556. _vector$a.subVectors( sphere.center, this.origin );
  3557. const tca = _vector$a.dot( this.direction );
  3558. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3559. const radius2 = sphere.radius * sphere.radius;
  3560. if ( d2 > radius2 ) return null;
  3561. const thc = Math.sqrt( radius2 - d2 );
  3562. // t0 = first intersect point - entrance on front of sphere
  3563. const t0 = tca - thc;
  3564. // t1 = second intersect point - exit point on back of sphere
  3565. const t1 = tca + thc;
  3566. // test to see if both t0 and t1 are behind the ray - if so, return null
  3567. if ( t0 < 0 && t1 < 0 ) return null;
  3568. // test to see if t0 is behind the ray:
  3569. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3570. // in order to always return an intersect point that is in front of the ray.
  3571. if ( t0 < 0 ) return this.at( t1, target );
  3572. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3573. return this.at( t0, target );
  3574. }
  3575. intersectsSphere( sphere ) {
  3576. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3577. }
  3578. distanceToPlane( plane ) {
  3579. const denominator = plane.normal.dot( this.direction );
  3580. if ( denominator === 0 ) {
  3581. // line is coplanar, return origin
  3582. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3583. return 0;
  3584. }
  3585. // Null is preferable to undefined since undefined means.... it is undefined
  3586. return null;
  3587. }
  3588. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3589. // Return if the ray never intersects the plane
  3590. return t >= 0 ? t : null;
  3591. }
  3592. intersectPlane( plane, target ) {
  3593. const t = this.distanceToPlane( plane );
  3594. if ( t === null ) {
  3595. return null;
  3596. }
  3597. return this.at( t, target );
  3598. }
  3599. intersectsPlane( plane ) {
  3600. // check if the ray lies on the plane first
  3601. const distToPoint = plane.distanceToPoint( this.origin );
  3602. if ( distToPoint === 0 ) {
  3603. return true;
  3604. }
  3605. const denominator = plane.normal.dot( this.direction );
  3606. if ( denominator * distToPoint < 0 ) {
  3607. return true;
  3608. }
  3609. // ray origin is behind the plane (and is pointing behind it)
  3610. return false;
  3611. }
  3612. intersectBox( box, target ) {
  3613. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3614. const invdirx = 1 / this.direction.x,
  3615. invdiry = 1 / this.direction.y,
  3616. invdirz = 1 / this.direction.z;
  3617. const origin = this.origin;
  3618. if ( invdirx >= 0 ) {
  3619. tmin = ( box.min.x - origin.x ) * invdirx;
  3620. tmax = ( box.max.x - origin.x ) * invdirx;
  3621. } else {
  3622. tmin = ( box.max.x - origin.x ) * invdirx;
  3623. tmax = ( box.min.x - origin.x ) * invdirx;
  3624. }
  3625. if ( invdiry >= 0 ) {
  3626. tymin = ( box.min.y - origin.y ) * invdiry;
  3627. tymax = ( box.max.y - origin.y ) * invdiry;
  3628. } else {
  3629. tymin = ( box.max.y - origin.y ) * invdiry;
  3630. tymax = ( box.min.y - origin.y ) * invdiry;
  3631. }
  3632. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3633. // These lines also handle the case where tmin or tmax is NaN
  3634. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3635. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3636. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3637. if ( invdirz >= 0 ) {
  3638. tzmin = ( box.min.z - origin.z ) * invdirz;
  3639. tzmax = ( box.max.z - origin.z ) * invdirz;
  3640. } else {
  3641. tzmin = ( box.max.z - origin.z ) * invdirz;
  3642. tzmax = ( box.min.z - origin.z ) * invdirz;
  3643. }
  3644. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3645. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3646. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3647. //return point closest to the ray (positive side)
  3648. if ( tmax < 0 ) return null;
  3649. return this.at( tmin >= 0 ? tmin : tmax, target );
  3650. }
  3651. intersectsBox( box ) {
  3652. return this.intersectBox( box, _vector$a ) !== null;
  3653. }
  3654. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3655. // Compute the offset origin, edges, and normal.
  3656. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3657. _edge1.subVectors( b, a );
  3658. _edge2.subVectors( c, a );
  3659. _normal$1.crossVectors( _edge1, _edge2 );
  3660. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3661. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3662. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3663. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3664. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3665. let DdN = this.direction.dot( _normal$1 );
  3666. let sign;
  3667. if ( DdN > 0 ) {
  3668. if ( backfaceCulling ) return null;
  3669. sign = 1;
  3670. } else if ( DdN < 0 ) {
  3671. sign = - 1;
  3672. DdN = - DdN;
  3673. } else {
  3674. return null;
  3675. }
  3676. _diff.subVectors( this.origin, a );
  3677. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3678. // b1 < 0, no intersection
  3679. if ( DdQxE2 < 0 ) {
  3680. return null;
  3681. }
  3682. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3683. // b2 < 0, no intersection
  3684. if ( DdE1xQ < 0 ) {
  3685. return null;
  3686. }
  3687. // b1+b2 > 1, no intersection
  3688. if ( DdQxE2 + DdE1xQ > DdN ) {
  3689. return null;
  3690. }
  3691. // Line intersects triangle, check if ray does.
  3692. const QdN = - sign * _diff.dot( _normal$1 );
  3693. // t < 0, no intersection
  3694. if ( QdN < 0 ) {
  3695. return null;
  3696. }
  3697. // Ray intersects triangle.
  3698. return this.at( QdN / DdN, target );
  3699. }
  3700. applyMatrix4( matrix4 ) {
  3701. this.origin.applyMatrix4( matrix4 );
  3702. this.direction.transformDirection( matrix4 );
  3703. return this;
  3704. }
  3705. equals( ray ) {
  3706. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3707. }
  3708. clone() {
  3709. return new this.constructor().copy( this );
  3710. }
  3711. }
  3712. class Matrix4 {
  3713. constructor() {
  3714. Matrix4.prototype.isMatrix4 = true;
  3715. this.elements = [
  3716. 1, 0, 0, 0,
  3717. 0, 1, 0, 0,
  3718. 0, 0, 1, 0,
  3719. 0, 0, 0, 1
  3720. ];
  3721. }
  3722. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3723. const te = this.elements;
  3724. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3725. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3726. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3727. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3728. return this;
  3729. }
  3730. identity() {
  3731. this.set(
  3732. 1, 0, 0, 0,
  3733. 0, 1, 0, 0,
  3734. 0, 0, 1, 0,
  3735. 0, 0, 0, 1
  3736. );
  3737. return this;
  3738. }
  3739. clone() {
  3740. return new Matrix4().fromArray( this.elements );
  3741. }
  3742. copy( m ) {
  3743. const te = this.elements;
  3744. const me = m.elements;
  3745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3746. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3747. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3748. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3749. return this;
  3750. }
  3751. copyPosition( m ) {
  3752. const te = this.elements, me = m.elements;
  3753. te[ 12 ] = me[ 12 ];
  3754. te[ 13 ] = me[ 13 ];
  3755. te[ 14 ] = me[ 14 ];
  3756. return this;
  3757. }
  3758. setFromMatrix3( m ) {
  3759. const me = m.elements;
  3760. this.set(
  3761. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3762. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3763. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3764. 0, 0, 0, 1
  3765. );
  3766. return this;
  3767. }
  3768. extractBasis( xAxis, yAxis, zAxis ) {
  3769. xAxis.setFromMatrixColumn( this, 0 );
  3770. yAxis.setFromMatrixColumn( this, 1 );
  3771. zAxis.setFromMatrixColumn( this, 2 );
  3772. return this;
  3773. }
  3774. makeBasis( xAxis, yAxis, zAxis ) {
  3775. this.set(
  3776. xAxis.x, yAxis.x, zAxis.x, 0,
  3777. xAxis.y, yAxis.y, zAxis.y, 0,
  3778. xAxis.z, yAxis.z, zAxis.z, 0,
  3779. 0, 0, 0, 1
  3780. );
  3781. return this;
  3782. }
  3783. extractRotation( m ) {
  3784. // this method does not support reflection matrices
  3785. const te = this.elements;
  3786. const me = m.elements;
  3787. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3788. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3789. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3790. te[ 0 ] = me[ 0 ] * scaleX;
  3791. te[ 1 ] = me[ 1 ] * scaleX;
  3792. te[ 2 ] = me[ 2 ] * scaleX;
  3793. te[ 3 ] = 0;
  3794. te[ 4 ] = me[ 4 ] * scaleY;
  3795. te[ 5 ] = me[ 5 ] * scaleY;
  3796. te[ 6 ] = me[ 6 ] * scaleY;
  3797. te[ 7 ] = 0;
  3798. te[ 8 ] = me[ 8 ] * scaleZ;
  3799. te[ 9 ] = me[ 9 ] * scaleZ;
  3800. te[ 10 ] = me[ 10 ] * scaleZ;
  3801. te[ 11 ] = 0;
  3802. te[ 12 ] = 0;
  3803. te[ 13 ] = 0;
  3804. te[ 14 ] = 0;
  3805. te[ 15 ] = 1;
  3806. return this;
  3807. }
  3808. makeRotationFromEuler( euler ) {
  3809. const te = this.elements;
  3810. const x = euler.x, y = euler.y, z = euler.z;
  3811. const a = Math.cos( x ), b = Math.sin( x );
  3812. const c = Math.cos( y ), d = Math.sin( y );
  3813. const e = Math.cos( z ), f = Math.sin( z );
  3814. if ( euler.order === 'XYZ' ) {
  3815. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3816. te[ 0 ] = c * e;
  3817. te[ 4 ] = - c * f;
  3818. te[ 8 ] = d;
  3819. te[ 1 ] = af + be * d;
  3820. te[ 5 ] = ae - bf * d;
  3821. te[ 9 ] = - b * c;
  3822. te[ 2 ] = bf - ae * d;
  3823. te[ 6 ] = be + af * d;
  3824. te[ 10 ] = a * c;
  3825. } else if ( euler.order === 'YXZ' ) {
  3826. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3827. te[ 0 ] = ce + df * b;
  3828. te[ 4 ] = de * b - cf;
  3829. te[ 8 ] = a * d;
  3830. te[ 1 ] = a * f;
  3831. te[ 5 ] = a * e;
  3832. te[ 9 ] = - b;
  3833. te[ 2 ] = cf * b - de;
  3834. te[ 6 ] = df + ce * b;
  3835. te[ 10 ] = a * c;
  3836. } else if ( euler.order === 'ZXY' ) {
  3837. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3838. te[ 0 ] = ce - df * b;
  3839. te[ 4 ] = - a * f;
  3840. te[ 8 ] = de + cf * b;
  3841. te[ 1 ] = cf + de * b;
  3842. te[ 5 ] = a * e;
  3843. te[ 9 ] = df - ce * b;
  3844. te[ 2 ] = - a * d;
  3845. te[ 6 ] = b;
  3846. te[ 10 ] = a * c;
  3847. } else if ( euler.order === 'ZYX' ) {
  3848. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3849. te[ 0 ] = c * e;
  3850. te[ 4 ] = be * d - af;
  3851. te[ 8 ] = ae * d + bf;
  3852. te[ 1 ] = c * f;
  3853. te[ 5 ] = bf * d + ae;
  3854. te[ 9 ] = af * d - be;
  3855. te[ 2 ] = - d;
  3856. te[ 6 ] = b * c;
  3857. te[ 10 ] = a * c;
  3858. } else if ( euler.order === 'YZX' ) {
  3859. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3860. te[ 0 ] = c * e;
  3861. te[ 4 ] = bd - ac * f;
  3862. te[ 8 ] = bc * f + ad;
  3863. te[ 1 ] = f;
  3864. te[ 5 ] = a * e;
  3865. te[ 9 ] = - b * e;
  3866. te[ 2 ] = - d * e;
  3867. te[ 6 ] = ad * f + bc;
  3868. te[ 10 ] = ac - bd * f;
  3869. } else if ( euler.order === 'XZY' ) {
  3870. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3871. te[ 0 ] = c * e;
  3872. te[ 4 ] = - f;
  3873. te[ 8 ] = d * e;
  3874. te[ 1 ] = ac * f + bd;
  3875. te[ 5 ] = a * e;
  3876. te[ 9 ] = ad * f - bc;
  3877. te[ 2 ] = bc * f - ad;
  3878. te[ 6 ] = b * e;
  3879. te[ 10 ] = bd * f + ac;
  3880. }
  3881. // bottom row
  3882. te[ 3 ] = 0;
  3883. te[ 7 ] = 0;
  3884. te[ 11 ] = 0;
  3885. // last column
  3886. te[ 12 ] = 0;
  3887. te[ 13 ] = 0;
  3888. te[ 14 ] = 0;
  3889. te[ 15 ] = 1;
  3890. return this;
  3891. }
  3892. makeRotationFromQuaternion( q ) {
  3893. return this.compose( _zero, q, _one );
  3894. }
  3895. lookAt( eye, target, up ) {
  3896. const te = this.elements;
  3897. _z.subVectors( eye, target );
  3898. if ( _z.lengthSq() === 0 ) {
  3899. // eye and target are in the same position
  3900. _z.z = 1;
  3901. }
  3902. _z.normalize();
  3903. _x.crossVectors( up, _z );
  3904. if ( _x.lengthSq() === 0 ) {
  3905. // up and z are parallel
  3906. if ( Math.abs( up.z ) === 1 ) {
  3907. _z.x += 0.0001;
  3908. } else {
  3909. _z.z += 0.0001;
  3910. }
  3911. _z.normalize();
  3912. _x.crossVectors( up, _z );
  3913. }
  3914. _x.normalize();
  3915. _y.crossVectors( _z, _x );
  3916. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3917. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3918. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3919. return this;
  3920. }
  3921. multiply( m ) {
  3922. return this.multiplyMatrices( this, m );
  3923. }
  3924. premultiply( m ) {
  3925. return this.multiplyMatrices( m, this );
  3926. }
  3927. multiplyMatrices( a, b ) {
  3928. const ae = a.elements;
  3929. const be = b.elements;
  3930. const te = this.elements;
  3931. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3932. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3933. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3934. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3935. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3936. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3937. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3938. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3939. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3940. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3941. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3942. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3943. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3944. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3945. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3946. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3947. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3948. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3949. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3950. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3951. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3952. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3953. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3954. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3955. return this;
  3956. }
  3957. multiplyScalar( s ) {
  3958. const te = this.elements;
  3959. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3960. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3961. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3962. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3963. return this;
  3964. }
  3965. determinant() {
  3966. const te = this.elements;
  3967. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3968. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3969. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3970. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3971. //TODO: make this more efficient
  3972. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3973. return (
  3974. n41 * (
  3975. + n14 * n23 * n32
  3976. - n13 * n24 * n32
  3977. - n14 * n22 * n33
  3978. + n12 * n24 * n33
  3979. + n13 * n22 * n34
  3980. - n12 * n23 * n34
  3981. ) +
  3982. n42 * (
  3983. + n11 * n23 * n34
  3984. - n11 * n24 * n33
  3985. + n14 * n21 * n33
  3986. - n13 * n21 * n34
  3987. + n13 * n24 * n31
  3988. - n14 * n23 * n31
  3989. ) +
  3990. n43 * (
  3991. + n11 * n24 * n32
  3992. - n11 * n22 * n34
  3993. - n14 * n21 * n32
  3994. + n12 * n21 * n34
  3995. + n14 * n22 * n31
  3996. - n12 * n24 * n31
  3997. ) +
  3998. n44 * (
  3999. - n13 * n22 * n31
  4000. - n11 * n23 * n32
  4001. + n11 * n22 * n33
  4002. + n13 * n21 * n32
  4003. - n12 * n21 * n33
  4004. + n12 * n23 * n31
  4005. )
  4006. );
  4007. }
  4008. transpose() {
  4009. const te = this.elements;
  4010. let tmp;
  4011. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4012. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4013. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4014. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4015. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4016. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4017. return this;
  4018. }
  4019. setPosition( x, y, z ) {
  4020. const te = this.elements;
  4021. if ( x.isVector3 ) {
  4022. te[ 12 ] = x.x;
  4023. te[ 13 ] = x.y;
  4024. te[ 14 ] = x.z;
  4025. } else {
  4026. te[ 12 ] = x;
  4027. te[ 13 ] = y;
  4028. te[ 14 ] = z;
  4029. }
  4030. return this;
  4031. }
  4032. invert() {
  4033. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4034. const te = this.elements,
  4035. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4036. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4037. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4038. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4039. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4040. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4041. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4042. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4043. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4044. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4045. const detInv = 1 / det;
  4046. te[ 0 ] = t11 * detInv;
  4047. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4048. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4049. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4050. te[ 4 ] = t12 * detInv;
  4051. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4052. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4053. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4054. te[ 8 ] = t13 * detInv;
  4055. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4056. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4057. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4058. te[ 12 ] = t14 * detInv;
  4059. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4060. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4061. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4062. return this;
  4063. }
  4064. scale( v ) {
  4065. const te = this.elements;
  4066. const x = v.x, y = v.y, z = v.z;
  4067. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4068. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4069. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4070. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4071. return this;
  4072. }
  4073. getMaxScaleOnAxis() {
  4074. const te = this.elements;
  4075. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4076. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4077. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4078. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4079. }
  4080. makeTranslation( x, y, z ) {
  4081. this.set(
  4082. 1, 0, 0, x,
  4083. 0, 1, 0, y,
  4084. 0, 0, 1, z,
  4085. 0, 0, 0, 1
  4086. );
  4087. return this;
  4088. }
  4089. makeRotationX( theta ) {
  4090. const c = Math.cos( theta ), s = Math.sin( theta );
  4091. this.set(
  4092. 1, 0, 0, 0,
  4093. 0, c, - s, 0,
  4094. 0, s, c, 0,
  4095. 0, 0, 0, 1
  4096. );
  4097. return this;
  4098. }
  4099. makeRotationY( theta ) {
  4100. const c = Math.cos( theta ), s = Math.sin( theta );
  4101. this.set(
  4102. c, 0, s, 0,
  4103. 0, 1, 0, 0,
  4104. - s, 0, c, 0,
  4105. 0, 0, 0, 1
  4106. );
  4107. return this;
  4108. }
  4109. makeRotationZ( theta ) {
  4110. const c = Math.cos( theta ), s = Math.sin( theta );
  4111. this.set(
  4112. c, - s, 0, 0,
  4113. s, c, 0, 0,
  4114. 0, 0, 1, 0,
  4115. 0, 0, 0, 1
  4116. );
  4117. return this;
  4118. }
  4119. makeRotationAxis( axis, angle ) {
  4120. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4121. const c = Math.cos( angle );
  4122. const s = Math.sin( angle );
  4123. const t = 1 - c;
  4124. const x = axis.x, y = axis.y, z = axis.z;
  4125. const tx = t * x, ty = t * y;
  4126. this.set(
  4127. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4128. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4129. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4130. 0, 0, 0, 1
  4131. );
  4132. return this;
  4133. }
  4134. makeScale( x, y, z ) {
  4135. this.set(
  4136. x, 0, 0, 0,
  4137. 0, y, 0, 0,
  4138. 0, 0, z, 0,
  4139. 0, 0, 0, 1
  4140. );
  4141. return this;
  4142. }
  4143. makeShear( xy, xz, yx, yz, zx, zy ) {
  4144. this.set(
  4145. 1, yx, zx, 0,
  4146. xy, 1, zy, 0,
  4147. xz, yz, 1, 0,
  4148. 0, 0, 0, 1
  4149. );
  4150. return this;
  4151. }
  4152. compose( position, quaternion, scale ) {
  4153. const te = this.elements;
  4154. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4155. const x2 = x + x, y2 = y + y, z2 = z + z;
  4156. const xx = x * x2, xy = x * y2, xz = x * z2;
  4157. const yy = y * y2, yz = y * z2, zz = z * z2;
  4158. const wx = w * x2, wy = w * y2, wz = w * z2;
  4159. const sx = scale.x, sy = scale.y, sz = scale.z;
  4160. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4161. te[ 1 ] = ( xy + wz ) * sx;
  4162. te[ 2 ] = ( xz - wy ) * sx;
  4163. te[ 3 ] = 0;
  4164. te[ 4 ] = ( xy - wz ) * sy;
  4165. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4166. te[ 6 ] = ( yz + wx ) * sy;
  4167. te[ 7 ] = 0;
  4168. te[ 8 ] = ( xz + wy ) * sz;
  4169. te[ 9 ] = ( yz - wx ) * sz;
  4170. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4171. te[ 11 ] = 0;
  4172. te[ 12 ] = position.x;
  4173. te[ 13 ] = position.y;
  4174. te[ 14 ] = position.z;
  4175. te[ 15 ] = 1;
  4176. return this;
  4177. }
  4178. decompose( position, quaternion, scale ) {
  4179. const te = this.elements;
  4180. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4181. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4182. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4183. // if determine is negative, we need to invert one scale
  4184. const det = this.determinant();
  4185. if ( det < 0 ) sx = - sx;
  4186. position.x = te[ 12 ];
  4187. position.y = te[ 13 ];
  4188. position.z = te[ 14 ];
  4189. // scale the rotation part
  4190. _m1$2.copy( this );
  4191. const invSX = 1 / sx;
  4192. const invSY = 1 / sy;
  4193. const invSZ = 1 / sz;
  4194. _m1$2.elements[ 0 ] *= invSX;
  4195. _m1$2.elements[ 1 ] *= invSX;
  4196. _m1$2.elements[ 2 ] *= invSX;
  4197. _m1$2.elements[ 4 ] *= invSY;
  4198. _m1$2.elements[ 5 ] *= invSY;
  4199. _m1$2.elements[ 6 ] *= invSY;
  4200. _m1$2.elements[ 8 ] *= invSZ;
  4201. _m1$2.elements[ 9 ] *= invSZ;
  4202. _m1$2.elements[ 10 ] *= invSZ;
  4203. quaternion.setFromRotationMatrix( _m1$2 );
  4204. scale.x = sx;
  4205. scale.y = sy;
  4206. scale.z = sz;
  4207. return this;
  4208. }
  4209. makePerspective( left, right, top, bottom, near, far ) {
  4210. const te = this.elements;
  4211. const x = 2 * near / ( right - left );
  4212. const y = 2 * near / ( top - bottom );
  4213. const a = ( right + left ) / ( right - left );
  4214. const b = ( top + bottom ) / ( top - bottom );
  4215. const c = - ( far + near ) / ( far - near );
  4216. const d = - 2 * far * near / ( far - near );
  4217. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4218. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4219. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4220. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4221. return this;
  4222. }
  4223. makeOrthographic( left, right, top, bottom, near, far ) {
  4224. const te = this.elements;
  4225. const w = 1.0 / ( right - left );
  4226. const h = 1.0 / ( top - bottom );
  4227. const p = 1.0 / ( far - near );
  4228. const x = ( right + left ) * w;
  4229. const y = ( top + bottom ) * h;
  4230. const z = ( far + near ) * p;
  4231. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4232. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4233. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4234. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4235. return this;
  4236. }
  4237. equals( matrix ) {
  4238. const te = this.elements;
  4239. const me = matrix.elements;
  4240. for ( let i = 0; i < 16; i ++ ) {
  4241. if ( te[ i ] !== me[ i ] ) return false;
  4242. }
  4243. return true;
  4244. }
  4245. fromArray( array, offset = 0 ) {
  4246. for ( let i = 0; i < 16; i ++ ) {
  4247. this.elements[ i ] = array[ i + offset ];
  4248. }
  4249. return this;
  4250. }
  4251. toArray( array = [], offset = 0 ) {
  4252. const te = this.elements;
  4253. array[ offset ] = te[ 0 ];
  4254. array[ offset + 1 ] = te[ 1 ];
  4255. array[ offset + 2 ] = te[ 2 ];
  4256. array[ offset + 3 ] = te[ 3 ];
  4257. array[ offset + 4 ] = te[ 4 ];
  4258. array[ offset + 5 ] = te[ 5 ];
  4259. array[ offset + 6 ] = te[ 6 ];
  4260. array[ offset + 7 ] = te[ 7 ];
  4261. array[ offset + 8 ] = te[ 8 ];
  4262. array[ offset + 9 ] = te[ 9 ];
  4263. array[ offset + 10 ] = te[ 10 ];
  4264. array[ offset + 11 ] = te[ 11 ];
  4265. array[ offset + 12 ] = te[ 12 ];
  4266. array[ offset + 13 ] = te[ 13 ];
  4267. array[ offset + 14 ] = te[ 14 ];
  4268. array[ offset + 15 ] = te[ 15 ];
  4269. return array;
  4270. }
  4271. }
  4272. const _v1$5 = /*@__PURE__*/ new Vector3();
  4273. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4274. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4275. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4276. const _x = /*@__PURE__*/ new Vector3();
  4277. const _y = /*@__PURE__*/ new Vector3();
  4278. const _z = /*@__PURE__*/ new Vector3();
  4279. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4280. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4281. class Euler {
  4282. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4283. this.isEuler = true;
  4284. this._x = x;
  4285. this._y = y;
  4286. this._z = z;
  4287. this._order = order;
  4288. }
  4289. get x() {
  4290. return this._x;
  4291. }
  4292. set x( value ) {
  4293. this._x = value;
  4294. this._onChangeCallback();
  4295. }
  4296. get y() {
  4297. return this._y;
  4298. }
  4299. set y( value ) {
  4300. this._y = value;
  4301. this._onChangeCallback();
  4302. }
  4303. get z() {
  4304. return this._z;
  4305. }
  4306. set z( value ) {
  4307. this._z = value;
  4308. this._onChangeCallback();
  4309. }
  4310. get order() {
  4311. return this._order;
  4312. }
  4313. set order( value ) {
  4314. this._order = value;
  4315. this._onChangeCallback();
  4316. }
  4317. set( x, y, z, order = this._order ) {
  4318. this._x = x;
  4319. this._y = y;
  4320. this._z = z;
  4321. this._order = order;
  4322. this._onChangeCallback();
  4323. return this;
  4324. }
  4325. clone() {
  4326. return new this.constructor( this._x, this._y, this._z, this._order );
  4327. }
  4328. copy( euler ) {
  4329. this._x = euler._x;
  4330. this._y = euler._y;
  4331. this._z = euler._z;
  4332. this._order = euler._order;
  4333. this._onChangeCallback();
  4334. return this;
  4335. }
  4336. setFromRotationMatrix( m, order = this._order, update = true ) {
  4337. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4338. const te = m.elements;
  4339. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4340. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4341. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4342. switch ( order ) {
  4343. case 'XYZ':
  4344. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4345. if ( Math.abs( m13 ) < 0.9999999 ) {
  4346. this._x = Math.atan2( - m23, m33 );
  4347. this._z = Math.atan2( - m12, m11 );
  4348. } else {
  4349. this._x = Math.atan2( m32, m22 );
  4350. this._z = 0;
  4351. }
  4352. break;
  4353. case 'YXZ':
  4354. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4355. if ( Math.abs( m23 ) < 0.9999999 ) {
  4356. this._y = Math.atan2( m13, m33 );
  4357. this._z = Math.atan2( m21, m22 );
  4358. } else {
  4359. this._y = Math.atan2( - m31, m11 );
  4360. this._z = 0;
  4361. }
  4362. break;
  4363. case 'ZXY':
  4364. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4365. if ( Math.abs( m32 ) < 0.9999999 ) {
  4366. this._y = Math.atan2( - m31, m33 );
  4367. this._z = Math.atan2( - m12, m22 );
  4368. } else {
  4369. this._y = 0;
  4370. this._z = Math.atan2( m21, m11 );
  4371. }
  4372. break;
  4373. case 'ZYX':
  4374. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4375. if ( Math.abs( m31 ) < 0.9999999 ) {
  4376. this._x = Math.atan2( m32, m33 );
  4377. this._z = Math.atan2( m21, m11 );
  4378. } else {
  4379. this._x = 0;
  4380. this._z = Math.atan2( - m12, m22 );
  4381. }
  4382. break;
  4383. case 'YZX':
  4384. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4385. if ( Math.abs( m21 ) < 0.9999999 ) {
  4386. this._x = Math.atan2( - m23, m22 );
  4387. this._y = Math.atan2( - m31, m11 );
  4388. } else {
  4389. this._x = 0;
  4390. this._y = Math.atan2( m13, m33 );
  4391. }
  4392. break;
  4393. case 'XZY':
  4394. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4395. if ( Math.abs( m12 ) < 0.9999999 ) {
  4396. this._x = Math.atan2( m32, m22 );
  4397. this._y = Math.atan2( m13, m11 );
  4398. } else {
  4399. this._x = Math.atan2( - m23, m33 );
  4400. this._y = 0;
  4401. }
  4402. break;
  4403. default:
  4404. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4405. }
  4406. this._order = order;
  4407. if ( update === true ) this._onChangeCallback();
  4408. return this;
  4409. }
  4410. setFromQuaternion( q, order, update ) {
  4411. _matrix$1.makeRotationFromQuaternion( q );
  4412. return this.setFromRotationMatrix( _matrix$1, order, update );
  4413. }
  4414. setFromVector3( v, order = this._order ) {
  4415. return this.set( v.x, v.y, v.z, order );
  4416. }
  4417. reorder( newOrder ) {
  4418. // WARNING: this discards revolution information -bhouston
  4419. _quaternion$3.setFromEuler( this );
  4420. return this.setFromQuaternion( _quaternion$3, newOrder );
  4421. }
  4422. equals( euler ) {
  4423. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4424. }
  4425. fromArray( array ) {
  4426. this._x = array[ 0 ];
  4427. this._y = array[ 1 ];
  4428. this._z = array[ 2 ];
  4429. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4430. this._onChangeCallback();
  4431. return this;
  4432. }
  4433. toArray( array = [], offset = 0 ) {
  4434. array[ offset ] = this._x;
  4435. array[ offset + 1 ] = this._y;
  4436. array[ offset + 2 ] = this._z;
  4437. array[ offset + 3 ] = this._order;
  4438. return array;
  4439. }
  4440. _onChange( callback ) {
  4441. this._onChangeCallback = callback;
  4442. return this;
  4443. }
  4444. _onChangeCallback() {}
  4445. *[ Symbol.iterator ]() {
  4446. yield this._x;
  4447. yield this._y;
  4448. yield this._z;
  4449. yield this._order;
  4450. }
  4451. // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4452. toVector3() {
  4453. console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' );
  4454. }
  4455. }
  4456. Euler.DefaultOrder = 'XYZ';
  4457. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4458. class Layers {
  4459. constructor() {
  4460. this.mask = 1 | 0;
  4461. }
  4462. set( channel ) {
  4463. this.mask = ( 1 << channel | 0 ) >>> 0;
  4464. }
  4465. enable( channel ) {
  4466. this.mask |= 1 << channel | 0;
  4467. }
  4468. enableAll() {
  4469. this.mask = 0xffffffff | 0;
  4470. }
  4471. toggle( channel ) {
  4472. this.mask ^= 1 << channel | 0;
  4473. }
  4474. disable( channel ) {
  4475. this.mask &= ~ ( 1 << channel | 0 );
  4476. }
  4477. disableAll() {
  4478. this.mask = 0;
  4479. }
  4480. test( layers ) {
  4481. return ( this.mask & layers.mask ) !== 0;
  4482. }
  4483. isEnabled( channel ) {
  4484. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4485. }
  4486. }
  4487. let _object3DId = 0;
  4488. const _v1$4 = /*@__PURE__*/ new Vector3();
  4489. const _q1 = /*@__PURE__*/ new Quaternion();
  4490. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4491. const _target = /*@__PURE__*/ new Vector3();
  4492. const _position$3 = /*@__PURE__*/ new Vector3();
  4493. const _scale$2 = /*@__PURE__*/ new Vector3();
  4494. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4495. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4496. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4497. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4498. const _addedEvent = { type: 'added' };
  4499. const _removedEvent = { type: 'removed' };
  4500. class Object3D extends EventDispatcher {
  4501. constructor() {
  4502. super();
  4503. this.isObject3D = true;
  4504. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4505. this.uuid = generateUUID();
  4506. this.name = '';
  4507. this.type = 'Object3D';
  4508. this.parent = null;
  4509. this.children = [];
  4510. this.up = Object3D.DefaultUp.clone();
  4511. const position = new Vector3();
  4512. const rotation = new Euler();
  4513. const quaternion = new Quaternion();
  4514. const scale = new Vector3( 1, 1, 1 );
  4515. function onRotationChange() {
  4516. quaternion.setFromEuler( rotation, false );
  4517. }
  4518. function onQuaternionChange() {
  4519. rotation.setFromQuaternion( quaternion, undefined, false );
  4520. }
  4521. rotation._onChange( onRotationChange );
  4522. quaternion._onChange( onQuaternionChange );
  4523. Object.defineProperties( this, {
  4524. position: {
  4525. configurable: true,
  4526. enumerable: true,
  4527. value: position
  4528. },
  4529. rotation: {
  4530. configurable: true,
  4531. enumerable: true,
  4532. value: rotation
  4533. },
  4534. quaternion: {
  4535. configurable: true,
  4536. enumerable: true,
  4537. value: quaternion
  4538. },
  4539. scale: {
  4540. configurable: true,
  4541. enumerable: true,
  4542. value: scale
  4543. },
  4544. modelViewMatrix: {
  4545. value: new Matrix4()
  4546. },
  4547. normalMatrix: {
  4548. value: new Matrix3()
  4549. }
  4550. } );
  4551. this.matrix = new Matrix4();
  4552. this.matrixWorld = new Matrix4();
  4553. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4554. this.matrixWorldNeedsUpdate = false;
  4555. this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer
  4556. this.layers = new Layers();
  4557. this.visible = true;
  4558. this.castShadow = false;
  4559. this.receiveShadow = false;
  4560. this.frustumCulled = true;
  4561. this.renderOrder = 0;
  4562. this.animations = [];
  4563. this.userData = {};
  4564. }
  4565. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4566. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4567. applyMatrix4( matrix ) {
  4568. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4569. this.matrix.premultiply( matrix );
  4570. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4571. }
  4572. applyQuaternion( q ) {
  4573. this.quaternion.premultiply( q );
  4574. return this;
  4575. }
  4576. setRotationFromAxisAngle( axis, angle ) {
  4577. // assumes axis is normalized
  4578. this.quaternion.setFromAxisAngle( axis, angle );
  4579. }
  4580. setRotationFromEuler( euler ) {
  4581. this.quaternion.setFromEuler( euler, true );
  4582. }
  4583. setRotationFromMatrix( m ) {
  4584. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4585. this.quaternion.setFromRotationMatrix( m );
  4586. }
  4587. setRotationFromQuaternion( q ) {
  4588. // assumes q is normalized
  4589. this.quaternion.copy( q );
  4590. }
  4591. rotateOnAxis( axis, angle ) {
  4592. // rotate object on axis in object space
  4593. // axis is assumed to be normalized
  4594. _q1.setFromAxisAngle( axis, angle );
  4595. this.quaternion.multiply( _q1 );
  4596. return this;
  4597. }
  4598. rotateOnWorldAxis( axis, angle ) {
  4599. // rotate object on axis in world space
  4600. // axis is assumed to be normalized
  4601. // method assumes no rotated parent
  4602. _q1.setFromAxisAngle( axis, angle );
  4603. this.quaternion.premultiply( _q1 );
  4604. return this;
  4605. }
  4606. rotateX( angle ) {
  4607. return this.rotateOnAxis( _xAxis, angle );
  4608. }
  4609. rotateY( angle ) {
  4610. return this.rotateOnAxis( _yAxis, angle );
  4611. }
  4612. rotateZ( angle ) {
  4613. return this.rotateOnAxis( _zAxis, angle );
  4614. }
  4615. translateOnAxis( axis, distance ) {
  4616. // translate object by distance along axis in object space
  4617. // axis is assumed to be normalized
  4618. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4619. this.position.add( _v1$4.multiplyScalar( distance ) );
  4620. return this;
  4621. }
  4622. translateX( distance ) {
  4623. return this.translateOnAxis( _xAxis, distance );
  4624. }
  4625. translateY( distance ) {
  4626. return this.translateOnAxis( _yAxis, distance );
  4627. }
  4628. translateZ( distance ) {
  4629. return this.translateOnAxis( _zAxis, distance );
  4630. }
  4631. localToWorld( vector ) {
  4632. return vector.applyMatrix4( this.matrixWorld );
  4633. }
  4634. worldToLocal( vector ) {
  4635. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4636. }
  4637. lookAt( x, y, z ) {
  4638. // This method does not support objects having non-uniformly-scaled parent(s)
  4639. if ( x.isVector3 ) {
  4640. _target.copy( x );
  4641. } else {
  4642. _target.set( x, y, z );
  4643. }
  4644. const parent = this.parent;
  4645. this.updateWorldMatrix( true, false );
  4646. _position$3.setFromMatrixPosition( this.matrixWorld );
  4647. if ( this.isCamera || this.isLight ) {
  4648. _m1$1.lookAt( _position$3, _target, this.up );
  4649. } else {
  4650. _m1$1.lookAt( _target, _position$3, this.up );
  4651. }
  4652. this.quaternion.setFromRotationMatrix( _m1$1 );
  4653. if ( parent ) {
  4654. _m1$1.extractRotation( parent.matrixWorld );
  4655. _q1.setFromRotationMatrix( _m1$1 );
  4656. this.quaternion.premultiply( _q1.invert() );
  4657. }
  4658. }
  4659. add( object ) {
  4660. if ( arguments.length > 1 ) {
  4661. for ( let i = 0; i < arguments.length; i ++ ) {
  4662. this.add( arguments[ i ] );
  4663. }
  4664. return this;
  4665. }
  4666. if ( object === this ) {
  4667. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4668. return this;
  4669. }
  4670. if ( object && object.isObject3D ) {
  4671. if ( object.parent !== null ) {
  4672. object.parent.remove( object );
  4673. }
  4674. object.parent = this;
  4675. this.children.push( object );
  4676. object.dispatchEvent( _addedEvent );
  4677. } else {
  4678. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4679. }
  4680. return this;
  4681. }
  4682. remove( object ) {
  4683. if ( arguments.length > 1 ) {
  4684. for ( let i = 0; i < arguments.length; i ++ ) {
  4685. this.remove( arguments[ i ] );
  4686. }
  4687. return this;
  4688. }
  4689. const index = this.children.indexOf( object );
  4690. if ( index !== - 1 ) {
  4691. object.parent = null;
  4692. this.children.splice( index, 1 );
  4693. object.dispatchEvent( _removedEvent );
  4694. }
  4695. return this;
  4696. }
  4697. removeFromParent() {
  4698. const parent = this.parent;
  4699. if ( parent !== null ) {
  4700. parent.remove( this );
  4701. }
  4702. return this;
  4703. }
  4704. clear() {
  4705. for ( let i = 0; i < this.children.length; i ++ ) {
  4706. const object = this.children[ i ];
  4707. object.parent = null;
  4708. object.dispatchEvent( _removedEvent );
  4709. }
  4710. this.children.length = 0;
  4711. return this;
  4712. }
  4713. attach( object ) {
  4714. // adds object as a child of this, while maintaining the object's world transform
  4715. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4716. this.updateWorldMatrix( true, false );
  4717. _m1$1.copy( this.matrixWorld ).invert();
  4718. if ( object.parent !== null ) {
  4719. object.parent.updateWorldMatrix( true, false );
  4720. _m1$1.multiply( object.parent.matrixWorld );
  4721. }
  4722. object.applyMatrix4( _m1$1 );
  4723. this.add( object );
  4724. object.updateWorldMatrix( false, true );
  4725. return this;
  4726. }
  4727. getObjectById( id ) {
  4728. return this.getObjectByProperty( 'id', id );
  4729. }
  4730. getObjectByName( name ) {
  4731. return this.getObjectByProperty( 'name', name );
  4732. }
  4733. getObjectByProperty( name, value ) {
  4734. if ( this[ name ] === value ) return this;
  4735. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4736. const child = this.children[ i ];
  4737. const object = child.getObjectByProperty( name, value );
  4738. if ( object !== undefined ) {
  4739. return object;
  4740. }
  4741. }
  4742. return undefined;
  4743. }
  4744. getWorldPosition( target ) {
  4745. this.updateWorldMatrix( true, false );
  4746. return target.setFromMatrixPosition( this.matrixWorld );
  4747. }
  4748. getWorldQuaternion( target ) {
  4749. this.updateWorldMatrix( true, false );
  4750. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4751. return target;
  4752. }
  4753. getWorldScale( target ) {
  4754. this.updateWorldMatrix( true, false );
  4755. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4756. return target;
  4757. }
  4758. getWorldDirection( target ) {
  4759. this.updateWorldMatrix( true, false );
  4760. const e = this.matrixWorld.elements;
  4761. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4762. }
  4763. raycast( /* raycaster, intersects */ ) {}
  4764. traverse( callback ) {
  4765. callback( this );
  4766. const children = this.children;
  4767. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4768. children[ i ].traverse( callback );
  4769. }
  4770. }
  4771. traverseVisible( callback ) {
  4772. if ( this.visible === false ) return;
  4773. callback( this );
  4774. const children = this.children;
  4775. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4776. children[ i ].traverseVisible( callback );
  4777. }
  4778. }
  4779. traverseAncestors( callback ) {
  4780. const parent = this.parent;
  4781. if ( parent !== null ) {
  4782. callback( parent );
  4783. parent.traverseAncestors( callback );
  4784. }
  4785. }
  4786. updateMatrix() {
  4787. this.matrix.compose( this.position, this.quaternion, this.scale );
  4788. this.matrixWorldNeedsUpdate = true;
  4789. }
  4790. updateMatrixWorld( force ) {
  4791. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4792. if ( this.matrixWorldNeedsUpdate || force ) {
  4793. if ( this.parent === null ) {
  4794. this.matrixWorld.copy( this.matrix );
  4795. } else {
  4796. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4797. }
  4798. this.matrixWorldNeedsUpdate = false;
  4799. force = true;
  4800. }
  4801. // update children
  4802. const children = this.children;
  4803. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4804. const child = children[ i ];
  4805. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4806. child.updateMatrixWorld( force );
  4807. }
  4808. }
  4809. }
  4810. updateWorldMatrix( updateParents, updateChildren ) {
  4811. const parent = this.parent;
  4812. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4813. parent.updateWorldMatrix( true, false );
  4814. }
  4815. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4816. if ( this.parent === null ) {
  4817. this.matrixWorld.copy( this.matrix );
  4818. } else {
  4819. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4820. }
  4821. // update children
  4822. if ( updateChildren === true ) {
  4823. const children = this.children;
  4824. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4825. const child = children[ i ];
  4826. if ( child.matrixWorldAutoUpdate === true ) {
  4827. child.updateWorldMatrix( false, true );
  4828. }
  4829. }
  4830. }
  4831. }
  4832. toJSON( meta ) {
  4833. // meta is a string when called from JSON.stringify
  4834. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4835. const output = {};
  4836. // meta is a hash used to collect geometries, materials.
  4837. // not providing it implies that this is the root object
  4838. // being serialized.
  4839. if ( isRootObject ) {
  4840. // initialize meta obj
  4841. meta = {
  4842. geometries: {},
  4843. materials: {},
  4844. textures: {},
  4845. images: {},
  4846. shapes: {},
  4847. skeletons: {},
  4848. animations: {},
  4849. nodes: {}
  4850. };
  4851. output.metadata = {
  4852. version: 4.5,
  4853. type: 'Object',
  4854. generator: 'Object3D.toJSON'
  4855. };
  4856. }
  4857. // standard Object3D serialization
  4858. const object = {};
  4859. object.uuid = this.uuid;
  4860. object.type = this.type;
  4861. if ( this.name !== '' ) object.name = this.name;
  4862. if ( this.castShadow === true ) object.castShadow = true;
  4863. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4864. if ( this.visible === false ) object.visible = false;
  4865. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4866. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4867. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4868. object.layers = this.layers.mask;
  4869. object.matrix = this.matrix.toArray();
  4870. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4871. // object specific properties
  4872. if ( this.isInstancedMesh ) {
  4873. object.type = 'InstancedMesh';
  4874. object.count = this.count;
  4875. object.instanceMatrix = this.instanceMatrix.toJSON();
  4876. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4877. }
  4878. //
  4879. function serialize( library, element ) {
  4880. if ( library[ element.uuid ] === undefined ) {
  4881. library[ element.uuid ] = element.toJSON( meta );
  4882. }
  4883. return element.uuid;
  4884. }
  4885. if ( this.isScene ) {
  4886. if ( this.background ) {
  4887. if ( this.background.isColor ) {
  4888. object.background = this.background.toJSON();
  4889. } else if ( this.background.isTexture ) {
  4890. object.background = this.background.toJSON( meta ).uuid;
  4891. }
  4892. }
  4893. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4894. object.environment = this.environment.toJSON( meta ).uuid;
  4895. }
  4896. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4897. object.geometry = serialize( meta.geometries, this.geometry );
  4898. const parameters = this.geometry.parameters;
  4899. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4900. const shapes = parameters.shapes;
  4901. if ( Array.isArray( shapes ) ) {
  4902. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4903. const shape = shapes[ i ];
  4904. serialize( meta.shapes, shape );
  4905. }
  4906. } else {
  4907. serialize( meta.shapes, shapes );
  4908. }
  4909. }
  4910. }
  4911. if ( this.isSkinnedMesh ) {
  4912. object.bindMode = this.bindMode;
  4913. object.bindMatrix = this.bindMatrix.toArray();
  4914. if ( this.skeleton !== undefined ) {
  4915. serialize( meta.skeletons, this.skeleton );
  4916. object.skeleton = this.skeleton.uuid;
  4917. }
  4918. }
  4919. if ( this.material !== undefined ) {
  4920. if ( Array.isArray( this.material ) ) {
  4921. const uuids = [];
  4922. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4923. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4924. }
  4925. object.material = uuids;
  4926. } else {
  4927. object.material = serialize( meta.materials, this.material );
  4928. }
  4929. }
  4930. //
  4931. if ( this.children.length > 0 ) {
  4932. object.children = [];
  4933. for ( let i = 0; i < this.children.length; i ++ ) {
  4934. object.children.push( this.children[ i ].toJSON( meta ).object );
  4935. }
  4936. }
  4937. //
  4938. if ( this.animations.length > 0 ) {
  4939. object.animations = [];
  4940. for ( let i = 0; i < this.animations.length; i ++ ) {
  4941. const animation = this.animations[ i ];
  4942. object.animations.push( serialize( meta.animations, animation ) );
  4943. }
  4944. }
  4945. if ( isRootObject ) {
  4946. const geometries = extractFromCache( meta.geometries );
  4947. const materials = extractFromCache( meta.materials );
  4948. const textures = extractFromCache( meta.textures );
  4949. const images = extractFromCache( meta.images );
  4950. const shapes = extractFromCache( meta.shapes );
  4951. const skeletons = extractFromCache( meta.skeletons );
  4952. const animations = extractFromCache( meta.animations );
  4953. const nodes = extractFromCache( meta.nodes );
  4954. if ( geometries.length > 0 ) output.geometries = geometries;
  4955. if ( materials.length > 0 ) output.materials = materials;
  4956. if ( textures.length > 0 ) output.textures = textures;
  4957. if ( images.length > 0 ) output.images = images;
  4958. if ( shapes.length > 0 ) output.shapes = shapes;
  4959. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4960. if ( animations.length > 0 ) output.animations = animations;
  4961. if ( nodes.length > 0 ) output.nodes = nodes;
  4962. }
  4963. output.object = object;
  4964. return output;
  4965. // extract data from the cache hash
  4966. // remove metadata on each item
  4967. // and return as array
  4968. function extractFromCache( cache ) {
  4969. const values = [];
  4970. for ( const key in cache ) {
  4971. const data = cache[ key ];
  4972. delete data.metadata;
  4973. values.push( data );
  4974. }
  4975. return values;
  4976. }
  4977. }
  4978. clone( recursive ) {
  4979. return new this.constructor().copy( this, recursive );
  4980. }
  4981. copy( source, recursive = true ) {
  4982. this.name = source.name;
  4983. this.up.copy( source.up );
  4984. this.position.copy( source.position );
  4985. this.rotation.order = source.rotation.order;
  4986. this.quaternion.copy( source.quaternion );
  4987. this.scale.copy( source.scale );
  4988. this.matrix.copy( source.matrix );
  4989. this.matrixWorld.copy( source.matrixWorld );
  4990. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4991. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4992. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4993. this.layers.mask = source.layers.mask;
  4994. this.visible = source.visible;
  4995. this.castShadow = source.castShadow;
  4996. this.receiveShadow = source.receiveShadow;
  4997. this.frustumCulled = source.frustumCulled;
  4998. this.renderOrder = source.renderOrder;
  4999. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5000. if ( recursive === true ) {
  5001. for ( let i = 0; i < source.children.length; i ++ ) {
  5002. const child = source.children[ i ];
  5003. this.add( child.clone() );
  5004. }
  5005. }
  5006. return this;
  5007. }
  5008. }
  5009. Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5010. Object3D.DefaultMatrixAutoUpdate = true;
  5011. Object3D.DefaultMatrixWorldAutoUpdate = true;
  5012. const _v0$1 = /*@__PURE__*/ new Vector3();
  5013. const _v1$3 = /*@__PURE__*/ new Vector3();
  5014. const _v2$2 = /*@__PURE__*/ new Vector3();
  5015. const _v3$1 = /*@__PURE__*/ new Vector3();
  5016. const _vab = /*@__PURE__*/ new Vector3();
  5017. const _vac = /*@__PURE__*/ new Vector3();
  5018. const _vbc = /*@__PURE__*/ new Vector3();
  5019. const _vap = /*@__PURE__*/ new Vector3();
  5020. const _vbp = /*@__PURE__*/ new Vector3();
  5021. const _vcp = /*@__PURE__*/ new Vector3();
  5022. class Triangle {
  5023. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5024. this.a = a;
  5025. this.b = b;
  5026. this.c = c;
  5027. }
  5028. static getNormal( a, b, c, target ) {
  5029. target.subVectors( c, b );
  5030. _v0$1.subVectors( a, b );
  5031. target.cross( _v0$1 );
  5032. const targetLengthSq = target.lengthSq();
  5033. if ( targetLengthSq > 0 ) {
  5034. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5035. }
  5036. return target.set( 0, 0, 0 );
  5037. }
  5038. // static/instance method to calculate barycentric coordinates
  5039. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5040. static getBarycoord( point, a, b, c, target ) {
  5041. _v0$1.subVectors( c, a );
  5042. _v1$3.subVectors( b, a );
  5043. _v2$2.subVectors( point, a );
  5044. const dot00 = _v0$1.dot( _v0$1 );
  5045. const dot01 = _v0$1.dot( _v1$3 );
  5046. const dot02 = _v0$1.dot( _v2$2 );
  5047. const dot11 = _v1$3.dot( _v1$3 );
  5048. const dot12 = _v1$3.dot( _v2$2 );
  5049. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5050. // collinear or singular triangle
  5051. if ( denom === 0 ) {
  5052. // arbitrary location outside of triangle?
  5053. // not sure if this is the best idea, maybe should be returning undefined
  5054. return target.set( - 2, - 1, - 1 );
  5055. }
  5056. const invDenom = 1 / denom;
  5057. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5058. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5059. // barycentric coordinates must always sum to 1
  5060. return target.set( 1 - u - v, v, u );
  5061. }
  5062. static containsPoint( point, a, b, c ) {
  5063. this.getBarycoord( point, a, b, c, _v3$1 );
  5064. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5065. }
  5066. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5067. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5068. target.set( 0, 0 );
  5069. target.addScaledVector( uv1, _v3$1.x );
  5070. target.addScaledVector( uv2, _v3$1.y );
  5071. target.addScaledVector( uv3, _v3$1.z );
  5072. return target;
  5073. }
  5074. static isFrontFacing( a, b, c, direction ) {
  5075. _v0$1.subVectors( c, b );
  5076. _v1$3.subVectors( a, b );
  5077. // strictly front facing
  5078. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5079. }
  5080. set( a, b, c ) {
  5081. this.a.copy( a );
  5082. this.b.copy( b );
  5083. this.c.copy( c );
  5084. return this;
  5085. }
  5086. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5087. this.a.copy( points[ i0 ] );
  5088. this.b.copy( points[ i1 ] );
  5089. this.c.copy( points[ i2 ] );
  5090. return this;
  5091. }
  5092. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5093. this.a.fromBufferAttribute( attribute, i0 );
  5094. this.b.fromBufferAttribute( attribute, i1 );
  5095. this.c.fromBufferAttribute( attribute, i2 );
  5096. return this;
  5097. }
  5098. clone() {
  5099. return new this.constructor().copy( this );
  5100. }
  5101. copy( triangle ) {
  5102. this.a.copy( triangle.a );
  5103. this.b.copy( triangle.b );
  5104. this.c.copy( triangle.c );
  5105. return this;
  5106. }
  5107. getArea() {
  5108. _v0$1.subVectors( this.c, this.b );
  5109. _v1$3.subVectors( this.a, this.b );
  5110. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5111. }
  5112. getMidpoint( target ) {
  5113. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5114. }
  5115. getNormal( target ) {
  5116. return Triangle.getNormal( this.a, this.b, this.c, target );
  5117. }
  5118. getPlane( target ) {
  5119. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5120. }
  5121. getBarycoord( point, target ) {
  5122. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5123. }
  5124. getUV( point, uv1, uv2, uv3, target ) {
  5125. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5126. }
  5127. containsPoint( point ) {
  5128. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5129. }
  5130. isFrontFacing( direction ) {
  5131. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5132. }
  5133. intersectsBox( box ) {
  5134. return box.intersectsTriangle( this );
  5135. }
  5136. closestPointToPoint( p, target ) {
  5137. const a = this.a, b = this.b, c = this.c;
  5138. let v, w;
  5139. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5140. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5141. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5142. // basically, we're distinguishing which of the voronoi regions of the triangle
  5143. // the point lies in with the minimum amount of redundant computation.
  5144. _vab.subVectors( b, a );
  5145. _vac.subVectors( c, a );
  5146. _vap.subVectors( p, a );
  5147. const d1 = _vab.dot( _vap );
  5148. const d2 = _vac.dot( _vap );
  5149. if ( d1 <= 0 && d2 <= 0 ) {
  5150. // vertex region of A; barycentric coords (1, 0, 0)
  5151. return target.copy( a );
  5152. }
  5153. _vbp.subVectors( p, b );
  5154. const d3 = _vab.dot( _vbp );
  5155. const d4 = _vac.dot( _vbp );
  5156. if ( d3 >= 0 && d4 <= d3 ) {
  5157. // vertex region of B; barycentric coords (0, 1, 0)
  5158. return target.copy( b );
  5159. }
  5160. const vc = d1 * d4 - d3 * d2;
  5161. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5162. v = d1 / ( d1 - d3 );
  5163. // edge region of AB; barycentric coords (1-v, v, 0)
  5164. return target.copy( a ).addScaledVector( _vab, v );
  5165. }
  5166. _vcp.subVectors( p, c );
  5167. const d5 = _vab.dot( _vcp );
  5168. const d6 = _vac.dot( _vcp );
  5169. if ( d6 >= 0 && d5 <= d6 ) {
  5170. // vertex region of C; barycentric coords (0, 0, 1)
  5171. return target.copy( c );
  5172. }
  5173. const vb = d5 * d2 - d1 * d6;
  5174. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5175. w = d2 / ( d2 - d6 );
  5176. // edge region of AC; barycentric coords (1-w, 0, w)
  5177. return target.copy( a ).addScaledVector( _vac, w );
  5178. }
  5179. const va = d3 * d6 - d5 * d4;
  5180. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5181. _vbc.subVectors( c, b );
  5182. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5183. // edge region of BC; barycentric coords (0, 1-w, w)
  5184. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5185. }
  5186. // face region
  5187. const denom = 1 / ( va + vb + vc );
  5188. // u = va * denom
  5189. v = vb * denom;
  5190. w = vc * denom;
  5191. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5192. }
  5193. equals( triangle ) {
  5194. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5195. }
  5196. }
  5197. let materialId = 0;
  5198. class Material extends EventDispatcher {
  5199. constructor() {
  5200. super();
  5201. this.isMaterial = true;
  5202. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5203. this.uuid = generateUUID();
  5204. this.name = '';
  5205. this.type = 'Material';
  5206. this.blending = NormalBlending;
  5207. this.side = FrontSide;
  5208. this.vertexColors = false;
  5209. this.opacity = 1;
  5210. this.transparent = false;
  5211. this.blendSrc = SrcAlphaFactor;
  5212. this.blendDst = OneMinusSrcAlphaFactor;
  5213. this.blendEquation = AddEquation;
  5214. this.blendSrcAlpha = null;
  5215. this.blendDstAlpha = null;
  5216. this.blendEquationAlpha = null;
  5217. this.depthFunc = LessEqualDepth;
  5218. this.depthTest = true;
  5219. this.depthWrite = true;
  5220. this.stencilWriteMask = 0xff;
  5221. this.stencilFunc = AlwaysStencilFunc;
  5222. this.stencilRef = 0;
  5223. this.stencilFuncMask = 0xff;
  5224. this.stencilFail = KeepStencilOp;
  5225. this.stencilZFail = KeepStencilOp;
  5226. this.stencilZPass = KeepStencilOp;
  5227. this.stencilWrite = false;
  5228. this.clippingPlanes = null;
  5229. this.clipIntersection = false;
  5230. this.clipShadows = false;
  5231. this.shadowSide = null;
  5232. this.colorWrite = true;
  5233. this.precision = null; // override the renderer's default precision for this material
  5234. this.polygonOffset = false;
  5235. this.polygonOffsetFactor = 0;
  5236. this.polygonOffsetUnits = 0;
  5237. this.dithering = false;
  5238. this.alphaToCoverage = false;
  5239. this.premultipliedAlpha = false;
  5240. this.visible = true;
  5241. this.toneMapped = true;
  5242. this.userData = {};
  5243. this.version = 0;
  5244. this._alphaTest = 0;
  5245. }
  5246. get alphaTest() {
  5247. return this._alphaTest;
  5248. }
  5249. set alphaTest( value ) {
  5250. if ( this._alphaTest > 0 !== value > 0 ) {
  5251. this.version ++;
  5252. }
  5253. this._alphaTest = value;
  5254. }
  5255. onBuild( /* shaderobject, renderer */ ) {}
  5256. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5257. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5258. customProgramCacheKey() {
  5259. return this.onBeforeCompile.toString();
  5260. }
  5261. setValues( values ) {
  5262. if ( values === undefined ) return;
  5263. for ( const key in values ) {
  5264. const newValue = values[ key ];
  5265. if ( newValue === undefined ) {
  5266. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5267. continue;
  5268. }
  5269. const currentValue = this[ key ];
  5270. if ( currentValue === undefined ) {
  5271. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5272. continue;
  5273. }
  5274. if ( currentValue && currentValue.isColor ) {
  5275. currentValue.set( newValue );
  5276. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5277. currentValue.copy( newValue );
  5278. } else {
  5279. this[ key ] = newValue;
  5280. }
  5281. }
  5282. }
  5283. toJSON( meta ) {
  5284. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5285. if ( isRootObject ) {
  5286. meta = {
  5287. textures: {},
  5288. images: {}
  5289. };
  5290. }
  5291. const data = {
  5292. metadata: {
  5293. version: 4.5,
  5294. type: 'Material',
  5295. generator: 'Material.toJSON'
  5296. }
  5297. };
  5298. // standard Material serialization
  5299. data.uuid = this.uuid;
  5300. data.type = this.type;
  5301. if ( this.name !== '' ) data.name = this.name;
  5302. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5303. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5304. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5305. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5306. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5307. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5308. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5309. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5310. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5311. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5312. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5313. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5314. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5315. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5316. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5317. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5318. }
  5319. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5320. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5321. }
  5322. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5323. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5324. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5325. }
  5326. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5327. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5328. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5329. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5330. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5331. }
  5332. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5333. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5334. }
  5335. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5336. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5337. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5338. if ( this.lightMap && this.lightMap.isTexture ) {
  5339. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5340. data.lightMapIntensity = this.lightMapIntensity;
  5341. }
  5342. if ( this.aoMap && this.aoMap.isTexture ) {
  5343. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5344. data.aoMapIntensity = this.aoMapIntensity;
  5345. }
  5346. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5347. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5348. data.bumpScale = this.bumpScale;
  5349. }
  5350. if ( this.normalMap && this.normalMap.isTexture ) {
  5351. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5352. data.normalMapType = this.normalMapType;
  5353. data.normalScale = this.normalScale.toArray();
  5354. }
  5355. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5356. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5357. data.displacementScale = this.displacementScale;
  5358. data.displacementBias = this.displacementBias;
  5359. }
  5360. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5361. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5362. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5363. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5364. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5365. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5366. if ( this.envMap && this.envMap.isTexture ) {
  5367. data.envMap = this.envMap.toJSON( meta ).uuid;
  5368. if ( this.combine !== undefined ) data.combine = this.combine;
  5369. }
  5370. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5371. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5372. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5373. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5374. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5375. }
  5376. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5377. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5378. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5379. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5380. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  5381. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5382. if ( this.size !== undefined ) data.size = this.size;
  5383. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5384. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5385. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5386. if ( this.side !== FrontSide ) data.side = this.side;
  5387. if ( this.vertexColors ) data.vertexColors = true;
  5388. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5389. if ( this.transparent === true ) data.transparent = this.transparent;
  5390. data.depthFunc = this.depthFunc;
  5391. data.depthTest = this.depthTest;
  5392. data.depthWrite = this.depthWrite;
  5393. data.colorWrite = this.colorWrite;
  5394. data.stencilWrite = this.stencilWrite;
  5395. data.stencilWriteMask = this.stencilWriteMask;
  5396. data.stencilFunc = this.stencilFunc;
  5397. data.stencilRef = this.stencilRef;
  5398. data.stencilFuncMask = this.stencilFuncMask;
  5399. data.stencilFail = this.stencilFail;
  5400. data.stencilZFail = this.stencilZFail;
  5401. data.stencilZPass = this.stencilZPass;
  5402. // rotation (SpriteMaterial)
  5403. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5404. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5405. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5406. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5407. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5408. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5409. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5410. if ( this.scale !== undefined ) data.scale = this.scale;
  5411. if ( this.dithering === true ) data.dithering = true;
  5412. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5413. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5414. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5415. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5416. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5417. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5418. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5419. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5420. if ( this.visible === false ) data.visible = false;
  5421. if ( this.toneMapped === false ) data.toneMapped = false;
  5422. if ( this.fog === false ) data.fog = false;
  5423. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5424. // TODO: Copied from Object3D.toJSON
  5425. function extractFromCache( cache ) {
  5426. const values = [];
  5427. for ( const key in cache ) {
  5428. const data = cache[ key ];
  5429. delete data.metadata;
  5430. values.push( data );
  5431. }
  5432. return values;
  5433. }
  5434. if ( isRootObject ) {
  5435. const textures = extractFromCache( meta.textures );
  5436. const images = extractFromCache( meta.images );
  5437. if ( textures.length > 0 ) data.textures = textures;
  5438. if ( images.length > 0 ) data.images = images;
  5439. }
  5440. return data;
  5441. }
  5442. clone() {
  5443. return new this.constructor().copy( this );
  5444. }
  5445. copy( source ) {
  5446. this.name = source.name;
  5447. this.blending = source.blending;
  5448. this.side = source.side;
  5449. this.vertexColors = source.vertexColors;
  5450. this.opacity = source.opacity;
  5451. this.transparent = source.transparent;
  5452. this.blendSrc = source.blendSrc;
  5453. this.blendDst = source.blendDst;
  5454. this.blendEquation = source.blendEquation;
  5455. this.blendSrcAlpha = source.blendSrcAlpha;
  5456. this.blendDstAlpha = source.blendDstAlpha;
  5457. this.blendEquationAlpha = source.blendEquationAlpha;
  5458. this.depthFunc = source.depthFunc;
  5459. this.depthTest = source.depthTest;
  5460. this.depthWrite = source.depthWrite;
  5461. this.stencilWriteMask = source.stencilWriteMask;
  5462. this.stencilFunc = source.stencilFunc;
  5463. this.stencilRef = source.stencilRef;
  5464. this.stencilFuncMask = source.stencilFuncMask;
  5465. this.stencilFail = source.stencilFail;
  5466. this.stencilZFail = source.stencilZFail;
  5467. this.stencilZPass = source.stencilZPass;
  5468. this.stencilWrite = source.stencilWrite;
  5469. const srcPlanes = source.clippingPlanes;
  5470. let dstPlanes = null;
  5471. if ( srcPlanes !== null ) {
  5472. const n = srcPlanes.length;
  5473. dstPlanes = new Array( n );
  5474. for ( let i = 0; i !== n; ++ i ) {
  5475. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5476. }
  5477. }
  5478. this.clippingPlanes = dstPlanes;
  5479. this.clipIntersection = source.clipIntersection;
  5480. this.clipShadows = source.clipShadows;
  5481. this.shadowSide = source.shadowSide;
  5482. this.colorWrite = source.colorWrite;
  5483. this.precision = source.precision;
  5484. this.polygonOffset = source.polygonOffset;
  5485. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5486. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5487. this.dithering = source.dithering;
  5488. this.alphaTest = source.alphaTest;
  5489. this.alphaToCoverage = source.alphaToCoverage;
  5490. this.premultipliedAlpha = source.premultipliedAlpha;
  5491. this.visible = source.visible;
  5492. this.toneMapped = source.toneMapped;
  5493. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5494. return this;
  5495. }
  5496. dispose() {
  5497. this.dispatchEvent( { type: 'dispose' } );
  5498. }
  5499. set needsUpdate( value ) {
  5500. if ( value === true ) this.version ++;
  5501. }
  5502. }
  5503. class MeshBasicMaterial extends Material {
  5504. constructor( parameters ) {
  5505. super();
  5506. this.isMeshBasicMaterial = true;
  5507. this.type = 'MeshBasicMaterial';
  5508. this.color = new Color( 0xffffff ); // emissive
  5509. this.map = null;
  5510. this.lightMap = null;
  5511. this.lightMapIntensity = 1.0;
  5512. this.aoMap = null;
  5513. this.aoMapIntensity = 1.0;
  5514. this.specularMap = null;
  5515. this.alphaMap = null;
  5516. this.envMap = null;
  5517. this.combine = MultiplyOperation;
  5518. this.reflectivity = 1;
  5519. this.refractionRatio = 0.98;
  5520. this.wireframe = false;
  5521. this.wireframeLinewidth = 1;
  5522. this.wireframeLinecap = 'round';
  5523. this.wireframeLinejoin = 'round';
  5524. this.fog = true;
  5525. this.setValues( parameters );
  5526. }
  5527. copy( source ) {
  5528. super.copy( source );
  5529. this.color.copy( source.color );
  5530. this.map = source.map;
  5531. this.lightMap = source.lightMap;
  5532. this.lightMapIntensity = source.lightMapIntensity;
  5533. this.aoMap = source.aoMap;
  5534. this.aoMapIntensity = source.aoMapIntensity;
  5535. this.specularMap = source.specularMap;
  5536. this.alphaMap = source.alphaMap;
  5537. this.envMap = source.envMap;
  5538. this.combine = source.combine;
  5539. this.reflectivity = source.reflectivity;
  5540. this.refractionRatio = source.refractionRatio;
  5541. this.wireframe = source.wireframe;
  5542. this.wireframeLinewidth = source.wireframeLinewidth;
  5543. this.wireframeLinecap = source.wireframeLinecap;
  5544. this.wireframeLinejoin = source.wireframeLinejoin;
  5545. this.fog = source.fog;
  5546. return this;
  5547. }
  5548. }
  5549. const _vector$9 = /*@__PURE__*/ new Vector3();
  5550. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5551. class BufferAttribute {
  5552. constructor( array, itemSize, normalized ) {
  5553. if ( Array.isArray( array ) ) {
  5554. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5555. }
  5556. this.isBufferAttribute = true;
  5557. this.name = '';
  5558. this.array = array;
  5559. this.itemSize = itemSize;
  5560. this.count = array !== undefined ? array.length / itemSize : 0;
  5561. this.normalized = normalized === true;
  5562. this.usage = StaticDrawUsage;
  5563. this.updateRange = { offset: 0, count: - 1 };
  5564. this.version = 0;
  5565. }
  5566. onUploadCallback() {}
  5567. set needsUpdate( value ) {
  5568. if ( value === true ) this.version ++;
  5569. }
  5570. setUsage( value ) {
  5571. this.usage = value;
  5572. return this;
  5573. }
  5574. copy( source ) {
  5575. this.name = source.name;
  5576. this.array = new source.array.constructor( source.array );
  5577. this.itemSize = source.itemSize;
  5578. this.count = source.count;
  5579. this.normalized = source.normalized;
  5580. this.usage = source.usage;
  5581. return this;
  5582. }
  5583. copyAt( index1, attribute, index2 ) {
  5584. index1 *= this.itemSize;
  5585. index2 *= attribute.itemSize;
  5586. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5587. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5588. }
  5589. return this;
  5590. }
  5591. copyArray( array ) {
  5592. this.array.set( array );
  5593. return this;
  5594. }
  5595. applyMatrix3( m ) {
  5596. if ( this.itemSize === 2 ) {
  5597. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5598. _vector2$1.fromBufferAttribute( this, i );
  5599. _vector2$1.applyMatrix3( m );
  5600. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5601. }
  5602. } else if ( this.itemSize === 3 ) {
  5603. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5604. _vector$9.fromBufferAttribute( this, i );
  5605. _vector$9.applyMatrix3( m );
  5606. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5607. }
  5608. }
  5609. return this;
  5610. }
  5611. applyMatrix4( m ) {
  5612. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5613. _vector$9.fromBufferAttribute( this, i );
  5614. _vector$9.applyMatrix4( m );
  5615. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5616. }
  5617. return this;
  5618. }
  5619. applyNormalMatrix( m ) {
  5620. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5621. _vector$9.fromBufferAttribute( this, i );
  5622. _vector$9.applyNormalMatrix( m );
  5623. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5624. }
  5625. return this;
  5626. }
  5627. transformDirection( m ) {
  5628. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5629. _vector$9.fromBufferAttribute( this, i );
  5630. _vector$9.transformDirection( m );
  5631. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5632. }
  5633. return this;
  5634. }
  5635. set( value, offset = 0 ) {
  5636. // Matching BufferAttribute constructor, do not normalize the array.
  5637. this.array.set( value, offset );
  5638. return this;
  5639. }
  5640. getX( index ) {
  5641. let x = this.array[ index * this.itemSize ];
  5642. if ( this.normalized ) x = denormalize( x, this.array );
  5643. return x;
  5644. }
  5645. setX( index, x ) {
  5646. if ( this.normalized ) x = normalize( x, this.array );
  5647. this.array[ index * this.itemSize ] = x;
  5648. return this;
  5649. }
  5650. getY( index ) {
  5651. let y = this.array[ index * this.itemSize + 1 ];
  5652. if ( this.normalized ) y = denormalize( y, this.array );
  5653. return y;
  5654. }
  5655. setY( index, y ) {
  5656. if ( this.normalized ) y = normalize( y, this.array );
  5657. this.array[ index * this.itemSize + 1 ] = y;
  5658. return this;
  5659. }
  5660. getZ( index ) {
  5661. let z = this.array[ index * this.itemSize + 2 ];
  5662. if ( this.normalized ) z = denormalize( z, this.array );
  5663. return z;
  5664. }
  5665. setZ( index, z ) {
  5666. if ( this.normalized ) z = normalize( z, this.array );
  5667. this.array[ index * this.itemSize + 2 ] = z;
  5668. return this;
  5669. }
  5670. getW( index ) {
  5671. let w = this.array[ index * this.itemSize + 3 ];
  5672. if ( this.normalized ) w = denormalize( w, this.array );
  5673. return w;
  5674. }
  5675. setW( index, w ) {
  5676. if ( this.normalized ) w = normalize( w, this.array );
  5677. this.array[ index * this.itemSize + 3 ] = w;
  5678. return this;
  5679. }
  5680. setXY( index, x, y ) {
  5681. index *= this.itemSize;
  5682. if ( this.normalized ) {
  5683. x = normalize( x, this.array );
  5684. y = normalize( y, this.array );
  5685. }
  5686. this.array[ index + 0 ] = x;
  5687. this.array[ index + 1 ] = y;
  5688. return this;
  5689. }
  5690. setXYZ( index, x, y, z ) {
  5691. index *= this.itemSize;
  5692. if ( this.normalized ) {
  5693. x = normalize( x, this.array );
  5694. y = normalize( y, this.array );
  5695. z = normalize( z, this.array );
  5696. }
  5697. this.array[ index + 0 ] = x;
  5698. this.array[ index + 1 ] = y;
  5699. this.array[ index + 2 ] = z;
  5700. return this;
  5701. }
  5702. setXYZW( index, x, y, z, w ) {
  5703. index *= this.itemSize;
  5704. if ( this.normalized ) {
  5705. x = normalize( x, this.array );
  5706. y = normalize( y, this.array );
  5707. z = normalize( z, this.array );
  5708. w = normalize( w, this.array );
  5709. }
  5710. this.array[ index + 0 ] = x;
  5711. this.array[ index + 1 ] = y;
  5712. this.array[ index + 2 ] = z;
  5713. this.array[ index + 3 ] = w;
  5714. return this;
  5715. }
  5716. onUpload( callback ) {
  5717. this.onUploadCallback = callback;
  5718. return this;
  5719. }
  5720. clone() {
  5721. return new this.constructor( this.array, this.itemSize ).copy( this );
  5722. }
  5723. toJSON() {
  5724. const data = {
  5725. itemSize: this.itemSize,
  5726. type: this.array.constructor.name,
  5727. array: Array.from( this.array ),
  5728. normalized: this.normalized
  5729. };
  5730. if ( this.name !== '' ) data.name = this.name;
  5731. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5732. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5733. return data;
  5734. }
  5735. // @deprecated
  5736. copyColorsArray() {
  5737. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5738. }
  5739. copyVector2sArray() {
  5740. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5741. }
  5742. copyVector3sArray() {
  5743. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5744. }
  5745. copyVector4sArray() {
  5746. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5747. }
  5748. }
  5749. //
  5750. class Int8BufferAttribute extends BufferAttribute {
  5751. constructor( array, itemSize, normalized ) {
  5752. super( new Int8Array( array ), itemSize, normalized );
  5753. }
  5754. }
  5755. class Uint8BufferAttribute extends BufferAttribute {
  5756. constructor( array, itemSize, normalized ) {
  5757. super( new Uint8Array( array ), itemSize, normalized );
  5758. }
  5759. }
  5760. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5761. constructor( array, itemSize, normalized ) {
  5762. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5763. }
  5764. }
  5765. class Int16BufferAttribute extends BufferAttribute {
  5766. constructor( array, itemSize, normalized ) {
  5767. super( new Int16Array( array ), itemSize, normalized );
  5768. }
  5769. }
  5770. class Uint16BufferAttribute extends BufferAttribute {
  5771. constructor( array, itemSize, normalized ) {
  5772. super( new Uint16Array( array ), itemSize, normalized );
  5773. }
  5774. }
  5775. class Int32BufferAttribute extends BufferAttribute {
  5776. constructor( array, itemSize, normalized ) {
  5777. super( new Int32Array( array ), itemSize, normalized );
  5778. }
  5779. }
  5780. class Uint32BufferAttribute extends BufferAttribute {
  5781. constructor( array, itemSize, normalized ) {
  5782. super( new Uint32Array( array ), itemSize, normalized );
  5783. }
  5784. }
  5785. class Float16BufferAttribute extends BufferAttribute {
  5786. constructor( array, itemSize, normalized ) {
  5787. super( new Uint16Array( array ), itemSize, normalized );
  5788. this.isFloat16BufferAttribute = true;
  5789. }
  5790. }
  5791. class Float32BufferAttribute extends BufferAttribute {
  5792. constructor( array, itemSize, normalized ) {
  5793. super( new Float32Array( array ), itemSize, normalized );
  5794. }
  5795. }
  5796. class Float64BufferAttribute extends BufferAttribute {
  5797. constructor( array, itemSize, normalized ) {
  5798. super( new Float64Array( array ), itemSize, normalized );
  5799. }
  5800. }
  5801. let _id$1 = 0;
  5802. const _m1 = /*@__PURE__*/ new Matrix4();
  5803. const _obj = /*@__PURE__*/ new Object3D();
  5804. const _offset = /*@__PURE__*/ new Vector3();
  5805. const _box$1 = /*@__PURE__*/ new Box3();
  5806. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5807. const _vector$8 = /*@__PURE__*/ new Vector3();
  5808. class BufferGeometry extends EventDispatcher {
  5809. constructor() {
  5810. super();
  5811. this.isBufferGeometry = true;
  5812. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5813. this.uuid = generateUUID();
  5814. this.name = '';
  5815. this.type = 'BufferGeometry';
  5816. this.index = null;
  5817. this.attributes = {};
  5818. this.morphAttributes = {};
  5819. this.morphTargetsRelative = false;
  5820. this.groups = [];
  5821. this.boundingBox = null;
  5822. this.boundingSphere = null;
  5823. this.drawRange = { start: 0, count: Infinity };
  5824. this.userData = {};
  5825. }
  5826. getIndex() {
  5827. return this.index;
  5828. }
  5829. setIndex( index ) {
  5830. if ( Array.isArray( index ) ) {
  5831. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5832. } else {
  5833. this.index = index;
  5834. }
  5835. return this;
  5836. }
  5837. getAttribute( name ) {
  5838. return this.attributes[ name ];
  5839. }
  5840. setAttribute( name, attribute ) {
  5841. this.attributes[ name ] = attribute;
  5842. return this;
  5843. }
  5844. deleteAttribute( name ) {
  5845. delete this.attributes[ name ];
  5846. return this;
  5847. }
  5848. hasAttribute( name ) {
  5849. return this.attributes[ name ] !== undefined;
  5850. }
  5851. addGroup( start, count, materialIndex = 0 ) {
  5852. this.groups.push( {
  5853. start: start,
  5854. count: count,
  5855. materialIndex: materialIndex
  5856. } );
  5857. }
  5858. clearGroups() {
  5859. this.groups = [];
  5860. }
  5861. setDrawRange( start, count ) {
  5862. this.drawRange.start = start;
  5863. this.drawRange.count = count;
  5864. }
  5865. applyMatrix4( matrix ) {
  5866. const position = this.attributes.position;
  5867. if ( position !== undefined ) {
  5868. position.applyMatrix4( matrix );
  5869. position.needsUpdate = true;
  5870. }
  5871. const normal = this.attributes.normal;
  5872. if ( normal !== undefined ) {
  5873. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5874. normal.applyNormalMatrix( normalMatrix );
  5875. normal.needsUpdate = true;
  5876. }
  5877. const tangent = this.attributes.tangent;
  5878. if ( tangent !== undefined ) {
  5879. tangent.transformDirection( matrix );
  5880. tangent.needsUpdate = true;
  5881. }
  5882. if ( this.boundingBox !== null ) {
  5883. this.computeBoundingBox();
  5884. }
  5885. if ( this.boundingSphere !== null ) {
  5886. this.computeBoundingSphere();
  5887. }
  5888. return this;
  5889. }
  5890. applyQuaternion( q ) {
  5891. _m1.makeRotationFromQuaternion( q );
  5892. this.applyMatrix4( _m1 );
  5893. return this;
  5894. }
  5895. rotateX( angle ) {
  5896. // rotate geometry around world x-axis
  5897. _m1.makeRotationX( angle );
  5898. this.applyMatrix4( _m1 );
  5899. return this;
  5900. }
  5901. rotateY( angle ) {
  5902. // rotate geometry around world y-axis
  5903. _m1.makeRotationY( angle );
  5904. this.applyMatrix4( _m1 );
  5905. return this;
  5906. }
  5907. rotateZ( angle ) {
  5908. // rotate geometry around world z-axis
  5909. _m1.makeRotationZ( angle );
  5910. this.applyMatrix4( _m1 );
  5911. return this;
  5912. }
  5913. translate( x, y, z ) {
  5914. // translate geometry
  5915. _m1.makeTranslation( x, y, z );
  5916. this.applyMatrix4( _m1 );
  5917. return this;
  5918. }
  5919. scale( x, y, z ) {
  5920. // scale geometry
  5921. _m1.makeScale( x, y, z );
  5922. this.applyMatrix4( _m1 );
  5923. return this;
  5924. }
  5925. lookAt( vector ) {
  5926. _obj.lookAt( vector );
  5927. _obj.updateMatrix();
  5928. this.applyMatrix4( _obj.matrix );
  5929. return this;
  5930. }
  5931. center() {
  5932. this.computeBoundingBox();
  5933. this.boundingBox.getCenter( _offset ).negate();
  5934. this.translate( _offset.x, _offset.y, _offset.z );
  5935. return this;
  5936. }
  5937. setFromPoints( points ) {
  5938. const position = [];
  5939. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5940. const point = points[ i ];
  5941. position.push( point.x, point.y, point.z || 0 );
  5942. }
  5943. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5944. return this;
  5945. }
  5946. computeBoundingBox() {
  5947. if ( this.boundingBox === null ) {
  5948. this.boundingBox = new Box3();
  5949. }
  5950. const position = this.attributes.position;
  5951. const morphAttributesPosition = this.morphAttributes.position;
  5952. if ( position && position.isGLBufferAttribute ) {
  5953. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5954. this.boundingBox.set(
  5955. new Vector3( - Infinity, - Infinity, - Infinity ),
  5956. new Vector3( + Infinity, + Infinity, + Infinity )
  5957. );
  5958. return;
  5959. }
  5960. if ( position !== undefined ) {
  5961. this.boundingBox.setFromBufferAttribute( position );
  5962. // process morph attributes if present
  5963. if ( morphAttributesPosition ) {
  5964. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5965. const morphAttribute = morphAttributesPosition[ i ];
  5966. _box$1.setFromBufferAttribute( morphAttribute );
  5967. if ( this.morphTargetsRelative ) {
  5968. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5969. this.boundingBox.expandByPoint( _vector$8 );
  5970. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5971. this.boundingBox.expandByPoint( _vector$8 );
  5972. } else {
  5973. this.boundingBox.expandByPoint( _box$1.min );
  5974. this.boundingBox.expandByPoint( _box$1.max );
  5975. }
  5976. }
  5977. }
  5978. } else {
  5979. this.boundingBox.makeEmpty();
  5980. }
  5981. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5982. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5983. }
  5984. }
  5985. computeBoundingSphere() {
  5986. if ( this.boundingSphere === null ) {
  5987. this.boundingSphere = new Sphere();
  5988. }
  5989. const position = this.attributes.position;
  5990. const morphAttributesPosition = this.morphAttributes.position;
  5991. if ( position && position.isGLBufferAttribute ) {
  5992. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5993. this.boundingSphere.set( new Vector3(), Infinity );
  5994. return;
  5995. }
  5996. if ( position ) {
  5997. // first, find the center of the bounding sphere
  5998. const center = this.boundingSphere.center;
  5999. _box$1.setFromBufferAttribute( position );
  6000. // process morph attributes if present
  6001. if ( morphAttributesPosition ) {
  6002. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6003. const morphAttribute = morphAttributesPosition[ i ];
  6004. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6005. if ( this.morphTargetsRelative ) {
  6006. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6007. _box$1.expandByPoint( _vector$8 );
  6008. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6009. _box$1.expandByPoint( _vector$8 );
  6010. } else {
  6011. _box$1.expandByPoint( _boxMorphTargets.min );
  6012. _box$1.expandByPoint( _boxMorphTargets.max );
  6013. }
  6014. }
  6015. }
  6016. _box$1.getCenter( center );
  6017. // second, try to find a boundingSphere with a radius smaller than the
  6018. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6019. let maxRadiusSq = 0;
  6020. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6021. _vector$8.fromBufferAttribute( position, i );
  6022. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6023. }
  6024. // process morph attributes if present
  6025. if ( morphAttributesPosition ) {
  6026. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6027. const morphAttribute = morphAttributesPosition[ i ];
  6028. const morphTargetsRelative = this.morphTargetsRelative;
  6029. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6030. _vector$8.fromBufferAttribute( morphAttribute, j );
  6031. if ( morphTargetsRelative ) {
  6032. _offset.fromBufferAttribute( position, j );
  6033. _vector$8.add( _offset );
  6034. }
  6035. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6036. }
  6037. }
  6038. }
  6039. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6040. if ( isNaN( this.boundingSphere.radius ) ) {
  6041. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6042. }
  6043. }
  6044. }
  6045. computeTangents() {
  6046. const index = this.index;
  6047. const attributes = this.attributes;
  6048. // based on http://www.terathon.com/code/tangent.html
  6049. // (per vertex tangents)
  6050. if ( index === null ||
  6051. attributes.position === undefined ||
  6052. attributes.normal === undefined ||
  6053. attributes.uv === undefined ) {
  6054. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6055. return;
  6056. }
  6057. const indices = index.array;
  6058. const positions = attributes.position.array;
  6059. const normals = attributes.normal.array;
  6060. const uvs = attributes.uv.array;
  6061. const nVertices = positions.length / 3;
  6062. if ( this.hasAttribute( 'tangent' ) === false ) {
  6063. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6064. }
  6065. const tangents = this.getAttribute( 'tangent' ).array;
  6066. const tan1 = [], tan2 = [];
  6067. for ( let i = 0; i < nVertices; i ++ ) {
  6068. tan1[ i ] = new Vector3();
  6069. tan2[ i ] = new Vector3();
  6070. }
  6071. const vA = new Vector3(),
  6072. vB = new Vector3(),
  6073. vC = new Vector3(),
  6074. uvA = new Vector2(),
  6075. uvB = new Vector2(),
  6076. uvC = new Vector2(),
  6077. sdir = new Vector3(),
  6078. tdir = new Vector3();
  6079. function handleTriangle( a, b, c ) {
  6080. vA.fromArray( positions, a * 3 );
  6081. vB.fromArray( positions, b * 3 );
  6082. vC.fromArray( positions, c * 3 );
  6083. uvA.fromArray( uvs, a * 2 );
  6084. uvB.fromArray( uvs, b * 2 );
  6085. uvC.fromArray( uvs, c * 2 );
  6086. vB.sub( vA );
  6087. vC.sub( vA );
  6088. uvB.sub( uvA );
  6089. uvC.sub( uvA );
  6090. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6091. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6092. if ( ! isFinite( r ) ) return;
  6093. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6094. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6095. tan1[ a ].add( sdir );
  6096. tan1[ b ].add( sdir );
  6097. tan1[ c ].add( sdir );
  6098. tan2[ a ].add( tdir );
  6099. tan2[ b ].add( tdir );
  6100. tan2[ c ].add( tdir );
  6101. }
  6102. let groups = this.groups;
  6103. if ( groups.length === 0 ) {
  6104. groups = [ {
  6105. start: 0,
  6106. count: indices.length
  6107. } ];
  6108. }
  6109. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6110. const group = groups[ i ];
  6111. const start = group.start;
  6112. const count = group.count;
  6113. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6114. handleTriangle(
  6115. indices[ j + 0 ],
  6116. indices[ j + 1 ],
  6117. indices[ j + 2 ]
  6118. );
  6119. }
  6120. }
  6121. const tmp = new Vector3(), tmp2 = new Vector3();
  6122. const n = new Vector3(), n2 = new Vector3();
  6123. function handleVertex( v ) {
  6124. n.fromArray( normals, v * 3 );
  6125. n2.copy( n );
  6126. const t = tan1[ v ];
  6127. // Gram-Schmidt orthogonalize
  6128. tmp.copy( t );
  6129. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6130. // Calculate handedness
  6131. tmp2.crossVectors( n2, t );
  6132. const test = tmp2.dot( tan2[ v ] );
  6133. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6134. tangents[ v * 4 ] = tmp.x;
  6135. tangents[ v * 4 + 1 ] = tmp.y;
  6136. tangents[ v * 4 + 2 ] = tmp.z;
  6137. tangents[ v * 4 + 3 ] = w;
  6138. }
  6139. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6140. const group = groups[ i ];
  6141. const start = group.start;
  6142. const count = group.count;
  6143. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6144. handleVertex( indices[ j + 0 ] );
  6145. handleVertex( indices[ j + 1 ] );
  6146. handleVertex( indices[ j + 2 ] );
  6147. }
  6148. }
  6149. }
  6150. computeVertexNormals() {
  6151. const index = this.index;
  6152. const positionAttribute = this.getAttribute( 'position' );
  6153. if ( positionAttribute !== undefined ) {
  6154. let normalAttribute = this.getAttribute( 'normal' );
  6155. if ( normalAttribute === undefined ) {
  6156. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6157. this.setAttribute( 'normal', normalAttribute );
  6158. } else {
  6159. // reset existing normals to zero
  6160. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6161. normalAttribute.setXYZ( i, 0, 0, 0 );
  6162. }
  6163. }
  6164. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6165. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6166. const cb = new Vector3(), ab = new Vector3();
  6167. // indexed elements
  6168. if ( index ) {
  6169. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6170. const vA = index.getX( i + 0 );
  6171. const vB = index.getX( i + 1 );
  6172. const vC = index.getX( i + 2 );
  6173. pA.fromBufferAttribute( positionAttribute, vA );
  6174. pB.fromBufferAttribute( positionAttribute, vB );
  6175. pC.fromBufferAttribute( positionAttribute, vC );
  6176. cb.subVectors( pC, pB );
  6177. ab.subVectors( pA, pB );
  6178. cb.cross( ab );
  6179. nA.fromBufferAttribute( normalAttribute, vA );
  6180. nB.fromBufferAttribute( normalAttribute, vB );
  6181. nC.fromBufferAttribute( normalAttribute, vC );
  6182. nA.add( cb );
  6183. nB.add( cb );
  6184. nC.add( cb );
  6185. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6186. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6187. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6188. }
  6189. } else {
  6190. // non-indexed elements (unconnected triangle soup)
  6191. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6192. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6193. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6194. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6195. cb.subVectors( pC, pB );
  6196. ab.subVectors( pA, pB );
  6197. cb.cross( ab );
  6198. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6199. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6200. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6201. }
  6202. }
  6203. this.normalizeNormals();
  6204. normalAttribute.needsUpdate = true;
  6205. }
  6206. }
  6207. // @deprecated since r144
  6208. merge() {
  6209. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6210. return this;
  6211. }
  6212. normalizeNormals() {
  6213. const normals = this.attributes.normal;
  6214. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6215. _vector$8.fromBufferAttribute( normals, i );
  6216. _vector$8.normalize();
  6217. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6218. }
  6219. }
  6220. toNonIndexed() {
  6221. function convertBufferAttribute( attribute, indices ) {
  6222. const array = attribute.array;
  6223. const itemSize = attribute.itemSize;
  6224. const normalized = attribute.normalized;
  6225. const array2 = new array.constructor( indices.length * itemSize );
  6226. let index = 0, index2 = 0;
  6227. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6228. if ( attribute.isInterleavedBufferAttribute ) {
  6229. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6230. } else {
  6231. index = indices[ i ] * itemSize;
  6232. }
  6233. for ( let j = 0; j < itemSize; j ++ ) {
  6234. array2[ index2 ++ ] = array[ index ++ ];
  6235. }
  6236. }
  6237. return new BufferAttribute( array2, itemSize, normalized );
  6238. }
  6239. //
  6240. if ( this.index === null ) {
  6241. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6242. return this;
  6243. }
  6244. const geometry2 = new BufferGeometry();
  6245. const indices = this.index.array;
  6246. const attributes = this.attributes;
  6247. // attributes
  6248. for ( const name in attributes ) {
  6249. const attribute = attributes[ name ];
  6250. const newAttribute = convertBufferAttribute( attribute, indices );
  6251. geometry2.setAttribute( name, newAttribute );
  6252. }
  6253. // morph attributes
  6254. const morphAttributes = this.morphAttributes;
  6255. for ( const name in morphAttributes ) {
  6256. const morphArray = [];
  6257. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6258. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6259. const attribute = morphAttribute[ i ];
  6260. const newAttribute = convertBufferAttribute( attribute, indices );
  6261. morphArray.push( newAttribute );
  6262. }
  6263. geometry2.morphAttributes[ name ] = morphArray;
  6264. }
  6265. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6266. // groups
  6267. const groups = this.groups;
  6268. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6269. const group = groups[ i ];
  6270. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6271. }
  6272. return geometry2;
  6273. }
  6274. toJSON() {
  6275. const data = {
  6276. metadata: {
  6277. version: 4.5,
  6278. type: 'BufferGeometry',
  6279. generator: 'BufferGeometry.toJSON'
  6280. }
  6281. };
  6282. // standard BufferGeometry serialization
  6283. data.uuid = this.uuid;
  6284. data.type = this.type;
  6285. if ( this.name !== '' ) data.name = this.name;
  6286. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6287. if ( this.parameters !== undefined ) {
  6288. const parameters = this.parameters;
  6289. for ( const key in parameters ) {
  6290. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6291. }
  6292. return data;
  6293. }
  6294. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6295. data.data = { attributes: {} };
  6296. const index = this.index;
  6297. if ( index !== null ) {
  6298. data.data.index = {
  6299. type: index.array.constructor.name,
  6300. array: Array.prototype.slice.call( index.array )
  6301. };
  6302. }
  6303. const attributes = this.attributes;
  6304. for ( const key in attributes ) {
  6305. const attribute = attributes[ key ];
  6306. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6307. }
  6308. const morphAttributes = {};
  6309. let hasMorphAttributes = false;
  6310. for ( const key in this.morphAttributes ) {
  6311. const attributeArray = this.morphAttributes[ key ];
  6312. const array = [];
  6313. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6314. const attribute = attributeArray[ i ];
  6315. array.push( attribute.toJSON( data.data ) );
  6316. }
  6317. if ( array.length > 0 ) {
  6318. morphAttributes[ key ] = array;
  6319. hasMorphAttributes = true;
  6320. }
  6321. }
  6322. if ( hasMorphAttributes ) {
  6323. data.data.morphAttributes = morphAttributes;
  6324. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6325. }
  6326. const groups = this.groups;
  6327. if ( groups.length > 0 ) {
  6328. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6329. }
  6330. const boundingSphere = this.boundingSphere;
  6331. if ( boundingSphere !== null ) {
  6332. data.data.boundingSphere = {
  6333. center: boundingSphere.center.toArray(),
  6334. radius: boundingSphere.radius
  6335. };
  6336. }
  6337. return data;
  6338. }
  6339. clone() {
  6340. return new this.constructor().copy( this );
  6341. }
  6342. copy( source ) {
  6343. // reset
  6344. this.index = null;
  6345. this.attributes = {};
  6346. this.morphAttributes = {};
  6347. this.groups = [];
  6348. this.boundingBox = null;
  6349. this.boundingSphere = null;
  6350. // used for storing cloned, shared data
  6351. const data = {};
  6352. // name
  6353. this.name = source.name;
  6354. // index
  6355. const index = source.index;
  6356. if ( index !== null ) {
  6357. this.setIndex( index.clone( data ) );
  6358. }
  6359. // attributes
  6360. const attributes = source.attributes;
  6361. for ( const name in attributes ) {
  6362. const attribute = attributes[ name ];
  6363. this.setAttribute( name, attribute.clone( data ) );
  6364. }
  6365. // morph attributes
  6366. const morphAttributes = source.morphAttributes;
  6367. for ( const name in morphAttributes ) {
  6368. const array = [];
  6369. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6370. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6371. array.push( morphAttribute[ i ].clone( data ) );
  6372. }
  6373. this.morphAttributes[ name ] = array;
  6374. }
  6375. this.morphTargetsRelative = source.morphTargetsRelative;
  6376. // groups
  6377. const groups = source.groups;
  6378. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6379. const group = groups[ i ];
  6380. this.addGroup( group.start, group.count, group.materialIndex );
  6381. }
  6382. // bounding box
  6383. const boundingBox = source.boundingBox;
  6384. if ( boundingBox !== null ) {
  6385. this.boundingBox = boundingBox.clone();
  6386. }
  6387. // bounding sphere
  6388. const boundingSphere = source.boundingSphere;
  6389. if ( boundingSphere !== null ) {
  6390. this.boundingSphere = boundingSphere.clone();
  6391. }
  6392. // draw range
  6393. this.drawRange.start = source.drawRange.start;
  6394. this.drawRange.count = source.drawRange.count;
  6395. // user data
  6396. this.userData = source.userData;
  6397. // geometry generator parameters
  6398. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6399. return this;
  6400. }
  6401. dispose() {
  6402. this.dispatchEvent( { type: 'dispose' } );
  6403. }
  6404. }
  6405. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6406. const _ray$2 = /*@__PURE__*/ new Ray();
  6407. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6408. const _vA$1 = /*@__PURE__*/ new Vector3();
  6409. const _vB$1 = /*@__PURE__*/ new Vector3();
  6410. const _vC$1 = /*@__PURE__*/ new Vector3();
  6411. const _tempA = /*@__PURE__*/ new Vector3();
  6412. const _tempB = /*@__PURE__*/ new Vector3();
  6413. const _tempC = /*@__PURE__*/ new Vector3();
  6414. const _morphA = /*@__PURE__*/ new Vector3();
  6415. const _morphB = /*@__PURE__*/ new Vector3();
  6416. const _morphC = /*@__PURE__*/ new Vector3();
  6417. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6418. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6419. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6420. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6421. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6422. class Mesh extends Object3D {
  6423. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6424. super();
  6425. this.isMesh = true;
  6426. this.type = 'Mesh';
  6427. this.geometry = geometry;
  6428. this.material = material;
  6429. this.updateMorphTargets();
  6430. }
  6431. copy( source, recursive ) {
  6432. super.copy( source, recursive );
  6433. if ( source.morphTargetInfluences !== undefined ) {
  6434. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6435. }
  6436. if ( source.morphTargetDictionary !== undefined ) {
  6437. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6438. }
  6439. this.material = source.material;
  6440. this.geometry = source.geometry;
  6441. return this;
  6442. }
  6443. updateMorphTargets() {
  6444. const geometry = this.geometry;
  6445. const morphAttributes = geometry.morphAttributes;
  6446. const keys = Object.keys( morphAttributes );
  6447. if ( keys.length > 0 ) {
  6448. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6449. if ( morphAttribute !== undefined ) {
  6450. this.morphTargetInfluences = [];
  6451. this.morphTargetDictionary = {};
  6452. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6453. const name = morphAttribute[ m ].name || String( m );
  6454. this.morphTargetInfluences.push( 0 );
  6455. this.morphTargetDictionary[ name ] = m;
  6456. }
  6457. }
  6458. }
  6459. }
  6460. raycast( raycaster, intersects ) {
  6461. const geometry = this.geometry;
  6462. const material = this.material;
  6463. const matrixWorld = this.matrixWorld;
  6464. if ( material === undefined ) return;
  6465. // Checking boundingSphere distance to ray
  6466. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6467. _sphere$3.copy( geometry.boundingSphere );
  6468. _sphere$3.applyMatrix4( matrixWorld );
  6469. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6470. //
  6471. _inverseMatrix$2.copy( matrixWorld ).invert();
  6472. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6473. // Check boundingBox before continuing
  6474. if ( geometry.boundingBox !== null ) {
  6475. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6476. }
  6477. let intersection;
  6478. const index = geometry.index;
  6479. const position = geometry.attributes.position;
  6480. const morphPosition = geometry.morphAttributes.position;
  6481. const morphTargetsRelative = geometry.morphTargetsRelative;
  6482. const uv = geometry.attributes.uv;
  6483. const uv2 = geometry.attributes.uv2;
  6484. const groups = geometry.groups;
  6485. const drawRange = geometry.drawRange;
  6486. if ( index !== null ) {
  6487. // indexed buffer geometry
  6488. if ( Array.isArray( material ) ) {
  6489. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6490. const group = groups[ i ];
  6491. const groupMaterial = material[ group.materialIndex ];
  6492. const start = Math.max( group.start, drawRange.start );
  6493. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6494. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6495. const a = index.getX( j );
  6496. const b = index.getX( j + 1 );
  6497. const c = index.getX( j + 2 );
  6498. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6499. if ( intersection ) {
  6500. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6501. intersection.face.materialIndex = group.materialIndex;
  6502. intersects.push( intersection );
  6503. }
  6504. }
  6505. }
  6506. } else {
  6507. const start = Math.max( 0, drawRange.start );
  6508. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6509. for ( let i = start, il = end; i < il; i += 3 ) {
  6510. const a = index.getX( i );
  6511. const b = index.getX( i + 1 );
  6512. const c = index.getX( i + 2 );
  6513. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6514. if ( intersection ) {
  6515. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6516. intersects.push( intersection );
  6517. }
  6518. }
  6519. }
  6520. } else if ( position !== undefined ) {
  6521. // non-indexed buffer geometry
  6522. if ( Array.isArray( material ) ) {
  6523. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6524. const group = groups[ i ];
  6525. const groupMaterial = material[ group.materialIndex ];
  6526. const start = Math.max( group.start, drawRange.start );
  6527. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6528. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6529. const a = j;
  6530. const b = j + 1;
  6531. const c = j + 2;
  6532. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6533. if ( intersection ) {
  6534. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6535. intersection.face.materialIndex = group.materialIndex;
  6536. intersects.push( intersection );
  6537. }
  6538. }
  6539. }
  6540. } else {
  6541. const start = Math.max( 0, drawRange.start );
  6542. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6543. for ( let i = start, il = end; i < il; i += 3 ) {
  6544. const a = i;
  6545. const b = i + 1;
  6546. const c = i + 2;
  6547. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6548. if ( intersection ) {
  6549. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6550. intersects.push( intersection );
  6551. }
  6552. }
  6553. }
  6554. }
  6555. }
  6556. }
  6557. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6558. let intersect;
  6559. if ( material.side === BackSide ) {
  6560. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6561. } else {
  6562. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6563. }
  6564. if ( intersect === null ) return null;
  6565. _intersectionPointWorld.copy( point );
  6566. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6567. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6568. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6569. return {
  6570. distance: distance,
  6571. point: _intersectionPointWorld.clone(),
  6572. object: object
  6573. };
  6574. }
  6575. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6576. _vA$1.fromBufferAttribute( position, a );
  6577. _vB$1.fromBufferAttribute( position, b );
  6578. _vC$1.fromBufferAttribute( position, c );
  6579. const morphInfluences = object.morphTargetInfluences;
  6580. if ( morphPosition && morphInfluences ) {
  6581. _morphA.set( 0, 0, 0 );
  6582. _morphB.set( 0, 0, 0 );
  6583. _morphC.set( 0, 0, 0 );
  6584. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6585. const influence = morphInfluences[ i ];
  6586. const morphAttribute = morphPosition[ i ];
  6587. if ( influence === 0 ) continue;
  6588. _tempA.fromBufferAttribute( morphAttribute, a );
  6589. _tempB.fromBufferAttribute( morphAttribute, b );
  6590. _tempC.fromBufferAttribute( morphAttribute, c );
  6591. if ( morphTargetsRelative ) {
  6592. _morphA.addScaledVector( _tempA, influence );
  6593. _morphB.addScaledVector( _tempB, influence );
  6594. _morphC.addScaledVector( _tempC, influence );
  6595. } else {
  6596. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6597. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6598. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6599. }
  6600. }
  6601. _vA$1.add( _morphA );
  6602. _vB$1.add( _morphB );
  6603. _vC$1.add( _morphC );
  6604. }
  6605. if ( object.isSkinnedMesh ) {
  6606. object.boneTransform( a, _vA$1 );
  6607. object.boneTransform( b, _vB$1 );
  6608. object.boneTransform( c, _vC$1 );
  6609. }
  6610. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6611. if ( intersection ) {
  6612. if ( uv ) {
  6613. _uvA$1.fromBufferAttribute( uv, a );
  6614. _uvB$1.fromBufferAttribute( uv, b );
  6615. _uvC$1.fromBufferAttribute( uv, c );
  6616. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6617. }
  6618. if ( uv2 ) {
  6619. _uvA$1.fromBufferAttribute( uv2, a );
  6620. _uvB$1.fromBufferAttribute( uv2, b );
  6621. _uvC$1.fromBufferAttribute( uv2, c );
  6622. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6623. }
  6624. const face = {
  6625. a: a,
  6626. b: b,
  6627. c: c,
  6628. normal: new Vector3(),
  6629. materialIndex: 0
  6630. };
  6631. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6632. intersection.face = face;
  6633. }
  6634. return intersection;
  6635. }
  6636. class BoxGeometry extends BufferGeometry {
  6637. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6638. super();
  6639. this.type = 'BoxGeometry';
  6640. this.parameters = {
  6641. width: width,
  6642. height: height,
  6643. depth: depth,
  6644. widthSegments: widthSegments,
  6645. heightSegments: heightSegments,
  6646. depthSegments: depthSegments
  6647. };
  6648. const scope = this;
  6649. // segments
  6650. widthSegments = Math.floor( widthSegments );
  6651. heightSegments = Math.floor( heightSegments );
  6652. depthSegments = Math.floor( depthSegments );
  6653. // buffers
  6654. const indices = [];
  6655. const vertices = [];
  6656. const normals = [];
  6657. const uvs = [];
  6658. // helper variables
  6659. let numberOfVertices = 0;
  6660. let groupStart = 0;
  6661. // build each side of the box geometry
  6662. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6663. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6664. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6665. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6666. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6667. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6668. // build geometry
  6669. this.setIndex( indices );
  6670. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6671. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6672. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6673. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6674. const segmentWidth = width / gridX;
  6675. const segmentHeight = height / gridY;
  6676. const widthHalf = width / 2;
  6677. const heightHalf = height / 2;
  6678. const depthHalf = depth / 2;
  6679. const gridX1 = gridX + 1;
  6680. const gridY1 = gridY + 1;
  6681. let vertexCounter = 0;
  6682. let groupCount = 0;
  6683. const vector = new Vector3();
  6684. // generate vertices, normals and uvs
  6685. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6686. const y = iy * segmentHeight - heightHalf;
  6687. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6688. const x = ix * segmentWidth - widthHalf;
  6689. // set values to correct vector component
  6690. vector[ u ] = x * udir;
  6691. vector[ v ] = y * vdir;
  6692. vector[ w ] = depthHalf;
  6693. // now apply vector to vertex buffer
  6694. vertices.push( vector.x, vector.y, vector.z );
  6695. // set values to correct vector component
  6696. vector[ u ] = 0;
  6697. vector[ v ] = 0;
  6698. vector[ w ] = depth > 0 ? 1 : - 1;
  6699. // now apply vector to normal buffer
  6700. normals.push( vector.x, vector.y, vector.z );
  6701. // uvs
  6702. uvs.push( ix / gridX );
  6703. uvs.push( 1 - ( iy / gridY ) );
  6704. // counters
  6705. vertexCounter += 1;
  6706. }
  6707. }
  6708. // indices
  6709. // 1. you need three indices to draw a single face
  6710. // 2. a single segment consists of two faces
  6711. // 3. so we need to generate six (2*3) indices per segment
  6712. for ( let iy = 0; iy < gridY; iy ++ ) {
  6713. for ( let ix = 0; ix < gridX; ix ++ ) {
  6714. const a = numberOfVertices + ix + gridX1 * iy;
  6715. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6716. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6717. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6718. // faces
  6719. indices.push( a, b, d );
  6720. indices.push( b, c, d );
  6721. // increase counter
  6722. groupCount += 6;
  6723. }
  6724. }
  6725. // add a group to the geometry. this will ensure multi material support
  6726. scope.addGroup( groupStart, groupCount, materialIndex );
  6727. // calculate new start value for groups
  6728. groupStart += groupCount;
  6729. // update total number of vertices
  6730. numberOfVertices += vertexCounter;
  6731. }
  6732. }
  6733. static fromJSON( data ) {
  6734. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6735. }
  6736. }
  6737. /**
  6738. * Uniform Utilities
  6739. */
  6740. function cloneUniforms( src ) {
  6741. const dst = {};
  6742. for ( const u in src ) {
  6743. dst[ u ] = {};
  6744. for ( const p in src[ u ] ) {
  6745. const property = src[ u ][ p ];
  6746. if ( property && ( property.isColor ||
  6747. property.isMatrix3 || property.isMatrix4 ||
  6748. property.isVector2 || property.isVector3 || property.isVector4 ||
  6749. property.isTexture || property.isQuaternion ) ) {
  6750. dst[ u ][ p ] = property.clone();
  6751. } else if ( Array.isArray( property ) ) {
  6752. dst[ u ][ p ] = property.slice();
  6753. } else {
  6754. dst[ u ][ p ] = property;
  6755. }
  6756. }
  6757. }
  6758. return dst;
  6759. }
  6760. function mergeUniforms( uniforms ) {
  6761. const merged = {};
  6762. for ( let u = 0; u < uniforms.length; u ++ ) {
  6763. const tmp = cloneUniforms( uniforms[ u ] );
  6764. for ( const p in tmp ) {
  6765. merged[ p ] = tmp[ p ];
  6766. }
  6767. }
  6768. return merged;
  6769. }
  6770. function cloneUniformsGroups( src ) {
  6771. const dst = [];
  6772. for ( let u = 0; u < src.length; u ++ ) {
  6773. dst.push( src[ u ].clone() );
  6774. }
  6775. return dst;
  6776. }
  6777. // Legacy
  6778. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6779. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6780. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6781. class ShaderMaterial extends Material {
  6782. constructor( parameters ) {
  6783. super();
  6784. this.isShaderMaterial = true;
  6785. this.type = 'ShaderMaterial';
  6786. this.defines = {};
  6787. this.uniforms = {};
  6788. this.uniformsGroups = [];
  6789. this.vertexShader = default_vertex;
  6790. this.fragmentShader = default_fragment;
  6791. this.linewidth = 1;
  6792. this.wireframe = false;
  6793. this.wireframeLinewidth = 1;
  6794. this.fog = false; // set to use scene fog
  6795. this.lights = false; // set to use scene lights
  6796. this.clipping = false; // set to use user-defined clipping planes
  6797. this.extensions = {
  6798. derivatives: false, // set to use derivatives
  6799. fragDepth: false, // set to use fragment depth values
  6800. drawBuffers: false, // set to use draw buffers
  6801. shaderTextureLOD: false // set to use shader texture LOD
  6802. };
  6803. // When rendered geometry doesn't include these attributes but the material does,
  6804. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6805. this.defaultAttributeValues = {
  6806. 'color': [ 1, 1, 1 ],
  6807. 'uv': [ 0, 0 ],
  6808. 'uv2': [ 0, 0 ]
  6809. };
  6810. this.index0AttributeName = undefined;
  6811. this.uniformsNeedUpdate = false;
  6812. this.glslVersion = null;
  6813. if ( parameters !== undefined ) {
  6814. this.setValues( parameters );
  6815. }
  6816. }
  6817. copy( source ) {
  6818. super.copy( source );
  6819. this.fragmentShader = source.fragmentShader;
  6820. this.vertexShader = source.vertexShader;
  6821. this.uniforms = cloneUniforms( source.uniforms );
  6822. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6823. this.defines = Object.assign( {}, source.defines );
  6824. this.wireframe = source.wireframe;
  6825. this.wireframeLinewidth = source.wireframeLinewidth;
  6826. this.fog = source.fog;
  6827. this.lights = source.lights;
  6828. this.clipping = source.clipping;
  6829. this.extensions = Object.assign( {}, source.extensions );
  6830. this.glslVersion = source.glslVersion;
  6831. return this;
  6832. }
  6833. toJSON( meta ) {
  6834. const data = super.toJSON( meta );
  6835. data.glslVersion = this.glslVersion;
  6836. data.uniforms = {};
  6837. for ( const name in this.uniforms ) {
  6838. const uniform = this.uniforms[ name ];
  6839. const value = uniform.value;
  6840. if ( value && value.isTexture ) {
  6841. data.uniforms[ name ] = {
  6842. type: 't',
  6843. value: value.toJSON( meta ).uuid
  6844. };
  6845. } else if ( value && value.isColor ) {
  6846. data.uniforms[ name ] = {
  6847. type: 'c',
  6848. value: value.getHex()
  6849. };
  6850. } else if ( value && value.isVector2 ) {
  6851. data.uniforms[ name ] = {
  6852. type: 'v2',
  6853. value: value.toArray()
  6854. };
  6855. } else if ( value && value.isVector3 ) {
  6856. data.uniforms[ name ] = {
  6857. type: 'v3',
  6858. value: value.toArray()
  6859. };
  6860. } else if ( value && value.isVector4 ) {
  6861. data.uniforms[ name ] = {
  6862. type: 'v4',
  6863. value: value.toArray()
  6864. };
  6865. } else if ( value && value.isMatrix3 ) {
  6866. data.uniforms[ name ] = {
  6867. type: 'm3',
  6868. value: value.toArray()
  6869. };
  6870. } else if ( value && value.isMatrix4 ) {
  6871. data.uniforms[ name ] = {
  6872. type: 'm4',
  6873. value: value.toArray()
  6874. };
  6875. } else {
  6876. data.uniforms[ name ] = {
  6877. value: value
  6878. };
  6879. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6880. }
  6881. }
  6882. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6883. data.vertexShader = this.vertexShader;
  6884. data.fragmentShader = this.fragmentShader;
  6885. const extensions = {};
  6886. for ( const key in this.extensions ) {
  6887. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6888. }
  6889. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6890. return data;
  6891. }
  6892. }
  6893. class Camera extends Object3D {
  6894. constructor() {
  6895. super();
  6896. this.isCamera = true;
  6897. this.type = 'Camera';
  6898. this.matrixWorldInverse = new Matrix4();
  6899. this.projectionMatrix = new Matrix4();
  6900. this.projectionMatrixInverse = new Matrix4();
  6901. }
  6902. copy( source, recursive ) {
  6903. super.copy( source, recursive );
  6904. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6905. this.projectionMatrix.copy( source.projectionMatrix );
  6906. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6907. return this;
  6908. }
  6909. getWorldDirection( target ) {
  6910. this.updateWorldMatrix( true, false );
  6911. const e = this.matrixWorld.elements;
  6912. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6913. }
  6914. updateMatrixWorld( force ) {
  6915. super.updateMatrixWorld( force );
  6916. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6917. }
  6918. updateWorldMatrix( updateParents, updateChildren ) {
  6919. super.updateWorldMatrix( updateParents, updateChildren );
  6920. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6921. }
  6922. clone() {
  6923. return new this.constructor().copy( this );
  6924. }
  6925. }
  6926. class PerspectiveCamera extends Camera {
  6927. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6928. super();
  6929. this.isPerspectiveCamera = true;
  6930. this.type = 'PerspectiveCamera';
  6931. this.fov = fov;
  6932. this.zoom = 1;
  6933. this.near = near;
  6934. this.far = far;
  6935. this.focus = 10;
  6936. this.aspect = aspect;
  6937. this.view = null;
  6938. this.filmGauge = 35; // width of the film (default in millimeters)
  6939. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6940. this.updateProjectionMatrix();
  6941. }
  6942. copy( source, recursive ) {
  6943. super.copy( source, recursive );
  6944. this.fov = source.fov;
  6945. this.zoom = source.zoom;
  6946. this.near = source.near;
  6947. this.far = source.far;
  6948. this.focus = source.focus;
  6949. this.aspect = source.aspect;
  6950. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6951. this.filmGauge = source.filmGauge;
  6952. this.filmOffset = source.filmOffset;
  6953. return this;
  6954. }
  6955. /**
  6956. * Sets the FOV by focal length in respect to the current .filmGauge.
  6957. *
  6958. * The default film gauge is 35, so that the focal length can be specified for
  6959. * a 35mm (full frame) camera.
  6960. *
  6961. * Values for focal length and film gauge must have the same unit.
  6962. */
  6963. setFocalLength( focalLength ) {
  6964. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6965. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6966. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6967. this.updateProjectionMatrix();
  6968. }
  6969. /**
  6970. * Calculates the focal length from the current .fov and .filmGauge.
  6971. */
  6972. getFocalLength() {
  6973. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6974. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6975. }
  6976. getEffectiveFOV() {
  6977. return RAD2DEG * 2 * Math.atan(
  6978. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6979. }
  6980. getFilmWidth() {
  6981. // film not completely covered in portrait format (aspect < 1)
  6982. return this.filmGauge * Math.min( this.aspect, 1 );
  6983. }
  6984. getFilmHeight() {
  6985. // film not completely covered in landscape format (aspect > 1)
  6986. return this.filmGauge / Math.max( this.aspect, 1 );
  6987. }
  6988. /**
  6989. * Sets an offset in a larger frustum. This is useful for multi-window or
  6990. * multi-monitor/multi-machine setups.
  6991. *
  6992. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6993. * the monitors are in grid like this
  6994. *
  6995. * +---+---+---+
  6996. * | A | B | C |
  6997. * +---+---+---+
  6998. * | D | E | F |
  6999. * +---+---+---+
  7000. *
  7001. * then for each monitor you would call it like this
  7002. *
  7003. * const w = 1920;
  7004. * const h = 1080;
  7005. * const fullWidth = w * 3;
  7006. * const fullHeight = h * 2;
  7007. *
  7008. * --A--
  7009. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7010. * --B--
  7011. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7012. * --C--
  7013. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7014. * --D--
  7015. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7016. * --E--
  7017. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7018. * --F--
  7019. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7020. *
  7021. * Note there is no reason monitors have to be the same size or in a grid.
  7022. */
  7023. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7024. this.aspect = fullWidth / fullHeight;
  7025. if ( this.view === null ) {
  7026. this.view = {
  7027. enabled: true,
  7028. fullWidth: 1,
  7029. fullHeight: 1,
  7030. offsetX: 0,
  7031. offsetY: 0,
  7032. width: 1,
  7033. height: 1
  7034. };
  7035. }
  7036. this.view.enabled = true;
  7037. this.view.fullWidth = fullWidth;
  7038. this.view.fullHeight = fullHeight;
  7039. this.view.offsetX = x;
  7040. this.view.offsetY = y;
  7041. this.view.width = width;
  7042. this.view.height = height;
  7043. this.updateProjectionMatrix();
  7044. }
  7045. clearViewOffset() {
  7046. if ( this.view !== null ) {
  7047. this.view.enabled = false;
  7048. }
  7049. this.updateProjectionMatrix();
  7050. }
  7051. updateProjectionMatrix() {
  7052. const near = this.near;
  7053. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7054. let height = 2 * top;
  7055. let width = this.aspect * height;
  7056. let left = - 0.5 * width;
  7057. const view = this.view;
  7058. if ( this.view !== null && this.view.enabled ) {
  7059. const fullWidth = view.fullWidth,
  7060. fullHeight = view.fullHeight;
  7061. left += view.offsetX * width / fullWidth;
  7062. top -= view.offsetY * height / fullHeight;
  7063. width *= view.width / fullWidth;
  7064. height *= view.height / fullHeight;
  7065. }
  7066. const skew = this.filmOffset;
  7067. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7068. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7069. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7070. }
  7071. toJSON( meta ) {
  7072. const data = super.toJSON( meta );
  7073. data.object.fov = this.fov;
  7074. data.object.zoom = this.zoom;
  7075. data.object.near = this.near;
  7076. data.object.far = this.far;
  7077. data.object.focus = this.focus;
  7078. data.object.aspect = this.aspect;
  7079. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7080. data.object.filmGauge = this.filmGauge;
  7081. data.object.filmOffset = this.filmOffset;
  7082. return data;
  7083. }
  7084. }
  7085. const fov = 90, aspect = 1;
  7086. class CubeCamera extends Object3D {
  7087. constructor( near, far, renderTarget ) {
  7088. super();
  7089. this.type = 'CubeCamera';
  7090. this.renderTarget = renderTarget;
  7091. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7092. cameraPX.layers = this.layers;
  7093. cameraPX.up.set( 0, - 1, 0 );
  7094. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7095. this.add( cameraPX );
  7096. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7097. cameraNX.layers = this.layers;
  7098. cameraNX.up.set( 0, - 1, 0 );
  7099. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7100. this.add( cameraNX );
  7101. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7102. cameraPY.layers = this.layers;
  7103. cameraPY.up.set( 0, 0, 1 );
  7104. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7105. this.add( cameraPY );
  7106. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7107. cameraNY.layers = this.layers;
  7108. cameraNY.up.set( 0, 0, - 1 );
  7109. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7110. this.add( cameraNY );
  7111. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7112. cameraPZ.layers = this.layers;
  7113. cameraPZ.up.set( 0, - 1, 0 );
  7114. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7115. this.add( cameraPZ );
  7116. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7117. cameraNZ.layers = this.layers;
  7118. cameraNZ.up.set( 0, - 1, 0 );
  7119. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7120. this.add( cameraNZ );
  7121. }
  7122. update( renderer, scene ) {
  7123. if ( this.parent === null ) this.updateMatrixWorld();
  7124. const renderTarget = this.renderTarget;
  7125. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7126. const currentRenderTarget = renderer.getRenderTarget();
  7127. const currentToneMapping = renderer.toneMapping;
  7128. const currentXrEnabled = renderer.xr.enabled;
  7129. renderer.toneMapping = NoToneMapping;
  7130. renderer.xr.enabled = false;
  7131. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7132. renderTarget.texture.generateMipmaps = false;
  7133. renderer.setRenderTarget( renderTarget, 0 );
  7134. renderer.render( scene, cameraPX );
  7135. renderer.setRenderTarget( renderTarget, 1 );
  7136. renderer.render( scene, cameraNX );
  7137. renderer.setRenderTarget( renderTarget, 2 );
  7138. renderer.render( scene, cameraPY );
  7139. renderer.setRenderTarget( renderTarget, 3 );
  7140. renderer.render( scene, cameraNY );
  7141. renderer.setRenderTarget( renderTarget, 4 );
  7142. renderer.render( scene, cameraPZ );
  7143. renderTarget.texture.generateMipmaps = generateMipmaps;
  7144. renderer.setRenderTarget( renderTarget, 5 );
  7145. renderer.render( scene, cameraNZ );
  7146. renderer.setRenderTarget( currentRenderTarget );
  7147. renderer.toneMapping = currentToneMapping;
  7148. renderer.xr.enabled = currentXrEnabled;
  7149. renderTarget.texture.needsPMREMUpdate = true;
  7150. }
  7151. }
  7152. class CubeTexture extends Texture {
  7153. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7154. images = images !== undefined ? images : [];
  7155. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7156. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7157. this.isCubeTexture = true;
  7158. this.flipY = false;
  7159. }
  7160. get images() {
  7161. return this.image;
  7162. }
  7163. set images( value ) {
  7164. this.image = value;
  7165. }
  7166. }
  7167. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7168. constructor( size, options = {} ) {
  7169. super( size, size, options );
  7170. this.isWebGLCubeRenderTarget = true;
  7171. const image = { width: size, height: size, depth: 1 };
  7172. const images = [ image, image, image, image, image, image ];
  7173. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7174. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7175. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7176. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7177. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7178. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7179. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7180. this.texture.isRenderTargetTexture = true;
  7181. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7182. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7183. }
  7184. fromEquirectangularTexture( renderer, texture ) {
  7185. this.texture.type = texture.type;
  7186. this.texture.encoding = texture.encoding;
  7187. this.texture.generateMipmaps = texture.generateMipmaps;
  7188. this.texture.minFilter = texture.minFilter;
  7189. this.texture.magFilter = texture.magFilter;
  7190. const shader = {
  7191. uniforms: {
  7192. tEquirect: { value: null },
  7193. },
  7194. vertexShader: /* glsl */`
  7195. varying vec3 vWorldDirection;
  7196. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7197. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7198. }
  7199. void main() {
  7200. vWorldDirection = transformDirection( position, modelMatrix );
  7201. #include <begin_vertex>
  7202. #include <project_vertex>
  7203. }
  7204. `,
  7205. fragmentShader: /* glsl */`
  7206. uniform sampler2D tEquirect;
  7207. varying vec3 vWorldDirection;
  7208. #include <common>
  7209. void main() {
  7210. vec3 direction = normalize( vWorldDirection );
  7211. vec2 sampleUV = equirectUv( direction );
  7212. gl_FragColor = texture2D( tEquirect, sampleUV );
  7213. }
  7214. `
  7215. };
  7216. const geometry = new BoxGeometry( 5, 5, 5 );
  7217. const material = new ShaderMaterial( {
  7218. name: 'CubemapFromEquirect',
  7219. uniforms: cloneUniforms( shader.uniforms ),
  7220. vertexShader: shader.vertexShader,
  7221. fragmentShader: shader.fragmentShader,
  7222. side: BackSide,
  7223. blending: NoBlending
  7224. } );
  7225. material.uniforms.tEquirect.value = texture;
  7226. const mesh = new Mesh( geometry, material );
  7227. const currentMinFilter = texture.minFilter;
  7228. // Avoid blurred poles
  7229. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7230. const camera = new CubeCamera( 1, 10, this );
  7231. camera.update( renderer, mesh );
  7232. texture.minFilter = currentMinFilter;
  7233. mesh.geometry.dispose();
  7234. mesh.material.dispose();
  7235. return this;
  7236. }
  7237. clear( renderer, color, depth, stencil ) {
  7238. const currentRenderTarget = renderer.getRenderTarget();
  7239. for ( let i = 0; i < 6; i ++ ) {
  7240. renderer.setRenderTarget( this, i );
  7241. renderer.clear( color, depth, stencil );
  7242. }
  7243. renderer.setRenderTarget( currentRenderTarget );
  7244. }
  7245. }
  7246. const _vector1 = /*@__PURE__*/ new Vector3();
  7247. const _vector2 = /*@__PURE__*/ new Vector3();
  7248. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7249. class Plane {
  7250. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7251. this.isPlane = true;
  7252. // normal is assumed to be normalized
  7253. this.normal = normal;
  7254. this.constant = constant;
  7255. }
  7256. set( normal, constant ) {
  7257. this.normal.copy( normal );
  7258. this.constant = constant;
  7259. return this;
  7260. }
  7261. setComponents( x, y, z, w ) {
  7262. this.normal.set( x, y, z );
  7263. this.constant = w;
  7264. return this;
  7265. }
  7266. setFromNormalAndCoplanarPoint( normal, point ) {
  7267. this.normal.copy( normal );
  7268. this.constant = - point.dot( this.normal );
  7269. return this;
  7270. }
  7271. setFromCoplanarPoints( a, b, c ) {
  7272. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7273. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7274. this.setFromNormalAndCoplanarPoint( normal, a );
  7275. return this;
  7276. }
  7277. copy( plane ) {
  7278. this.normal.copy( plane.normal );
  7279. this.constant = plane.constant;
  7280. return this;
  7281. }
  7282. normalize() {
  7283. // Note: will lead to a divide by zero if the plane is invalid.
  7284. const inverseNormalLength = 1.0 / this.normal.length();
  7285. this.normal.multiplyScalar( inverseNormalLength );
  7286. this.constant *= inverseNormalLength;
  7287. return this;
  7288. }
  7289. negate() {
  7290. this.constant *= - 1;
  7291. this.normal.negate();
  7292. return this;
  7293. }
  7294. distanceToPoint( point ) {
  7295. return this.normal.dot( point ) + this.constant;
  7296. }
  7297. distanceToSphere( sphere ) {
  7298. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7299. }
  7300. projectPoint( point, target ) {
  7301. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7302. }
  7303. intersectLine( line, target ) {
  7304. const direction = line.delta( _vector1 );
  7305. const denominator = this.normal.dot( direction );
  7306. if ( denominator === 0 ) {
  7307. // line is coplanar, return origin
  7308. if ( this.distanceToPoint( line.start ) === 0 ) {
  7309. return target.copy( line.start );
  7310. }
  7311. // Unsure if this is the correct method to handle this case.
  7312. return null;
  7313. }
  7314. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7315. if ( t < 0 || t > 1 ) {
  7316. return null;
  7317. }
  7318. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7319. }
  7320. intersectsLine( line ) {
  7321. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7322. const startSign = this.distanceToPoint( line.start );
  7323. const endSign = this.distanceToPoint( line.end );
  7324. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7325. }
  7326. intersectsBox( box ) {
  7327. return box.intersectsPlane( this );
  7328. }
  7329. intersectsSphere( sphere ) {
  7330. return sphere.intersectsPlane( this );
  7331. }
  7332. coplanarPoint( target ) {
  7333. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7334. }
  7335. applyMatrix4( matrix, optionalNormalMatrix ) {
  7336. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7337. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7338. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7339. this.constant = - referencePoint.dot( normal );
  7340. return this;
  7341. }
  7342. translate( offset ) {
  7343. this.constant -= offset.dot( this.normal );
  7344. return this;
  7345. }
  7346. equals( plane ) {
  7347. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7348. }
  7349. clone() {
  7350. return new this.constructor().copy( this );
  7351. }
  7352. }
  7353. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7354. const _vector$7 = /*@__PURE__*/ new Vector3();
  7355. class Frustum {
  7356. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7357. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7358. }
  7359. set( p0, p1, p2, p3, p4, p5 ) {
  7360. const planes = this.planes;
  7361. planes[ 0 ].copy( p0 );
  7362. planes[ 1 ].copy( p1 );
  7363. planes[ 2 ].copy( p2 );
  7364. planes[ 3 ].copy( p3 );
  7365. planes[ 4 ].copy( p4 );
  7366. planes[ 5 ].copy( p5 );
  7367. return this;
  7368. }
  7369. copy( frustum ) {
  7370. const planes = this.planes;
  7371. for ( let i = 0; i < 6; i ++ ) {
  7372. planes[ i ].copy( frustum.planes[ i ] );
  7373. }
  7374. return this;
  7375. }
  7376. setFromProjectionMatrix( m ) {
  7377. const planes = this.planes;
  7378. const me = m.elements;
  7379. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7380. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7381. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7382. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7383. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7384. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7385. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7386. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7387. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7388. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7389. return this;
  7390. }
  7391. intersectsObject( object ) {
  7392. const geometry = object.geometry;
  7393. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7394. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7395. return this.intersectsSphere( _sphere$2 );
  7396. }
  7397. intersectsSprite( sprite ) {
  7398. _sphere$2.center.set( 0, 0, 0 );
  7399. _sphere$2.radius = 0.7071067811865476;
  7400. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7401. return this.intersectsSphere( _sphere$2 );
  7402. }
  7403. intersectsSphere( sphere ) {
  7404. const planes = this.planes;
  7405. const center = sphere.center;
  7406. const negRadius = - sphere.radius;
  7407. for ( let i = 0; i < 6; i ++ ) {
  7408. const distance = planes[ i ].distanceToPoint( center );
  7409. if ( distance < negRadius ) {
  7410. return false;
  7411. }
  7412. }
  7413. return true;
  7414. }
  7415. intersectsBox( box ) {
  7416. const planes = this.planes;
  7417. for ( let i = 0; i < 6; i ++ ) {
  7418. const plane = planes[ i ];
  7419. // corner at max distance
  7420. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7421. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7422. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7423. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7424. return false;
  7425. }
  7426. }
  7427. return true;
  7428. }
  7429. containsPoint( point ) {
  7430. const planes = this.planes;
  7431. for ( let i = 0; i < 6; i ++ ) {
  7432. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7433. return false;
  7434. }
  7435. }
  7436. return true;
  7437. }
  7438. clone() {
  7439. return new this.constructor().copy( this );
  7440. }
  7441. }
  7442. function WebGLAnimation() {
  7443. let context = null;
  7444. let isAnimating = false;
  7445. let animationLoop = null;
  7446. let requestId = null;
  7447. function onAnimationFrame( time, frame ) {
  7448. animationLoop( time, frame );
  7449. requestId = context.requestAnimationFrame( onAnimationFrame );
  7450. }
  7451. return {
  7452. start: function () {
  7453. if ( isAnimating === true ) return;
  7454. if ( animationLoop === null ) return;
  7455. requestId = context.requestAnimationFrame( onAnimationFrame );
  7456. isAnimating = true;
  7457. },
  7458. stop: function () {
  7459. context.cancelAnimationFrame( requestId );
  7460. isAnimating = false;
  7461. },
  7462. setAnimationLoop: function ( callback ) {
  7463. animationLoop = callback;
  7464. },
  7465. setContext: function ( value ) {
  7466. context = value;
  7467. }
  7468. };
  7469. }
  7470. function WebGLAttributes( gl, capabilities ) {
  7471. const isWebGL2 = capabilities.isWebGL2;
  7472. const buffers = new WeakMap();
  7473. function createBuffer( attribute, bufferType ) {
  7474. const array = attribute.array;
  7475. const usage = attribute.usage;
  7476. const buffer = gl.createBuffer();
  7477. gl.bindBuffer( bufferType, buffer );
  7478. gl.bufferData( bufferType, array, usage );
  7479. attribute.onUploadCallback();
  7480. let type;
  7481. if ( array instanceof Float32Array ) {
  7482. type = 5126;
  7483. } else if ( array instanceof Uint16Array ) {
  7484. if ( attribute.isFloat16BufferAttribute ) {
  7485. if ( isWebGL2 ) {
  7486. type = 5131;
  7487. } else {
  7488. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7489. }
  7490. } else {
  7491. type = 5123;
  7492. }
  7493. } else if ( array instanceof Int16Array ) {
  7494. type = 5122;
  7495. } else if ( array instanceof Uint32Array ) {
  7496. type = 5125;
  7497. } else if ( array instanceof Int32Array ) {
  7498. type = 5124;
  7499. } else if ( array instanceof Int8Array ) {
  7500. type = 5120;
  7501. } else if ( array instanceof Uint8Array ) {
  7502. type = 5121;
  7503. } else if ( array instanceof Uint8ClampedArray ) {
  7504. type = 5121;
  7505. } else {
  7506. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7507. }
  7508. return {
  7509. buffer: buffer,
  7510. type: type,
  7511. bytesPerElement: array.BYTES_PER_ELEMENT,
  7512. version: attribute.version
  7513. };
  7514. }
  7515. function updateBuffer( buffer, attribute, bufferType ) {
  7516. const array = attribute.array;
  7517. const updateRange = attribute.updateRange;
  7518. gl.bindBuffer( bufferType, buffer );
  7519. if ( updateRange.count === - 1 ) {
  7520. // Not using update ranges
  7521. gl.bufferSubData( bufferType, 0, array );
  7522. } else {
  7523. if ( isWebGL2 ) {
  7524. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7525. array, updateRange.offset, updateRange.count );
  7526. } else {
  7527. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7528. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7529. }
  7530. updateRange.count = - 1; // reset range
  7531. }
  7532. }
  7533. //
  7534. function get( attribute ) {
  7535. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7536. return buffers.get( attribute );
  7537. }
  7538. function remove( attribute ) {
  7539. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7540. const data = buffers.get( attribute );
  7541. if ( data ) {
  7542. gl.deleteBuffer( data.buffer );
  7543. buffers.delete( attribute );
  7544. }
  7545. }
  7546. function update( attribute, bufferType ) {
  7547. if ( attribute.isGLBufferAttribute ) {
  7548. const cached = buffers.get( attribute );
  7549. if ( ! cached || cached.version < attribute.version ) {
  7550. buffers.set( attribute, {
  7551. buffer: attribute.buffer,
  7552. type: attribute.type,
  7553. bytesPerElement: attribute.elementSize,
  7554. version: attribute.version
  7555. } );
  7556. }
  7557. return;
  7558. }
  7559. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7560. const data = buffers.get( attribute );
  7561. if ( data === undefined ) {
  7562. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7563. } else if ( data.version < attribute.version ) {
  7564. updateBuffer( data.buffer, attribute, bufferType );
  7565. data.version = attribute.version;
  7566. }
  7567. }
  7568. return {
  7569. get: get,
  7570. remove: remove,
  7571. update: update
  7572. };
  7573. }
  7574. class PlaneGeometry extends BufferGeometry {
  7575. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7576. super();
  7577. this.type = 'PlaneGeometry';
  7578. this.parameters = {
  7579. width: width,
  7580. height: height,
  7581. widthSegments: widthSegments,
  7582. heightSegments: heightSegments
  7583. };
  7584. const width_half = width / 2;
  7585. const height_half = height / 2;
  7586. const gridX = Math.floor( widthSegments );
  7587. const gridY = Math.floor( heightSegments );
  7588. const gridX1 = gridX + 1;
  7589. const gridY1 = gridY + 1;
  7590. const segment_width = width / gridX;
  7591. const segment_height = height / gridY;
  7592. //
  7593. const indices = [];
  7594. const vertices = [];
  7595. const normals = [];
  7596. const uvs = [];
  7597. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7598. const y = iy * segment_height - height_half;
  7599. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7600. const x = ix * segment_width - width_half;
  7601. vertices.push( x, - y, 0 );
  7602. normals.push( 0, 0, 1 );
  7603. uvs.push( ix / gridX );
  7604. uvs.push( 1 - ( iy / gridY ) );
  7605. }
  7606. }
  7607. for ( let iy = 0; iy < gridY; iy ++ ) {
  7608. for ( let ix = 0; ix < gridX; ix ++ ) {
  7609. const a = ix + gridX1 * iy;
  7610. const b = ix + gridX1 * ( iy + 1 );
  7611. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7612. const d = ( ix + 1 ) + gridX1 * iy;
  7613. indices.push( a, b, d );
  7614. indices.push( b, c, d );
  7615. }
  7616. }
  7617. this.setIndex( indices );
  7618. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7619. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7620. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7621. }
  7622. static fromJSON( data ) {
  7623. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7624. }
  7625. }
  7626. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7627. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7628. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7629. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7630. 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";
  7631. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7632. var begin_vertex = "vec3 transformed = vec3( position );";
  7633. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7634. 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";
  7635. 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";
  7636. 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";
  7637. 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";
  7638. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7639. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7640. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7641. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7642. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7643. 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";
  7644. 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";
  7645. 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}";
  7646. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7647. 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";
  7648. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7649. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7650. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7651. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7652. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7653. 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}";
  7654. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7655. 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";
  7656. 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";
  7657. 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";
  7658. 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";
  7659. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7660. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7661. 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";
  7662. 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";
  7663. 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}";
  7664. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7665. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7666. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7667. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material )\t(0)";
  7668. 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";
  7669. 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";
  7670. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7671. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7672. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7673. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7674. 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";
  7675. 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}";
  7676. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\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 *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7677. 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";
  7678. 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";
  7679. 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";
  7680. 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";
  7681. 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";
  7682. 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";
  7683. 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";
  7684. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7685. 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";
  7686. 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";
  7687. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7688. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7689. 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";
  7690. 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";
  7691. 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";
  7692. 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";
  7693. 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;";
  7694. 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";
  7695. 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";
  7696. 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";
  7697. 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";
  7698. 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";
  7699. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7700. 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";
  7701. 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";
  7702. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7703. 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 );";
  7704. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7705. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7706. 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;";
  7707. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7708. 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";
  7709. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7710. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7711. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7712. 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";
  7713. var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( 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\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7714. 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}";
  7715. 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";
  7716. 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";
  7717. 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";
  7718. 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";
  7719. 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";
  7720. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7721. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7722. 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; }";
  7723. 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";
  7724. 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";
  7725. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7726. 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";
  7727. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7728. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7729. 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";
  7730. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7731. 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";
  7732. const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7733. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7734. 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}";
  7735. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7736. 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}";
  7737. 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}";
  7738. 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}";
  7739. 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}";
  7740. 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}";
  7741. 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}";
  7742. 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}";
  7743. 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}";
  7744. 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}";
  7745. 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}";
  7746. 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}";
  7747. 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}";
  7748. 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}";
  7749. 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}";
  7750. 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}";
  7751. 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}";
  7752. 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}";
  7753. 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}";
  7754. 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}";
  7755. 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}";
  7756. 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}";
  7757. 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}";
  7758. 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}";
  7759. 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}";
  7760. 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}";
  7761. 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}";
  7762. 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}";
  7763. 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}";
  7764. const ShaderChunk = {
  7765. alphamap_fragment: alphamap_fragment,
  7766. alphamap_pars_fragment: alphamap_pars_fragment,
  7767. alphatest_fragment: alphatest_fragment,
  7768. alphatest_pars_fragment: alphatest_pars_fragment,
  7769. aomap_fragment: aomap_fragment,
  7770. aomap_pars_fragment: aomap_pars_fragment,
  7771. begin_vertex: begin_vertex,
  7772. beginnormal_vertex: beginnormal_vertex,
  7773. bsdfs: bsdfs,
  7774. iridescence_fragment: iridescence_fragment,
  7775. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7776. clipping_planes_fragment: clipping_planes_fragment,
  7777. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7778. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7779. clipping_planes_vertex: clipping_planes_vertex,
  7780. color_fragment: color_fragment,
  7781. color_pars_fragment: color_pars_fragment,
  7782. color_pars_vertex: color_pars_vertex,
  7783. color_vertex: color_vertex,
  7784. common: common,
  7785. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7786. defaultnormal_vertex: defaultnormal_vertex,
  7787. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7788. displacementmap_vertex: displacementmap_vertex,
  7789. emissivemap_fragment: emissivemap_fragment,
  7790. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7791. encodings_fragment: encodings_fragment,
  7792. encodings_pars_fragment: encodings_pars_fragment,
  7793. envmap_fragment: envmap_fragment,
  7794. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7795. envmap_pars_fragment: envmap_pars_fragment,
  7796. envmap_pars_vertex: envmap_pars_vertex,
  7797. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7798. envmap_vertex: envmap_vertex,
  7799. fog_vertex: fog_vertex,
  7800. fog_pars_vertex: fog_pars_vertex,
  7801. fog_fragment: fog_fragment,
  7802. fog_pars_fragment: fog_pars_fragment,
  7803. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7804. lightmap_fragment: lightmap_fragment,
  7805. lightmap_pars_fragment: lightmap_pars_fragment,
  7806. lights_lambert_fragment: lights_lambert_fragment,
  7807. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7808. lights_pars_begin: lights_pars_begin,
  7809. lights_toon_fragment: lights_toon_fragment,
  7810. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7811. lights_phong_fragment: lights_phong_fragment,
  7812. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7813. lights_physical_fragment: lights_physical_fragment,
  7814. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7815. lights_fragment_begin: lights_fragment_begin,
  7816. lights_fragment_maps: lights_fragment_maps,
  7817. lights_fragment_end: lights_fragment_end,
  7818. logdepthbuf_fragment: logdepthbuf_fragment,
  7819. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7820. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7821. logdepthbuf_vertex: logdepthbuf_vertex,
  7822. map_fragment: map_fragment,
  7823. map_pars_fragment: map_pars_fragment,
  7824. map_particle_fragment: map_particle_fragment,
  7825. map_particle_pars_fragment: map_particle_pars_fragment,
  7826. metalnessmap_fragment: metalnessmap_fragment,
  7827. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7828. morphcolor_vertex: morphcolor_vertex,
  7829. morphnormal_vertex: morphnormal_vertex,
  7830. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7831. morphtarget_vertex: morphtarget_vertex,
  7832. normal_fragment_begin: normal_fragment_begin,
  7833. normal_fragment_maps: normal_fragment_maps,
  7834. normal_pars_fragment: normal_pars_fragment,
  7835. normal_pars_vertex: normal_pars_vertex,
  7836. normal_vertex: normal_vertex,
  7837. normalmap_pars_fragment: normalmap_pars_fragment,
  7838. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7839. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7840. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7841. iridescence_pars_fragment: iridescence_pars_fragment,
  7842. output_fragment: output_fragment,
  7843. packing: packing,
  7844. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7845. project_vertex: project_vertex,
  7846. dithering_fragment: dithering_fragment,
  7847. dithering_pars_fragment: dithering_pars_fragment,
  7848. roughnessmap_fragment: roughnessmap_fragment,
  7849. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7850. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7851. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7852. shadowmap_vertex: shadowmap_vertex,
  7853. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7854. skinbase_vertex: skinbase_vertex,
  7855. skinning_pars_vertex: skinning_pars_vertex,
  7856. skinning_vertex: skinning_vertex,
  7857. skinnormal_vertex: skinnormal_vertex,
  7858. specularmap_fragment: specularmap_fragment,
  7859. specularmap_pars_fragment: specularmap_pars_fragment,
  7860. tonemapping_fragment: tonemapping_fragment,
  7861. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7862. transmission_fragment: transmission_fragment,
  7863. transmission_pars_fragment: transmission_pars_fragment,
  7864. uv_pars_fragment: uv_pars_fragment,
  7865. uv_pars_vertex: uv_pars_vertex,
  7866. uv_vertex: uv_vertex,
  7867. uv2_pars_fragment: uv2_pars_fragment,
  7868. uv2_pars_vertex: uv2_pars_vertex,
  7869. uv2_vertex: uv2_vertex,
  7870. worldpos_vertex: worldpos_vertex,
  7871. background_vert: vertex$g,
  7872. background_frag: fragment$g,
  7873. cube_vert: vertex$f,
  7874. cube_frag: fragment$f,
  7875. depth_vert: vertex$e,
  7876. depth_frag: fragment$e,
  7877. distanceRGBA_vert: vertex$d,
  7878. distanceRGBA_frag: fragment$d,
  7879. equirect_vert: vertex$c,
  7880. equirect_frag: fragment$c,
  7881. linedashed_vert: vertex$b,
  7882. linedashed_frag: fragment$b,
  7883. meshbasic_vert: vertex$a,
  7884. meshbasic_frag: fragment$a,
  7885. meshlambert_vert: vertex$9,
  7886. meshlambert_frag: fragment$9,
  7887. meshmatcap_vert: vertex$8,
  7888. meshmatcap_frag: fragment$8,
  7889. meshnormal_vert: vertex$7,
  7890. meshnormal_frag: fragment$7,
  7891. meshphong_vert: vertex$6,
  7892. meshphong_frag: fragment$6,
  7893. meshphysical_vert: vertex$5,
  7894. meshphysical_frag: fragment$5,
  7895. meshtoon_vert: vertex$4,
  7896. meshtoon_frag: fragment$4,
  7897. points_vert: vertex$3,
  7898. points_frag: fragment$3,
  7899. shadow_vert: vertex$2,
  7900. shadow_frag: fragment$2,
  7901. sprite_vert: vertex$1,
  7902. sprite_frag: fragment$1
  7903. };
  7904. /**
  7905. * Uniforms library for shared webgl shaders
  7906. */
  7907. const UniformsLib = {
  7908. common: {
  7909. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7910. opacity: { value: 1.0 },
  7911. map: { value: null },
  7912. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7913. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7914. alphaMap: { value: null },
  7915. alphaTest: { value: 0 }
  7916. },
  7917. specularmap: {
  7918. specularMap: { value: null },
  7919. },
  7920. envmap: {
  7921. envMap: { value: null },
  7922. flipEnvMap: { value: - 1 },
  7923. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7924. ior: { value: 1.5 }, // physical
  7925. refractionRatio: { value: 0.98 } // basic, lambert, phong
  7926. },
  7927. aomap: {
  7928. aoMap: { value: null },
  7929. aoMapIntensity: { value: 1 }
  7930. },
  7931. lightmap: {
  7932. lightMap: { value: null },
  7933. lightMapIntensity: { value: 1 }
  7934. },
  7935. emissivemap: {
  7936. emissiveMap: { value: null }
  7937. },
  7938. bumpmap: {
  7939. bumpMap: { value: null },
  7940. bumpScale: { value: 1 }
  7941. },
  7942. normalmap: {
  7943. normalMap: { value: null },
  7944. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  7945. },
  7946. displacementmap: {
  7947. displacementMap: { value: null },
  7948. displacementScale: { value: 1 },
  7949. displacementBias: { value: 0 }
  7950. },
  7951. roughnessmap: {
  7952. roughnessMap: { value: null }
  7953. },
  7954. metalnessmap: {
  7955. metalnessMap: { value: null }
  7956. },
  7957. gradientmap: {
  7958. gradientMap: { value: null }
  7959. },
  7960. fog: {
  7961. fogDensity: { value: 0.00025 },
  7962. fogNear: { value: 1 },
  7963. fogFar: { value: 2000 },
  7964. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  7965. },
  7966. lights: {
  7967. ambientLightColor: { value: [] },
  7968. lightProbe: { value: [] },
  7969. directionalLights: { value: [], properties: {
  7970. direction: {},
  7971. color: {}
  7972. } },
  7973. directionalLightShadows: { value: [], properties: {
  7974. shadowBias: {},
  7975. shadowNormalBias: {},
  7976. shadowRadius: {},
  7977. shadowMapSize: {}
  7978. } },
  7979. directionalShadowMap: { value: [] },
  7980. directionalShadowMatrix: { value: [] },
  7981. spotLights: { value: [], properties: {
  7982. color: {},
  7983. position: {},
  7984. direction: {},
  7985. distance: {},
  7986. coneCos: {},
  7987. penumbraCos: {},
  7988. decay: {}
  7989. } },
  7990. spotLightShadows: { value: [], properties: {
  7991. shadowBias: {},
  7992. shadowNormalBias: {},
  7993. shadowRadius: {},
  7994. shadowMapSize: {}
  7995. } },
  7996. spotLightMap: { value: [] },
  7997. spotShadowMap: { value: [] },
  7998. spotLightMatrix: { value: [] },
  7999. pointLights: { value: [], properties: {
  8000. color: {},
  8001. position: {},
  8002. decay: {},
  8003. distance: {}
  8004. } },
  8005. pointLightShadows: { value: [], properties: {
  8006. shadowBias: {},
  8007. shadowNormalBias: {},
  8008. shadowRadius: {},
  8009. shadowMapSize: {},
  8010. shadowCameraNear: {},
  8011. shadowCameraFar: {}
  8012. } },
  8013. pointShadowMap: { value: [] },
  8014. pointShadowMatrix: { value: [] },
  8015. hemisphereLights: { value: [], properties: {
  8016. direction: {},
  8017. skyColor: {},
  8018. groundColor: {}
  8019. } },
  8020. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8021. rectAreaLights: { value: [], properties: {
  8022. color: {},
  8023. position: {},
  8024. width: {},
  8025. height: {}
  8026. } },
  8027. ltc_1: { value: null },
  8028. ltc_2: { value: null }
  8029. },
  8030. points: {
  8031. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8032. opacity: { value: 1.0 },
  8033. size: { value: 1.0 },
  8034. scale: { value: 1.0 },
  8035. map: { value: null },
  8036. alphaMap: { value: null },
  8037. alphaTest: { value: 0 },
  8038. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8039. },
  8040. sprite: {
  8041. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8042. opacity: { value: 1.0 },
  8043. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8044. rotation: { value: 0.0 },
  8045. map: { value: null },
  8046. alphaMap: { value: null },
  8047. alphaTest: { value: 0 },
  8048. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8049. }
  8050. };
  8051. const ShaderLib = {
  8052. basic: {
  8053. uniforms: /*@__PURE__*/ mergeUniforms( [
  8054. UniformsLib.common,
  8055. UniformsLib.specularmap,
  8056. UniformsLib.envmap,
  8057. UniformsLib.aomap,
  8058. UniformsLib.lightmap,
  8059. UniformsLib.fog
  8060. ] ),
  8061. vertexShader: ShaderChunk.meshbasic_vert,
  8062. fragmentShader: ShaderChunk.meshbasic_frag
  8063. },
  8064. lambert: {
  8065. uniforms: /*@__PURE__*/ mergeUniforms( [
  8066. UniformsLib.common,
  8067. UniformsLib.specularmap,
  8068. UniformsLib.envmap,
  8069. UniformsLib.aomap,
  8070. UniformsLib.lightmap,
  8071. UniformsLib.emissivemap,
  8072. UniformsLib.bumpmap,
  8073. UniformsLib.normalmap,
  8074. UniformsLib.displacementmap,
  8075. UniformsLib.fog,
  8076. UniformsLib.lights,
  8077. {
  8078. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8079. }
  8080. ] ),
  8081. vertexShader: ShaderChunk.meshlambert_vert,
  8082. fragmentShader: ShaderChunk.meshlambert_frag
  8083. },
  8084. phong: {
  8085. uniforms: /*@__PURE__*/ mergeUniforms( [
  8086. UniformsLib.common,
  8087. UniformsLib.specularmap,
  8088. UniformsLib.envmap,
  8089. UniformsLib.aomap,
  8090. UniformsLib.lightmap,
  8091. UniformsLib.emissivemap,
  8092. UniformsLib.bumpmap,
  8093. UniformsLib.normalmap,
  8094. UniformsLib.displacementmap,
  8095. UniformsLib.fog,
  8096. UniformsLib.lights,
  8097. {
  8098. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8099. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8100. shininess: { value: 30 }
  8101. }
  8102. ] ),
  8103. vertexShader: ShaderChunk.meshphong_vert,
  8104. fragmentShader: ShaderChunk.meshphong_frag
  8105. },
  8106. standard: {
  8107. uniforms: /*@__PURE__*/ mergeUniforms( [
  8108. UniformsLib.common,
  8109. UniformsLib.envmap,
  8110. UniformsLib.aomap,
  8111. UniformsLib.lightmap,
  8112. UniformsLib.emissivemap,
  8113. UniformsLib.bumpmap,
  8114. UniformsLib.normalmap,
  8115. UniformsLib.displacementmap,
  8116. UniformsLib.roughnessmap,
  8117. UniformsLib.metalnessmap,
  8118. UniformsLib.fog,
  8119. UniformsLib.lights,
  8120. {
  8121. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8122. roughness: { value: 1.0 },
  8123. metalness: { value: 0.0 },
  8124. envMapIntensity: { value: 1 } // temporary
  8125. }
  8126. ] ),
  8127. vertexShader: ShaderChunk.meshphysical_vert,
  8128. fragmentShader: ShaderChunk.meshphysical_frag
  8129. },
  8130. toon: {
  8131. uniforms: /*@__PURE__*/ mergeUniforms( [
  8132. UniformsLib.common,
  8133. UniformsLib.aomap,
  8134. UniformsLib.lightmap,
  8135. UniformsLib.emissivemap,
  8136. UniformsLib.bumpmap,
  8137. UniformsLib.normalmap,
  8138. UniformsLib.displacementmap,
  8139. UniformsLib.gradientmap,
  8140. UniformsLib.fog,
  8141. UniformsLib.lights,
  8142. {
  8143. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8144. }
  8145. ] ),
  8146. vertexShader: ShaderChunk.meshtoon_vert,
  8147. fragmentShader: ShaderChunk.meshtoon_frag
  8148. },
  8149. matcap: {
  8150. uniforms: /*@__PURE__*/ mergeUniforms( [
  8151. UniformsLib.common,
  8152. UniformsLib.bumpmap,
  8153. UniformsLib.normalmap,
  8154. UniformsLib.displacementmap,
  8155. UniformsLib.fog,
  8156. {
  8157. matcap: { value: null }
  8158. }
  8159. ] ),
  8160. vertexShader: ShaderChunk.meshmatcap_vert,
  8161. fragmentShader: ShaderChunk.meshmatcap_frag
  8162. },
  8163. points: {
  8164. uniforms: /*@__PURE__*/ mergeUniforms( [
  8165. UniformsLib.points,
  8166. UniformsLib.fog
  8167. ] ),
  8168. vertexShader: ShaderChunk.points_vert,
  8169. fragmentShader: ShaderChunk.points_frag
  8170. },
  8171. dashed: {
  8172. uniforms: /*@__PURE__*/ mergeUniforms( [
  8173. UniformsLib.common,
  8174. UniformsLib.fog,
  8175. {
  8176. scale: { value: 1 },
  8177. dashSize: { value: 1 },
  8178. totalSize: { value: 2 }
  8179. }
  8180. ] ),
  8181. vertexShader: ShaderChunk.linedashed_vert,
  8182. fragmentShader: ShaderChunk.linedashed_frag
  8183. },
  8184. depth: {
  8185. uniforms: /*@__PURE__*/ mergeUniforms( [
  8186. UniformsLib.common,
  8187. UniformsLib.displacementmap
  8188. ] ),
  8189. vertexShader: ShaderChunk.depth_vert,
  8190. fragmentShader: ShaderChunk.depth_frag
  8191. },
  8192. normal: {
  8193. uniforms: /*@__PURE__*/ mergeUniforms( [
  8194. UniformsLib.common,
  8195. UniformsLib.bumpmap,
  8196. UniformsLib.normalmap,
  8197. UniformsLib.displacementmap,
  8198. {
  8199. opacity: { value: 1.0 }
  8200. }
  8201. ] ),
  8202. vertexShader: ShaderChunk.meshnormal_vert,
  8203. fragmentShader: ShaderChunk.meshnormal_frag
  8204. },
  8205. sprite: {
  8206. uniforms: /*@__PURE__*/ mergeUniforms( [
  8207. UniformsLib.sprite,
  8208. UniformsLib.fog
  8209. ] ),
  8210. vertexShader: ShaderChunk.sprite_vert,
  8211. fragmentShader: ShaderChunk.sprite_frag
  8212. },
  8213. background: {
  8214. uniforms: {
  8215. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8216. t2D: { value: null },
  8217. },
  8218. vertexShader: ShaderChunk.background_vert,
  8219. fragmentShader: ShaderChunk.background_frag
  8220. },
  8221. cube: {
  8222. uniforms: /*@__PURE__*/ mergeUniforms( [
  8223. UniformsLib.envmap,
  8224. {
  8225. opacity: { value: 1.0 }
  8226. }
  8227. ] ),
  8228. vertexShader: ShaderChunk.cube_vert,
  8229. fragmentShader: ShaderChunk.cube_frag
  8230. },
  8231. equirect: {
  8232. uniforms: {
  8233. tEquirect: { value: null },
  8234. },
  8235. vertexShader: ShaderChunk.equirect_vert,
  8236. fragmentShader: ShaderChunk.equirect_frag
  8237. },
  8238. distanceRGBA: {
  8239. uniforms: /*@__PURE__*/ mergeUniforms( [
  8240. UniformsLib.common,
  8241. UniformsLib.displacementmap,
  8242. {
  8243. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8244. nearDistance: { value: 1 },
  8245. farDistance: { value: 1000 }
  8246. }
  8247. ] ),
  8248. vertexShader: ShaderChunk.distanceRGBA_vert,
  8249. fragmentShader: ShaderChunk.distanceRGBA_frag
  8250. },
  8251. shadow: {
  8252. uniforms: /*@__PURE__*/ mergeUniforms( [
  8253. UniformsLib.lights,
  8254. UniformsLib.fog,
  8255. {
  8256. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8257. opacity: { value: 1.0 }
  8258. },
  8259. ] ),
  8260. vertexShader: ShaderChunk.shadow_vert,
  8261. fragmentShader: ShaderChunk.shadow_frag
  8262. }
  8263. };
  8264. ShaderLib.physical = {
  8265. uniforms: /*@__PURE__*/ mergeUniforms( [
  8266. ShaderLib.standard.uniforms,
  8267. {
  8268. clearcoat: { value: 0 },
  8269. clearcoatMap: { value: null },
  8270. clearcoatRoughness: { value: 0 },
  8271. clearcoatRoughnessMap: { value: null },
  8272. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8273. clearcoatNormalMap: { value: null },
  8274. iridescence: { value: 0 },
  8275. iridescenceMap: { value: null },
  8276. iridescenceIOR: { value: 1.3 },
  8277. iridescenceThicknessMinimum: { value: 100 },
  8278. iridescenceThicknessMaximum: { value: 400 },
  8279. iridescenceThicknessMap: { value: null },
  8280. sheen: { value: 0 },
  8281. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8282. sheenColorMap: { value: null },
  8283. sheenRoughness: { value: 1 },
  8284. sheenRoughnessMap: { value: null },
  8285. transmission: { value: 0 },
  8286. transmissionMap: { value: null },
  8287. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8288. transmissionSamplerMap: { value: null },
  8289. thickness: { value: 0 },
  8290. thicknessMap: { value: null },
  8291. attenuationDistance: { value: 0 },
  8292. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8293. specularIntensity: { value: 1 },
  8294. specularIntensityMap: { value: null },
  8295. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8296. specularColorMap: { value: null },
  8297. }
  8298. ] ),
  8299. vertexShader: ShaderChunk.meshphysical_vert,
  8300. fragmentShader: ShaderChunk.meshphysical_frag
  8301. };
  8302. function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
  8303. const clearColor = new Color( 0x000000 );
  8304. let clearAlpha = alpha === true ? 0 : 1;
  8305. let planeMesh;
  8306. let boxMesh;
  8307. let currentBackground = null;
  8308. let currentBackgroundVersion = 0;
  8309. let currentTonemapping = null;
  8310. function render( renderList, scene ) {
  8311. let forceClear = false;
  8312. let background = scene.isScene === true ? scene.background : null;
  8313. if ( background && background.isTexture ) {
  8314. background = cubemaps.get( background );
  8315. }
  8316. // Ignore background in AR
  8317. // TODO: Reconsider this.
  8318. const xr = renderer.xr;
  8319. const session = xr.getSession && xr.getSession();
  8320. if ( session && session.environmentBlendMode === 'additive' ) {
  8321. background = null;
  8322. }
  8323. if ( background === null ) {
  8324. setClear( clearColor, clearAlpha );
  8325. } else if ( background && background.isColor ) {
  8326. setClear( background, 1 );
  8327. forceClear = true;
  8328. }
  8329. if ( renderer.autoClear || forceClear ) {
  8330. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8331. }
  8332. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8333. if ( boxMesh === undefined ) {
  8334. boxMesh = new Mesh(
  8335. new BoxGeometry( 1, 1, 1 ),
  8336. new ShaderMaterial( {
  8337. name: 'BackgroundCubeMaterial',
  8338. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8339. vertexShader: ShaderLib.cube.vertexShader,
  8340. fragmentShader: ShaderLib.cube.fragmentShader,
  8341. side: BackSide,
  8342. depthTest: false,
  8343. depthWrite: false,
  8344. fog: false
  8345. } )
  8346. );
  8347. boxMesh.geometry.deleteAttribute( 'normal' );
  8348. boxMesh.geometry.deleteAttribute( 'uv' );
  8349. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8350. this.matrixWorld.copyPosition( camera.matrixWorld );
  8351. };
  8352. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8353. Object.defineProperty( boxMesh.material, 'envMap', {
  8354. get: function () {
  8355. return this.uniforms.envMap.value;
  8356. }
  8357. } );
  8358. objects.update( boxMesh );
  8359. }
  8360. boxMesh.material.uniforms.envMap.value = background;
  8361. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8362. if ( currentBackground !== background ||
  8363. currentBackgroundVersion !== background.version ||
  8364. currentTonemapping !== renderer.toneMapping ) {
  8365. boxMesh.material.needsUpdate = true;
  8366. currentBackground = background;
  8367. currentBackgroundVersion = background.version;
  8368. currentTonemapping = renderer.toneMapping;
  8369. }
  8370. boxMesh.layers.enableAll();
  8371. // push to the pre-sorted opaque render list
  8372. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8373. } else if ( background && background.isTexture ) {
  8374. if ( planeMesh === undefined ) {
  8375. planeMesh = new Mesh(
  8376. new PlaneGeometry( 2, 2 ),
  8377. new ShaderMaterial( {
  8378. name: 'BackgroundMaterial',
  8379. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8380. vertexShader: ShaderLib.background.vertexShader,
  8381. fragmentShader: ShaderLib.background.fragmentShader,
  8382. side: FrontSide,
  8383. depthTest: false,
  8384. depthWrite: false,
  8385. fog: false
  8386. } )
  8387. );
  8388. planeMesh.geometry.deleteAttribute( 'normal' );
  8389. // add "map" material property so the renderer can evaluate it like for built-in materials
  8390. Object.defineProperty( planeMesh.material, 'map', {
  8391. get: function () {
  8392. return this.uniforms.t2D.value;
  8393. }
  8394. } );
  8395. objects.update( planeMesh );
  8396. }
  8397. planeMesh.material.uniforms.t2D.value = background;
  8398. if ( background.matrixAutoUpdate === true ) {
  8399. background.updateMatrix();
  8400. }
  8401. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8402. if ( currentBackground !== background ||
  8403. currentBackgroundVersion !== background.version ||
  8404. currentTonemapping !== renderer.toneMapping ) {
  8405. planeMesh.material.needsUpdate = true;
  8406. currentBackground = background;
  8407. currentBackgroundVersion = background.version;
  8408. currentTonemapping = renderer.toneMapping;
  8409. }
  8410. planeMesh.layers.enableAll();
  8411. // push to the pre-sorted opaque render list
  8412. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8413. }
  8414. }
  8415. function setClear( color, alpha ) {
  8416. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8417. }
  8418. return {
  8419. getClearColor: function () {
  8420. return clearColor;
  8421. },
  8422. setClearColor: function ( color, alpha = 1 ) {
  8423. clearColor.set( color );
  8424. clearAlpha = alpha;
  8425. setClear( clearColor, clearAlpha );
  8426. },
  8427. getClearAlpha: function () {
  8428. return clearAlpha;
  8429. },
  8430. setClearAlpha: function ( alpha ) {
  8431. clearAlpha = alpha;
  8432. setClear( clearColor, clearAlpha );
  8433. },
  8434. render: render
  8435. };
  8436. }
  8437. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8438. const maxVertexAttributes = gl.getParameter( 34921 );
  8439. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8440. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8441. const bindingStates = {};
  8442. const defaultState = createBindingState( null );
  8443. let currentState = defaultState;
  8444. let forceUpdate = false;
  8445. function setup( object, material, program, geometry, index ) {
  8446. let updateBuffers = false;
  8447. if ( vaoAvailable ) {
  8448. const state = getBindingState( geometry, program, material );
  8449. if ( currentState !== state ) {
  8450. currentState = state;
  8451. bindVertexArrayObject( currentState.object );
  8452. }
  8453. updateBuffers = needsUpdate( object, geometry, program, index );
  8454. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8455. } else {
  8456. const wireframe = ( material.wireframe === true );
  8457. if ( currentState.geometry !== geometry.id ||
  8458. currentState.program !== program.id ||
  8459. currentState.wireframe !== wireframe ) {
  8460. currentState.geometry = geometry.id;
  8461. currentState.program = program.id;
  8462. currentState.wireframe = wireframe;
  8463. updateBuffers = true;
  8464. }
  8465. }
  8466. if ( index !== null ) {
  8467. attributes.update( index, 34963 );
  8468. }
  8469. if ( updateBuffers || forceUpdate ) {
  8470. forceUpdate = false;
  8471. setupVertexAttributes( object, material, program, geometry );
  8472. if ( index !== null ) {
  8473. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8474. }
  8475. }
  8476. }
  8477. function createVertexArrayObject() {
  8478. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8479. return extension.createVertexArrayOES();
  8480. }
  8481. function bindVertexArrayObject( vao ) {
  8482. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8483. return extension.bindVertexArrayOES( vao );
  8484. }
  8485. function deleteVertexArrayObject( vao ) {
  8486. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8487. return extension.deleteVertexArrayOES( vao );
  8488. }
  8489. function getBindingState( geometry, program, material ) {
  8490. const wireframe = ( material.wireframe === true );
  8491. let programMap = bindingStates[ geometry.id ];
  8492. if ( programMap === undefined ) {
  8493. programMap = {};
  8494. bindingStates[ geometry.id ] = programMap;
  8495. }
  8496. let stateMap = programMap[ program.id ];
  8497. if ( stateMap === undefined ) {
  8498. stateMap = {};
  8499. programMap[ program.id ] = stateMap;
  8500. }
  8501. let state = stateMap[ wireframe ];
  8502. if ( state === undefined ) {
  8503. state = createBindingState( createVertexArrayObject() );
  8504. stateMap[ wireframe ] = state;
  8505. }
  8506. return state;
  8507. }
  8508. function createBindingState( vao ) {
  8509. const newAttributes = [];
  8510. const enabledAttributes = [];
  8511. const attributeDivisors = [];
  8512. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8513. newAttributes[ i ] = 0;
  8514. enabledAttributes[ i ] = 0;
  8515. attributeDivisors[ i ] = 0;
  8516. }
  8517. return {
  8518. // for backward compatibility on non-VAO support browser
  8519. geometry: null,
  8520. program: null,
  8521. wireframe: false,
  8522. newAttributes: newAttributes,
  8523. enabledAttributes: enabledAttributes,
  8524. attributeDivisors: attributeDivisors,
  8525. object: vao,
  8526. attributes: {},
  8527. index: null
  8528. };
  8529. }
  8530. function needsUpdate( object, geometry, program, index ) {
  8531. const cachedAttributes = currentState.attributes;
  8532. const geometryAttributes = geometry.attributes;
  8533. let attributesNum = 0;
  8534. const programAttributes = program.getAttributes();
  8535. for ( const name in programAttributes ) {
  8536. const programAttribute = programAttributes[ name ];
  8537. if ( programAttribute.location >= 0 ) {
  8538. const cachedAttribute = cachedAttributes[ name ];
  8539. let geometryAttribute = geometryAttributes[ name ];
  8540. if ( geometryAttribute === undefined ) {
  8541. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8542. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8543. }
  8544. if ( cachedAttribute === undefined ) return true;
  8545. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8546. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8547. attributesNum ++;
  8548. }
  8549. }
  8550. if ( currentState.attributesNum !== attributesNum ) return true;
  8551. if ( currentState.index !== index ) return true;
  8552. return false;
  8553. }
  8554. function saveCache( object, geometry, program, index ) {
  8555. const cache = {};
  8556. const attributes = geometry.attributes;
  8557. let attributesNum = 0;
  8558. const programAttributes = program.getAttributes();
  8559. for ( const name in programAttributes ) {
  8560. const programAttribute = programAttributes[ name ];
  8561. if ( programAttribute.location >= 0 ) {
  8562. let attribute = attributes[ name ];
  8563. if ( attribute === undefined ) {
  8564. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8565. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8566. }
  8567. const data = {};
  8568. data.attribute = attribute;
  8569. if ( attribute && attribute.data ) {
  8570. data.data = attribute.data;
  8571. }
  8572. cache[ name ] = data;
  8573. attributesNum ++;
  8574. }
  8575. }
  8576. currentState.attributes = cache;
  8577. currentState.attributesNum = attributesNum;
  8578. currentState.index = index;
  8579. }
  8580. function initAttributes() {
  8581. const newAttributes = currentState.newAttributes;
  8582. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8583. newAttributes[ i ] = 0;
  8584. }
  8585. }
  8586. function enableAttribute( attribute ) {
  8587. enableAttributeAndDivisor( attribute, 0 );
  8588. }
  8589. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8590. const newAttributes = currentState.newAttributes;
  8591. const enabledAttributes = currentState.enabledAttributes;
  8592. const attributeDivisors = currentState.attributeDivisors;
  8593. newAttributes[ attribute ] = 1;
  8594. if ( enabledAttributes[ attribute ] === 0 ) {
  8595. gl.enableVertexAttribArray( attribute );
  8596. enabledAttributes[ attribute ] = 1;
  8597. }
  8598. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8599. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8600. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8601. attributeDivisors[ attribute ] = meshPerAttribute;
  8602. }
  8603. }
  8604. function disableUnusedAttributes() {
  8605. const newAttributes = currentState.newAttributes;
  8606. const enabledAttributes = currentState.enabledAttributes;
  8607. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8608. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8609. gl.disableVertexAttribArray( i );
  8610. enabledAttributes[ i ] = 0;
  8611. }
  8612. }
  8613. }
  8614. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8615. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8616. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8617. } else {
  8618. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8619. }
  8620. }
  8621. function setupVertexAttributes( object, material, program, geometry ) {
  8622. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8623. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8624. }
  8625. initAttributes();
  8626. const geometryAttributes = geometry.attributes;
  8627. const programAttributes = program.getAttributes();
  8628. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8629. for ( const name in programAttributes ) {
  8630. const programAttribute = programAttributes[ name ];
  8631. if ( programAttribute.location >= 0 ) {
  8632. let geometryAttribute = geometryAttributes[ name ];
  8633. if ( geometryAttribute === undefined ) {
  8634. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8635. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8636. }
  8637. if ( geometryAttribute !== undefined ) {
  8638. const normalized = geometryAttribute.normalized;
  8639. const size = geometryAttribute.itemSize;
  8640. const attribute = attributes.get( geometryAttribute );
  8641. // TODO Attribute may not be available on context restore
  8642. if ( attribute === undefined ) continue;
  8643. const buffer = attribute.buffer;
  8644. const type = attribute.type;
  8645. const bytesPerElement = attribute.bytesPerElement;
  8646. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8647. const data = geometryAttribute.data;
  8648. const stride = data.stride;
  8649. const offset = geometryAttribute.offset;
  8650. if ( data.isInstancedInterleavedBuffer ) {
  8651. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8652. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8653. }
  8654. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8655. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8656. }
  8657. } else {
  8658. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8659. enableAttribute( programAttribute.location + i );
  8660. }
  8661. }
  8662. gl.bindBuffer( 34962, buffer );
  8663. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8664. vertexAttribPointer(
  8665. programAttribute.location + i,
  8666. size / programAttribute.locationSize,
  8667. type,
  8668. normalized,
  8669. stride * bytesPerElement,
  8670. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8671. );
  8672. }
  8673. } else {
  8674. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8675. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8676. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8677. }
  8678. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8679. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8680. }
  8681. } else {
  8682. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8683. enableAttribute( programAttribute.location + i );
  8684. }
  8685. }
  8686. gl.bindBuffer( 34962, buffer );
  8687. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8688. vertexAttribPointer(
  8689. programAttribute.location + i,
  8690. size / programAttribute.locationSize,
  8691. type,
  8692. normalized,
  8693. size * bytesPerElement,
  8694. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8695. );
  8696. }
  8697. }
  8698. } else if ( materialDefaultAttributeValues !== undefined ) {
  8699. const value = materialDefaultAttributeValues[ name ];
  8700. if ( value !== undefined ) {
  8701. switch ( value.length ) {
  8702. case 2:
  8703. gl.vertexAttrib2fv( programAttribute.location, value );
  8704. break;
  8705. case 3:
  8706. gl.vertexAttrib3fv( programAttribute.location, value );
  8707. break;
  8708. case 4:
  8709. gl.vertexAttrib4fv( programAttribute.location, value );
  8710. break;
  8711. default:
  8712. gl.vertexAttrib1fv( programAttribute.location, value );
  8713. }
  8714. }
  8715. }
  8716. }
  8717. }
  8718. disableUnusedAttributes();
  8719. }
  8720. function dispose() {
  8721. reset();
  8722. for ( const geometryId in bindingStates ) {
  8723. const programMap = bindingStates[ geometryId ];
  8724. for ( const programId in programMap ) {
  8725. const stateMap = programMap[ programId ];
  8726. for ( const wireframe in stateMap ) {
  8727. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8728. delete stateMap[ wireframe ];
  8729. }
  8730. delete programMap[ programId ];
  8731. }
  8732. delete bindingStates[ geometryId ];
  8733. }
  8734. }
  8735. function releaseStatesOfGeometry( geometry ) {
  8736. if ( bindingStates[ geometry.id ] === undefined ) return;
  8737. const programMap = bindingStates[ geometry.id ];
  8738. for ( const programId in programMap ) {
  8739. const stateMap = programMap[ programId ];
  8740. for ( const wireframe in stateMap ) {
  8741. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8742. delete stateMap[ wireframe ];
  8743. }
  8744. delete programMap[ programId ];
  8745. }
  8746. delete bindingStates[ geometry.id ];
  8747. }
  8748. function releaseStatesOfProgram( program ) {
  8749. for ( const geometryId in bindingStates ) {
  8750. const programMap = bindingStates[ geometryId ];
  8751. if ( programMap[ program.id ] === undefined ) continue;
  8752. const stateMap = programMap[ program.id ];
  8753. for ( const wireframe in stateMap ) {
  8754. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8755. delete stateMap[ wireframe ];
  8756. }
  8757. delete programMap[ program.id ];
  8758. }
  8759. }
  8760. function reset() {
  8761. resetDefaultState();
  8762. forceUpdate = true;
  8763. if ( currentState === defaultState ) return;
  8764. currentState = defaultState;
  8765. bindVertexArrayObject( currentState.object );
  8766. }
  8767. // for backward-compatibility
  8768. function resetDefaultState() {
  8769. defaultState.geometry = null;
  8770. defaultState.program = null;
  8771. defaultState.wireframe = false;
  8772. }
  8773. return {
  8774. setup: setup,
  8775. reset: reset,
  8776. resetDefaultState: resetDefaultState,
  8777. dispose: dispose,
  8778. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8779. releaseStatesOfProgram: releaseStatesOfProgram,
  8780. initAttributes: initAttributes,
  8781. enableAttribute: enableAttribute,
  8782. disableUnusedAttributes: disableUnusedAttributes
  8783. };
  8784. }
  8785. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8786. const isWebGL2 = capabilities.isWebGL2;
  8787. let mode;
  8788. function setMode( value ) {
  8789. mode = value;
  8790. }
  8791. function render( start, count ) {
  8792. gl.drawArrays( mode, start, count );
  8793. info.update( count, mode, 1 );
  8794. }
  8795. function renderInstances( start, count, primcount ) {
  8796. if ( primcount === 0 ) return;
  8797. let extension, methodName;
  8798. if ( isWebGL2 ) {
  8799. extension = gl;
  8800. methodName = 'drawArraysInstanced';
  8801. } else {
  8802. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8803. methodName = 'drawArraysInstancedANGLE';
  8804. if ( extension === null ) {
  8805. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8806. return;
  8807. }
  8808. }
  8809. extension[ methodName ]( mode, start, count, primcount );
  8810. info.update( count, mode, primcount );
  8811. }
  8812. //
  8813. this.setMode = setMode;
  8814. this.render = render;
  8815. this.renderInstances = renderInstances;
  8816. }
  8817. function WebGLCapabilities( gl, extensions, parameters ) {
  8818. let maxAnisotropy;
  8819. function getMaxAnisotropy() {
  8820. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8821. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8822. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8823. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8824. } else {
  8825. maxAnisotropy = 0;
  8826. }
  8827. return maxAnisotropy;
  8828. }
  8829. function getMaxPrecision( precision ) {
  8830. if ( precision === 'highp' ) {
  8831. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8832. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8833. return 'highp';
  8834. }
  8835. precision = 'mediump';
  8836. }
  8837. if ( precision === 'mediump' ) {
  8838. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8839. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8840. return 'mediump';
  8841. }
  8842. }
  8843. return 'lowp';
  8844. }
  8845. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8846. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8847. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8848. const maxPrecision = getMaxPrecision( precision );
  8849. if ( maxPrecision !== precision ) {
  8850. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8851. precision = maxPrecision;
  8852. }
  8853. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8854. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8855. const maxTextures = gl.getParameter( 34930 );
  8856. const maxVertexTextures = gl.getParameter( 35660 );
  8857. const maxTextureSize = gl.getParameter( 3379 );
  8858. const maxCubemapSize = gl.getParameter( 34076 );
  8859. const maxAttributes = gl.getParameter( 34921 );
  8860. const maxVertexUniforms = gl.getParameter( 36347 );
  8861. const maxVaryings = gl.getParameter( 36348 );
  8862. const maxFragmentUniforms = gl.getParameter( 36349 );
  8863. const vertexTextures = maxVertexTextures > 0;
  8864. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8865. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8866. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8867. return {
  8868. isWebGL2: isWebGL2,
  8869. drawBuffers: drawBuffers,
  8870. getMaxAnisotropy: getMaxAnisotropy,
  8871. getMaxPrecision: getMaxPrecision,
  8872. precision: precision,
  8873. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8874. maxTextures: maxTextures,
  8875. maxVertexTextures: maxVertexTextures,
  8876. maxTextureSize: maxTextureSize,
  8877. maxCubemapSize: maxCubemapSize,
  8878. maxAttributes: maxAttributes,
  8879. maxVertexUniforms: maxVertexUniforms,
  8880. maxVaryings: maxVaryings,
  8881. maxFragmentUniforms: maxFragmentUniforms,
  8882. vertexTextures: vertexTextures,
  8883. floatFragmentTextures: floatFragmentTextures,
  8884. floatVertexTextures: floatVertexTextures,
  8885. maxSamples: maxSamples
  8886. };
  8887. }
  8888. function WebGLClipping( properties ) {
  8889. const scope = this;
  8890. let globalState = null,
  8891. numGlobalPlanes = 0,
  8892. localClippingEnabled = false,
  8893. renderingShadows = false;
  8894. const plane = new Plane(),
  8895. viewNormalMatrix = new Matrix3(),
  8896. uniform = { value: null, needsUpdate: false };
  8897. this.uniform = uniform;
  8898. this.numPlanes = 0;
  8899. this.numIntersection = 0;
  8900. this.init = function ( planes, enableLocalClipping, camera ) {
  8901. const enabled =
  8902. planes.length !== 0 ||
  8903. enableLocalClipping ||
  8904. // enable state of previous frame - the clipping code has to
  8905. // run another frame in order to reset the state:
  8906. numGlobalPlanes !== 0 ||
  8907. localClippingEnabled;
  8908. localClippingEnabled = enableLocalClipping;
  8909. globalState = projectPlanes( planes, camera, 0 );
  8910. numGlobalPlanes = planes.length;
  8911. return enabled;
  8912. };
  8913. this.beginShadows = function () {
  8914. renderingShadows = true;
  8915. projectPlanes( null );
  8916. };
  8917. this.endShadows = function () {
  8918. renderingShadows = false;
  8919. resetGlobalState();
  8920. };
  8921. this.setState = function ( material, camera, useCache ) {
  8922. const planes = material.clippingPlanes,
  8923. clipIntersection = material.clipIntersection,
  8924. clipShadows = material.clipShadows;
  8925. const materialProperties = properties.get( material );
  8926. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8927. // there's no local clipping
  8928. if ( renderingShadows ) {
  8929. // there's no global clipping
  8930. projectPlanes( null );
  8931. } else {
  8932. resetGlobalState();
  8933. }
  8934. } else {
  8935. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8936. lGlobal = nGlobal * 4;
  8937. let dstArray = materialProperties.clippingState || null;
  8938. uniform.value = dstArray; // ensure unique state
  8939. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8940. for ( let i = 0; i !== lGlobal; ++ i ) {
  8941. dstArray[ i ] = globalState[ i ];
  8942. }
  8943. materialProperties.clippingState = dstArray;
  8944. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8945. this.numPlanes += nGlobal;
  8946. }
  8947. };
  8948. function resetGlobalState() {
  8949. if ( uniform.value !== globalState ) {
  8950. uniform.value = globalState;
  8951. uniform.needsUpdate = numGlobalPlanes > 0;
  8952. }
  8953. scope.numPlanes = numGlobalPlanes;
  8954. scope.numIntersection = 0;
  8955. }
  8956. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8957. const nPlanes = planes !== null ? planes.length : 0;
  8958. let dstArray = null;
  8959. if ( nPlanes !== 0 ) {
  8960. dstArray = uniform.value;
  8961. if ( skipTransform !== true || dstArray === null ) {
  8962. const flatSize = dstOffset + nPlanes * 4,
  8963. viewMatrix = camera.matrixWorldInverse;
  8964. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8965. if ( dstArray === null || dstArray.length < flatSize ) {
  8966. dstArray = new Float32Array( flatSize );
  8967. }
  8968. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8969. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8970. plane.normal.toArray( dstArray, i4 );
  8971. dstArray[ i4 + 3 ] = plane.constant;
  8972. }
  8973. }
  8974. uniform.value = dstArray;
  8975. uniform.needsUpdate = true;
  8976. }
  8977. scope.numPlanes = nPlanes;
  8978. scope.numIntersection = 0;
  8979. return dstArray;
  8980. }
  8981. }
  8982. function WebGLCubeMaps( renderer ) {
  8983. let cubemaps = new WeakMap();
  8984. function mapTextureMapping( texture, mapping ) {
  8985. if ( mapping === EquirectangularReflectionMapping ) {
  8986. texture.mapping = CubeReflectionMapping;
  8987. } else if ( mapping === EquirectangularRefractionMapping ) {
  8988. texture.mapping = CubeRefractionMapping;
  8989. }
  8990. return texture;
  8991. }
  8992. function get( texture ) {
  8993. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8994. const mapping = texture.mapping;
  8995. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8996. if ( cubemaps.has( texture ) ) {
  8997. const cubemap = cubemaps.get( texture ).texture;
  8998. return mapTextureMapping( cubemap, texture.mapping );
  8999. } else {
  9000. const image = texture.image;
  9001. if ( image && image.height > 0 ) {
  9002. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9003. renderTarget.fromEquirectangularTexture( renderer, texture );
  9004. cubemaps.set( texture, renderTarget );
  9005. texture.addEventListener( 'dispose', onTextureDispose );
  9006. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9007. } else {
  9008. // image not yet ready. try the conversion next frame
  9009. return null;
  9010. }
  9011. }
  9012. }
  9013. }
  9014. return texture;
  9015. }
  9016. function onTextureDispose( event ) {
  9017. const texture = event.target;
  9018. texture.removeEventListener( 'dispose', onTextureDispose );
  9019. const cubemap = cubemaps.get( texture );
  9020. if ( cubemap !== undefined ) {
  9021. cubemaps.delete( texture );
  9022. cubemap.dispose();
  9023. }
  9024. }
  9025. function dispose() {
  9026. cubemaps = new WeakMap();
  9027. }
  9028. return {
  9029. get: get,
  9030. dispose: dispose
  9031. };
  9032. }
  9033. class OrthographicCamera extends Camera {
  9034. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9035. super();
  9036. this.isOrthographicCamera = true;
  9037. this.type = 'OrthographicCamera';
  9038. this.zoom = 1;
  9039. this.view = null;
  9040. this.left = left;
  9041. this.right = right;
  9042. this.top = top;
  9043. this.bottom = bottom;
  9044. this.near = near;
  9045. this.far = far;
  9046. this.updateProjectionMatrix();
  9047. }
  9048. copy( source, recursive ) {
  9049. super.copy( source, recursive );
  9050. this.left = source.left;
  9051. this.right = source.right;
  9052. this.top = source.top;
  9053. this.bottom = source.bottom;
  9054. this.near = source.near;
  9055. this.far = source.far;
  9056. this.zoom = source.zoom;
  9057. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9058. return this;
  9059. }
  9060. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9061. if ( this.view === null ) {
  9062. this.view = {
  9063. enabled: true,
  9064. fullWidth: 1,
  9065. fullHeight: 1,
  9066. offsetX: 0,
  9067. offsetY: 0,
  9068. width: 1,
  9069. height: 1
  9070. };
  9071. }
  9072. this.view.enabled = true;
  9073. this.view.fullWidth = fullWidth;
  9074. this.view.fullHeight = fullHeight;
  9075. this.view.offsetX = x;
  9076. this.view.offsetY = y;
  9077. this.view.width = width;
  9078. this.view.height = height;
  9079. this.updateProjectionMatrix();
  9080. }
  9081. clearViewOffset() {
  9082. if ( this.view !== null ) {
  9083. this.view.enabled = false;
  9084. }
  9085. this.updateProjectionMatrix();
  9086. }
  9087. updateProjectionMatrix() {
  9088. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9089. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9090. const cx = ( this.right + this.left ) / 2;
  9091. const cy = ( this.top + this.bottom ) / 2;
  9092. let left = cx - dx;
  9093. let right = cx + dx;
  9094. let top = cy + dy;
  9095. let bottom = cy - dy;
  9096. if ( this.view !== null && this.view.enabled ) {
  9097. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9098. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9099. left += scaleW * this.view.offsetX;
  9100. right = left + scaleW * this.view.width;
  9101. top -= scaleH * this.view.offsetY;
  9102. bottom = top - scaleH * this.view.height;
  9103. }
  9104. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9105. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9106. }
  9107. toJSON( meta ) {
  9108. const data = super.toJSON( meta );
  9109. data.object.zoom = this.zoom;
  9110. data.object.left = this.left;
  9111. data.object.right = this.right;
  9112. data.object.top = this.top;
  9113. data.object.bottom = this.bottom;
  9114. data.object.near = this.near;
  9115. data.object.far = this.far;
  9116. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9117. return data;
  9118. }
  9119. }
  9120. const LOD_MIN = 4;
  9121. // The standard deviations (radians) associated with the extra mips. These are
  9122. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9123. // geometric shadowing function. These sigma values squared must match the
  9124. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9125. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9126. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9127. // samples and exit early, but not recompile the shader.
  9128. const MAX_SAMPLES = 20;
  9129. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9130. const _clearColor = /*@__PURE__*/ new Color();
  9131. let _oldTarget = null;
  9132. // Golden Ratio
  9133. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9134. const INV_PHI = 1 / PHI;
  9135. // Vertices of a dodecahedron (except the opposites, which represent the
  9136. // same axis), used as axis directions evenly spread on a sphere.
  9137. const _axisDirections = [
  9138. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9139. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9140. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9141. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9142. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9143. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9144. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9145. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9146. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9147. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9148. /**
  9149. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9150. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9151. * blur to be quickly accessed based on material roughness. It is packed into a
  9152. * special CubeUV format that allows us to perform custom interpolation so that
  9153. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9154. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9155. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9156. * higher roughness levels. In this way we maintain resolution to smoothly
  9157. * interpolate diffuse lighting while limiting sampling computation.
  9158. *
  9159. * Paper: Fast, Accurate Image-Based Lighting
  9160. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9161. */
  9162. class PMREMGenerator {
  9163. constructor( renderer ) {
  9164. this._renderer = renderer;
  9165. this._pingPongRenderTarget = null;
  9166. this._lodMax = 0;
  9167. this._cubeSize = 0;
  9168. this._lodPlanes = [];
  9169. this._sizeLods = [];
  9170. this._sigmas = [];
  9171. this._blurMaterial = null;
  9172. this._cubemapMaterial = null;
  9173. this._equirectMaterial = null;
  9174. this._compileMaterial( this._blurMaterial );
  9175. }
  9176. /**
  9177. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9178. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9179. * in radians to be applied to the scene before PMREM generation. Optional near
  9180. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9181. * is placed at the origin).
  9182. */
  9183. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9184. _oldTarget = this._renderer.getRenderTarget();
  9185. this._setSize( 256 );
  9186. const cubeUVRenderTarget = this._allocateTargets();
  9187. cubeUVRenderTarget.depthBuffer = true;
  9188. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9189. if ( sigma > 0 ) {
  9190. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9191. }
  9192. this._applyPMREM( cubeUVRenderTarget );
  9193. this._cleanup( cubeUVRenderTarget );
  9194. return cubeUVRenderTarget;
  9195. }
  9196. /**
  9197. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9198. * or HDR. The ideal input image size is 1k (1024 x 512),
  9199. * as this matches best with the 256 x 256 cubemap output.
  9200. */
  9201. fromEquirectangular( equirectangular, renderTarget = null ) {
  9202. return this._fromTexture( equirectangular, renderTarget );
  9203. }
  9204. /**
  9205. * Generates a PMREM from an cubemap texture, which can be either LDR
  9206. * or HDR. The ideal input cube size is 256 x 256,
  9207. * as this matches best with the 256 x 256 cubemap output.
  9208. */
  9209. fromCubemap( cubemap, renderTarget = null ) {
  9210. return this._fromTexture( cubemap, renderTarget );
  9211. }
  9212. /**
  9213. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9214. * your texture's network fetch for increased concurrency.
  9215. */
  9216. compileCubemapShader() {
  9217. if ( this._cubemapMaterial === null ) {
  9218. this._cubemapMaterial = _getCubemapMaterial();
  9219. this._compileMaterial( this._cubemapMaterial );
  9220. }
  9221. }
  9222. /**
  9223. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9224. * your texture's network fetch for increased concurrency.
  9225. */
  9226. compileEquirectangularShader() {
  9227. if ( this._equirectMaterial === null ) {
  9228. this._equirectMaterial = _getEquirectMaterial();
  9229. this._compileMaterial( this._equirectMaterial );
  9230. }
  9231. }
  9232. /**
  9233. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9234. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9235. * one of them will cause any others to also become unusable.
  9236. */
  9237. dispose() {
  9238. this._dispose();
  9239. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9240. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9241. }
  9242. // private interface
  9243. _setSize( cubeSize ) {
  9244. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9245. this._cubeSize = Math.pow( 2, this._lodMax );
  9246. }
  9247. _dispose() {
  9248. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9249. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9250. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9251. this._lodPlanes[ i ].dispose();
  9252. }
  9253. }
  9254. _cleanup( outputTarget ) {
  9255. this._renderer.setRenderTarget( _oldTarget );
  9256. outputTarget.scissorTest = false;
  9257. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9258. }
  9259. _fromTexture( texture, renderTarget ) {
  9260. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9261. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9262. } else { // Equirectangular
  9263. this._setSize( texture.image.width / 4 );
  9264. }
  9265. _oldTarget = this._renderer.getRenderTarget();
  9266. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9267. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9268. this._applyPMREM( cubeUVRenderTarget );
  9269. this._cleanup( cubeUVRenderTarget );
  9270. return cubeUVRenderTarget;
  9271. }
  9272. _allocateTargets() {
  9273. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9274. const height = 4 * this._cubeSize;
  9275. const params = {
  9276. magFilter: LinearFilter,
  9277. minFilter: LinearFilter,
  9278. generateMipmaps: false,
  9279. type: HalfFloatType,
  9280. format: RGBAFormat,
  9281. encoding: LinearEncoding,
  9282. depthBuffer: false
  9283. };
  9284. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9285. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width ) {
  9286. if ( this._pingPongRenderTarget !== null ) {
  9287. this._dispose();
  9288. }
  9289. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9290. const { _lodMax } = this;
  9291. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9292. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9293. }
  9294. return cubeUVRenderTarget;
  9295. }
  9296. _compileMaterial( material ) {
  9297. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9298. this._renderer.compile( tmpMesh, _flatCamera );
  9299. }
  9300. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9301. const fov = 90;
  9302. const aspect = 1;
  9303. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9304. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9305. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9306. const renderer = this._renderer;
  9307. const originalAutoClear = renderer.autoClear;
  9308. const toneMapping = renderer.toneMapping;
  9309. renderer.getClearColor( _clearColor );
  9310. renderer.toneMapping = NoToneMapping;
  9311. renderer.autoClear = false;
  9312. const backgroundMaterial = new MeshBasicMaterial( {
  9313. name: 'PMREM.Background',
  9314. side: BackSide,
  9315. depthWrite: false,
  9316. depthTest: false,
  9317. } );
  9318. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9319. let useSolidColor = false;
  9320. const background = scene.background;
  9321. if ( background ) {
  9322. if ( background.isColor ) {
  9323. backgroundMaterial.color.copy( background );
  9324. scene.background = null;
  9325. useSolidColor = true;
  9326. }
  9327. } else {
  9328. backgroundMaterial.color.copy( _clearColor );
  9329. useSolidColor = true;
  9330. }
  9331. for ( let i = 0; i < 6; i ++ ) {
  9332. const col = i % 3;
  9333. if ( col === 0 ) {
  9334. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9335. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9336. } else if ( col === 1 ) {
  9337. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9338. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9339. } else {
  9340. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9341. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9342. }
  9343. const size = this._cubeSize;
  9344. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9345. renderer.setRenderTarget( cubeUVRenderTarget );
  9346. if ( useSolidColor ) {
  9347. renderer.render( backgroundBox, cubeCamera );
  9348. }
  9349. renderer.render( scene, cubeCamera );
  9350. }
  9351. backgroundBox.geometry.dispose();
  9352. backgroundBox.material.dispose();
  9353. renderer.toneMapping = toneMapping;
  9354. renderer.autoClear = originalAutoClear;
  9355. scene.background = background;
  9356. }
  9357. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9358. const renderer = this._renderer;
  9359. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9360. if ( isCubeTexture ) {
  9361. if ( this._cubemapMaterial === null ) {
  9362. this._cubemapMaterial = _getCubemapMaterial();
  9363. }
  9364. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9365. } else {
  9366. if ( this._equirectMaterial === null ) {
  9367. this._equirectMaterial = _getEquirectMaterial();
  9368. }
  9369. }
  9370. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9371. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9372. const uniforms = material.uniforms;
  9373. uniforms[ 'envMap' ].value = texture;
  9374. const size = this._cubeSize;
  9375. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9376. renderer.setRenderTarget( cubeUVRenderTarget );
  9377. renderer.render( mesh, _flatCamera );
  9378. }
  9379. _applyPMREM( cubeUVRenderTarget ) {
  9380. const renderer = this._renderer;
  9381. const autoClear = renderer.autoClear;
  9382. renderer.autoClear = false;
  9383. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9384. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9385. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9386. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9387. }
  9388. renderer.autoClear = autoClear;
  9389. }
  9390. /**
  9391. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9392. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9393. * the blur latitudinally (around the poles), and then longitudinally (towards
  9394. * the poles) to approximate the orthogonally-separable blur. It is least
  9395. * accurate at the poles, but still does a decent job.
  9396. */
  9397. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9398. const pingPongRenderTarget = this._pingPongRenderTarget;
  9399. this._halfBlur(
  9400. cubeUVRenderTarget,
  9401. pingPongRenderTarget,
  9402. lodIn,
  9403. lodOut,
  9404. sigma,
  9405. 'latitudinal',
  9406. poleAxis );
  9407. this._halfBlur(
  9408. pingPongRenderTarget,
  9409. cubeUVRenderTarget,
  9410. lodOut,
  9411. lodOut,
  9412. sigma,
  9413. 'longitudinal',
  9414. poleAxis );
  9415. }
  9416. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9417. const renderer = this._renderer;
  9418. const blurMaterial = this._blurMaterial;
  9419. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9420. console.error(
  9421. 'blur direction must be either latitudinal or longitudinal!' );
  9422. }
  9423. // Number of standard deviations at which to cut off the discrete approximation.
  9424. const STANDARD_DEVIATIONS = 3;
  9425. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9426. const blurUniforms = blurMaterial.uniforms;
  9427. const pixels = this._sizeLods[ lodIn ] - 1;
  9428. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9429. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9430. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9431. if ( samples > MAX_SAMPLES ) {
  9432. console.warn( `sigmaRadians, ${
  9433. sigmaRadians}, is too large and will clip, as it requested ${
  9434. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9435. }
  9436. const weights = [];
  9437. let sum = 0;
  9438. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9439. const x = i / sigmaPixels;
  9440. const weight = Math.exp( - x * x / 2 );
  9441. weights.push( weight );
  9442. if ( i === 0 ) {
  9443. sum += weight;
  9444. } else if ( i < samples ) {
  9445. sum += 2 * weight;
  9446. }
  9447. }
  9448. for ( let i = 0; i < weights.length; i ++ ) {
  9449. weights[ i ] = weights[ i ] / sum;
  9450. }
  9451. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9452. blurUniforms[ 'samples' ].value = samples;
  9453. blurUniforms[ 'weights' ].value = weights;
  9454. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9455. if ( poleAxis ) {
  9456. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9457. }
  9458. const { _lodMax } = this;
  9459. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9460. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9461. const outputSize = this._sizeLods[ lodOut ];
  9462. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9463. const y = 4 * ( this._cubeSize - outputSize );
  9464. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9465. renderer.setRenderTarget( targetOut );
  9466. renderer.render( blurMesh, _flatCamera );
  9467. }
  9468. }
  9469. function _createPlanes( lodMax ) {
  9470. const lodPlanes = [];
  9471. const sizeLods = [];
  9472. const sigmas = [];
  9473. let lod = lodMax;
  9474. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9475. for ( let i = 0; i < totalLods; i ++ ) {
  9476. const sizeLod = Math.pow( 2, lod );
  9477. sizeLods.push( sizeLod );
  9478. let sigma = 1.0 / sizeLod;
  9479. if ( i > lodMax - LOD_MIN ) {
  9480. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9481. } else if ( i === 0 ) {
  9482. sigma = 0;
  9483. }
  9484. sigmas.push( sigma );
  9485. const texelSize = 1.0 / ( sizeLod - 2 );
  9486. const min = - texelSize;
  9487. const max = 1 + texelSize;
  9488. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9489. const cubeFaces = 6;
  9490. const vertices = 6;
  9491. const positionSize = 3;
  9492. const uvSize = 2;
  9493. const faceIndexSize = 1;
  9494. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9495. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9496. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9497. for ( let face = 0; face < cubeFaces; face ++ ) {
  9498. const x = ( face % 3 ) * 2 / 3 - 1;
  9499. const y = face > 2 ? 0 : - 1;
  9500. const coordinates = [
  9501. x, y, 0,
  9502. x + 2 / 3, y, 0,
  9503. x + 2 / 3, y + 1, 0,
  9504. x, y, 0,
  9505. x + 2 / 3, y + 1, 0,
  9506. x, y + 1, 0
  9507. ];
  9508. position.set( coordinates, positionSize * vertices * face );
  9509. uv.set( uv1, uvSize * vertices * face );
  9510. const fill = [ face, face, face, face, face, face ];
  9511. faceIndex.set( fill, faceIndexSize * vertices * face );
  9512. }
  9513. const planes = new BufferGeometry();
  9514. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9515. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9516. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9517. lodPlanes.push( planes );
  9518. if ( lod > LOD_MIN ) {
  9519. lod --;
  9520. }
  9521. }
  9522. return { lodPlanes, sizeLods, sigmas };
  9523. }
  9524. function _createRenderTarget( width, height, params ) {
  9525. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9526. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9527. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9528. cubeUVRenderTarget.scissorTest = true;
  9529. return cubeUVRenderTarget;
  9530. }
  9531. function _setViewport( target, x, y, width, height ) {
  9532. target.viewport.set( x, y, width, height );
  9533. target.scissor.set( x, y, width, height );
  9534. }
  9535. function _getBlurShader( lodMax, width, height ) {
  9536. const weights = new Float32Array( MAX_SAMPLES );
  9537. const poleAxis = new Vector3( 0, 1, 0 );
  9538. const shaderMaterial = new ShaderMaterial( {
  9539. name: 'SphericalGaussianBlur',
  9540. defines: {
  9541. 'n': MAX_SAMPLES,
  9542. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9543. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9544. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9545. },
  9546. uniforms: {
  9547. 'envMap': { value: null },
  9548. 'samples': { value: 1 },
  9549. 'weights': { value: weights },
  9550. 'latitudinal': { value: false },
  9551. 'dTheta': { value: 0 },
  9552. 'mipInt': { value: 0 },
  9553. 'poleAxis': { value: poleAxis }
  9554. },
  9555. vertexShader: _getCommonVertexShader(),
  9556. fragmentShader: /* glsl */`
  9557. precision mediump float;
  9558. precision mediump int;
  9559. varying vec3 vOutputDirection;
  9560. uniform sampler2D envMap;
  9561. uniform int samples;
  9562. uniform float weights[ n ];
  9563. uniform bool latitudinal;
  9564. uniform float dTheta;
  9565. uniform float mipInt;
  9566. uniform vec3 poleAxis;
  9567. #define ENVMAP_TYPE_CUBE_UV
  9568. #include <cube_uv_reflection_fragment>
  9569. vec3 getSample( float theta, vec3 axis ) {
  9570. float cosTheta = cos( theta );
  9571. // Rodrigues' axis-angle rotation
  9572. vec3 sampleDirection = vOutputDirection * cosTheta
  9573. + cross( axis, vOutputDirection ) * sin( theta )
  9574. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9575. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9576. }
  9577. void main() {
  9578. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9579. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9580. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9581. }
  9582. axis = normalize( axis );
  9583. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9584. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9585. for ( int i = 1; i < n; i++ ) {
  9586. if ( i >= samples ) {
  9587. break;
  9588. }
  9589. float theta = dTheta * float( i );
  9590. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9591. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9592. }
  9593. }
  9594. `,
  9595. blending: NoBlending,
  9596. depthTest: false,
  9597. depthWrite: false
  9598. } );
  9599. return shaderMaterial;
  9600. }
  9601. function _getEquirectMaterial() {
  9602. return new ShaderMaterial( {
  9603. name: 'EquirectangularToCubeUV',
  9604. uniforms: {
  9605. 'envMap': { value: null }
  9606. },
  9607. vertexShader: _getCommonVertexShader(),
  9608. fragmentShader: /* glsl */`
  9609. precision mediump float;
  9610. precision mediump int;
  9611. varying vec3 vOutputDirection;
  9612. uniform sampler2D envMap;
  9613. #include <common>
  9614. void main() {
  9615. vec3 outputDirection = normalize( vOutputDirection );
  9616. vec2 uv = equirectUv( outputDirection );
  9617. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9618. }
  9619. `,
  9620. blending: NoBlending,
  9621. depthTest: false,
  9622. depthWrite: false
  9623. } );
  9624. }
  9625. function _getCubemapMaterial() {
  9626. return new ShaderMaterial( {
  9627. name: 'CubemapToCubeUV',
  9628. uniforms: {
  9629. 'envMap': { value: null },
  9630. 'flipEnvMap': { value: - 1 }
  9631. },
  9632. vertexShader: _getCommonVertexShader(),
  9633. fragmentShader: /* glsl */`
  9634. precision mediump float;
  9635. precision mediump int;
  9636. uniform float flipEnvMap;
  9637. varying vec3 vOutputDirection;
  9638. uniform samplerCube envMap;
  9639. void main() {
  9640. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9641. }
  9642. `,
  9643. blending: NoBlending,
  9644. depthTest: false,
  9645. depthWrite: false
  9646. } );
  9647. }
  9648. function _getCommonVertexShader() {
  9649. return /* glsl */`
  9650. precision mediump float;
  9651. precision mediump int;
  9652. attribute float faceIndex;
  9653. varying vec3 vOutputDirection;
  9654. // RH coordinate system; PMREM face-indexing convention
  9655. vec3 getDirection( vec2 uv, float face ) {
  9656. uv = 2.0 * uv - 1.0;
  9657. vec3 direction = vec3( uv, 1.0 );
  9658. if ( face == 0.0 ) {
  9659. direction = direction.zyx; // ( 1, v, u ) pos x
  9660. } else if ( face == 1.0 ) {
  9661. direction = direction.xzy;
  9662. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9663. } else if ( face == 2.0 ) {
  9664. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9665. } else if ( face == 3.0 ) {
  9666. direction = direction.zyx;
  9667. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9668. } else if ( face == 4.0 ) {
  9669. direction = direction.xzy;
  9670. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9671. } else if ( face == 5.0 ) {
  9672. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9673. }
  9674. return direction;
  9675. }
  9676. void main() {
  9677. vOutputDirection = getDirection( uv, faceIndex );
  9678. gl_Position = vec4( position, 1.0 );
  9679. }
  9680. `;
  9681. }
  9682. function WebGLCubeUVMaps( renderer ) {
  9683. let cubeUVmaps = new WeakMap();
  9684. let pmremGenerator = null;
  9685. function get( texture ) {
  9686. if ( texture && texture.isTexture ) {
  9687. const mapping = texture.mapping;
  9688. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9689. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9690. // equirect/cube map to cubeUV conversion
  9691. if ( isEquirectMap || isCubeMap ) {
  9692. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9693. texture.needsPMREMUpdate = false;
  9694. let renderTarget = cubeUVmaps.get( texture );
  9695. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9696. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9697. cubeUVmaps.set( texture, renderTarget );
  9698. return renderTarget.texture;
  9699. } else {
  9700. if ( cubeUVmaps.has( texture ) ) {
  9701. return cubeUVmaps.get( texture ).texture;
  9702. } else {
  9703. const image = texture.image;
  9704. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9705. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9706. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9707. cubeUVmaps.set( texture, renderTarget );
  9708. texture.addEventListener( 'dispose', onTextureDispose );
  9709. return renderTarget.texture;
  9710. } else {
  9711. // image not yet ready. try the conversion next frame
  9712. return null;
  9713. }
  9714. }
  9715. }
  9716. }
  9717. }
  9718. return texture;
  9719. }
  9720. function isCubeTextureComplete( image ) {
  9721. let count = 0;
  9722. const length = 6;
  9723. for ( let i = 0; i < length; i ++ ) {
  9724. if ( image[ i ] !== undefined ) count ++;
  9725. }
  9726. return count === length;
  9727. }
  9728. function onTextureDispose( event ) {
  9729. const texture = event.target;
  9730. texture.removeEventListener( 'dispose', onTextureDispose );
  9731. const cubemapUV = cubeUVmaps.get( texture );
  9732. if ( cubemapUV !== undefined ) {
  9733. cubeUVmaps.delete( texture );
  9734. cubemapUV.dispose();
  9735. }
  9736. }
  9737. function dispose() {
  9738. cubeUVmaps = new WeakMap();
  9739. if ( pmremGenerator !== null ) {
  9740. pmremGenerator.dispose();
  9741. pmremGenerator = null;
  9742. }
  9743. }
  9744. return {
  9745. get: get,
  9746. dispose: dispose
  9747. };
  9748. }
  9749. function WebGLExtensions( gl ) {
  9750. const extensions = {};
  9751. function getExtension( name ) {
  9752. if ( extensions[ name ] !== undefined ) {
  9753. return extensions[ name ];
  9754. }
  9755. let extension;
  9756. switch ( name ) {
  9757. case 'WEBGL_depth_texture':
  9758. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9759. break;
  9760. case 'EXT_texture_filter_anisotropic':
  9761. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9762. break;
  9763. case 'WEBGL_compressed_texture_s3tc':
  9764. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9765. break;
  9766. case 'WEBGL_compressed_texture_pvrtc':
  9767. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9768. break;
  9769. default:
  9770. extension = gl.getExtension( name );
  9771. }
  9772. extensions[ name ] = extension;
  9773. return extension;
  9774. }
  9775. return {
  9776. has: function ( name ) {
  9777. return getExtension( name ) !== null;
  9778. },
  9779. init: function ( capabilities ) {
  9780. if ( capabilities.isWebGL2 ) {
  9781. getExtension( 'EXT_color_buffer_float' );
  9782. } else {
  9783. getExtension( 'WEBGL_depth_texture' );
  9784. getExtension( 'OES_texture_float' );
  9785. getExtension( 'OES_texture_half_float' );
  9786. getExtension( 'OES_texture_half_float_linear' );
  9787. getExtension( 'OES_standard_derivatives' );
  9788. getExtension( 'OES_element_index_uint' );
  9789. getExtension( 'OES_vertex_array_object' );
  9790. getExtension( 'ANGLE_instanced_arrays' );
  9791. }
  9792. getExtension( 'OES_texture_float_linear' );
  9793. getExtension( 'EXT_color_buffer_half_float' );
  9794. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9795. },
  9796. get: function ( name ) {
  9797. const extension = getExtension( name );
  9798. if ( extension === null ) {
  9799. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9800. }
  9801. return extension;
  9802. }
  9803. };
  9804. }
  9805. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9806. const geometries = {};
  9807. const wireframeAttributes = new WeakMap();
  9808. function onGeometryDispose( event ) {
  9809. const geometry = event.target;
  9810. if ( geometry.index !== null ) {
  9811. attributes.remove( geometry.index );
  9812. }
  9813. for ( const name in geometry.attributes ) {
  9814. attributes.remove( geometry.attributes[ name ] );
  9815. }
  9816. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9817. delete geometries[ geometry.id ];
  9818. const attribute = wireframeAttributes.get( geometry );
  9819. if ( attribute ) {
  9820. attributes.remove( attribute );
  9821. wireframeAttributes.delete( geometry );
  9822. }
  9823. bindingStates.releaseStatesOfGeometry( geometry );
  9824. if ( geometry.isInstancedBufferGeometry === true ) {
  9825. delete geometry._maxInstanceCount;
  9826. }
  9827. //
  9828. info.memory.geometries --;
  9829. }
  9830. function get( object, geometry ) {
  9831. if ( geometries[ geometry.id ] === true ) return geometry;
  9832. geometry.addEventListener( 'dispose', onGeometryDispose );
  9833. geometries[ geometry.id ] = true;
  9834. info.memory.geometries ++;
  9835. return geometry;
  9836. }
  9837. function update( geometry ) {
  9838. const geometryAttributes = geometry.attributes;
  9839. // Updating index buffer in VAO now. See WebGLBindingStates.
  9840. for ( const name in geometryAttributes ) {
  9841. attributes.update( geometryAttributes[ name ], 34962 );
  9842. }
  9843. // morph targets
  9844. const morphAttributes = geometry.morphAttributes;
  9845. for ( const name in morphAttributes ) {
  9846. const array = morphAttributes[ name ];
  9847. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9848. attributes.update( array[ i ], 34962 );
  9849. }
  9850. }
  9851. }
  9852. function updateWireframeAttribute( geometry ) {
  9853. const indices = [];
  9854. const geometryIndex = geometry.index;
  9855. const geometryPosition = geometry.attributes.position;
  9856. let version = 0;
  9857. if ( geometryIndex !== null ) {
  9858. const array = geometryIndex.array;
  9859. version = geometryIndex.version;
  9860. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9861. const a = array[ i + 0 ];
  9862. const b = array[ i + 1 ];
  9863. const c = array[ i + 2 ];
  9864. indices.push( a, b, b, c, c, a );
  9865. }
  9866. } else {
  9867. const array = geometryPosition.array;
  9868. version = geometryPosition.version;
  9869. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9870. const a = i + 0;
  9871. const b = i + 1;
  9872. const c = i + 2;
  9873. indices.push( a, b, b, c, c, a );
  9874. }
  9875. }
  9876. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9877. attribute.version = version;
  9878. // Updating index buffer in VAO now. See WebGLBindingStates
  9879. //
  9880. const previousAttribute = wireframeAttributes.get( geometry );
  9881. if ( previousAttribute ) attributes.remove( previousAttribute );
  9882. //
  9883. wireframeAttributes.set( geometry, attribute );
  9884. }
  9885. function getWireframeAttribute( geometry ) {
  9886. const currentAttribute = wireframeAttributes.get( geometry );
  9887. if ( currentAttribute ) {
  9888. const geometryIndex = geometry.index;
  9889. if ( geometryIndex !== null ) {
  9890. // if the attribute is obsolete, create a new one
  9891. if ( currentAttribute.version < geometryIndex.version ) {
  9892. updateWireframeAttribute( geometry );
  9893. }
  9894. }
  9895. } else {
  9896. updateWireframeAttribute( geometry );
  9897. }
  9898. return wireframeAttributes.get( geometry );
  9899. }
  9900. return {
  9901. get: get,
  9902. update: update,
  9903. getWireframeAttribute: getWireframeAttribute
  9904. };
  9905. }
  9906. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9907. const isWebGL2 = capabilities.isWebGL2;
  9908. let mode;
  9909. function setMode( value ) {
  9910. mode = value;
  9911. }
  9912. let type, bytesPerElement;
  9913. function setIndex( value ) {
  9914. type = value.type;
  9915. bytesPerElement = value.bytesPerElement;
  9916. }
  9917. function render( start, count ) {
  9918. gl.drawElements( mode, count, type, start * bytesPerElement );
  9919. info.update( count, mode, 1 );
  9920. }
  9921. function renderInstances( start, count, primcount ) {
  9922. if ( primcount === 0 ) return;
  9923. let extension, methodName;
  9924. if ( isWebGL2 ) {
  9925. extension = gl;
  9926. methodName = 'drawElementsInstanced';
  9927. } else {
  9928. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9929. methodName = 'drawElementsInstancedANGLE';
  9930. if ( extension === null ) {
  9931. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9932. return;
  9933. }
  9934. }
  9935. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9936. info.update( count, mode, primcount );
  9937. }
  9938. //
  9939. this.setMode = setMode;
  9940. this.setIndex = setIndex;
  9941. this.render = render;
  9942. this.renderInstances = renderInstances;
  9943. }
  9944. function WebGLInfo( gl ) {
  9945. const memory = {
  9946. geometries: 0,
  9947. textures: 0
  9948. };
  9949. const render = {
  9950. frame: 0,
  9951. calls: 0,
  9952. triangles: 0,
  9953. points: 0,
  9954. lines: 0
  9955. };
  9956. function update( count, mode, instanceCount ) {
  9957. render.calls ++;
  9958. switch ( mode ) {
  9959. case 4:
  9960. render.triangles += instanceCount * ( count / 3 );
  9961. break;
  9962. case 1:
  9963. render.lines += instanceCount * ( count / 2 );
  9964. break;
  9965. case 3:
  9966. render.lines += instanceCount * ( count - 1 );
  9967. break;
  9968. case 2:
  9969. render.lines += instanceCount * count;
  9970. break;
  9971. case 0:
  9972. render.points += instanceCount * count;
  9973. break;
  9974. default:
  9975. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9976. break;
  9977. }
  9978. }
  9979. function reset() {
  9980. render.frame ++;
  9981. render.calls = 0;
  9982. render.triangles = 0;
  9983. render.points = 0;
  9984. render.lines = 0;
  9985. }
  9986. return {
  9987. memory: memory,
  9988. render: render,
  9989. programs: null,
  9990. autoReset: true,
  9991. reset: reset,
  9992. update: update
  9993. };
  9994. }
  9995. function numericalSort( a, b ) {
  9996. return a[ 0 ] - b[ 0 ];
  9997. }
  9998. function absNumericalSort( a, b ) {
  9999. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10000. }
  10001. function WebGLMorphtargets( gl, capabilities, textures ) {
  10002. const influencesList = {};
  10003. const morphInfluences = new Float32Array( 8 );
  10004. const morphTextures = new WeakMap();
  10005. const morph = new Vector4();
  10006. const workInfluences = [];
  10007. for ( let i = 0; i < 8; i ++ ) {
  10008. workInfluences[ i ] = [ i, 0 ];
  10009. }
  10010. function update( object, geometry, material, program ) {
  10011. const objectInfluences = object.morphTargetInfluences;
  10012. if ( capabilities.isWebGL2 === true ) {
  10013. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10014. // into an array of data textures. Each layer represents a single morph target.
  10015. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10016. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10017. let entry = morphTextures.get( geometry );
  10018. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10019. if ( entry !== undefined ) entry.texture.dispose();
  10020. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10021. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10022. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10023. const morphTargets = geometry.morphAttributes.position || [];
  10024. const morphNormals = geometry.morphAttributes.normal || [];
  10025. const morphColors = geometry.morphAttributes.color || [];
  10026. let vertexDataCount = 0;
  10027. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10028. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10029. if ( hasMorphColors === true ) vertexDataCount = 3;
  10030. let width = geometry.attributes.position.count * vertexDataCount;
  10031. let height = 1;
  10032. if ( width > capabilities.maxTextureSize ) {
  10033. height = Math.ceil( width / capabilities.maxTextureSize );
  10034. width = capabilities.maxTextureSize;
  10035. }
  10036. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10037. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10038. texture.type = FloatType;
  10039. texture.needsUpdate = true;
  10040. // fill buffer
  10041. const vertexDataStride = vertexDataCount * 4;
  10042. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10043. const morphTarget = morphTargets[ i ];
  10044. const morphNormal = morphNormals[ i ];
  10045. const morphColor = morphColors[ i ];
  10046. const offset = width * height * 4 * i;
  10047. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10048. const stride = j * vertexDataStride;
  10049. if ( hasMorphPosition === true ) {
  10050. morph.fromBufferAttribute( morphTarget, j );
  10051. buffer[ offset + stride + 0 ] = morph.x;
  10052. buffer[ offset + stride + 1 ] = morph.y;
  10053. buffer[ offset + stride + 2 ] = morph.z;
  10054. buffer[ offset + stride + 3 ] = 0;
  10055. }
  10056. if ( hasMorphNormals === true ) {
  10057. morph.fromBufferAttribute( morphNormal, j );
  10058. buffer[ offset + stride + 4 ] = morph.x;
  10059. buffer[ offset + stride + 5 ] = morph.y;
  10060. buffer[ offset + stride + 6 ] = morph.z;
  10061. buffer[ offset + stride + 7 ] = 0;
  10062. }
  10063. if ( hasMorphColors === true ) {
  10064. morph.fromBufferAttribute( morphColor, j );
  10065. buffer[ offset + stride + 8 ] = morph.x;
  10066. buffer[ offset + stride + 9 ] = morph.y;
  10067. buffer[ offset + stride + 10 ] = morph.z;
  10068. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10069. }
  10070. }
  10071. }
  10072. entry = {
  10073. count: morphTargetsCount,
  10074. texture: texture,
  10075. size: new Vector2( width, height )
  10076. };
  10077. morphTextures.set( geometry, entry );
  10078. function disposeTexture() {
  10079. texture.dispose();
  10080. morphTextures.delete( geometry );
  10081. geometry.removeEventListener( 'dispose', disposeTexture );
  10082. }
  10083. geometry.addEventListener( 'dispose', disposeTexture );
  10084. }
  10085. //
  10086. let morphInfluencesSum = 0;
  10087. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10088. morphInfluencesSum += objectInfluences[ i ];
  10089. }
  10090. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10091. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10092. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10093. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10094. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10095. } else {
  10096. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10097. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10098. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10099. let influences = influencesList[ geometry.id ];
  10100. if ( influences === undefined || influences.length !== length ) {
  10101. // initialise list
  10102. influences = [];
  10103. for ( let i = 0; i < length; i ++ ) {
  10104. influences[ i ] = [ i, 0 ];
  10105. }
  10106. influencesList[ geometry.id ] = influences;
  10107. }
  10108. // Collect influences
  10109. for ( let i = 0; i < length; i ++ ) {
  10110. const influence = influences[ i ];
  10111. influence[ 0 ] = i;
  10112. influence[ 1 ] = objectInfluences[ i ];
  10113. }
  10114. influences.sort( absNumericalSort );
  10115. for ( let i = 0; i < 8; i ++ ) {
  10116. if ( i < length && influences[ i ][ 1 ] ) {
  10117. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10118. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10119. } else {
  10120. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10121. workInfluences[ i ][ 1 ] = 0;
  10122. }
  10123. }
  10124. workInfluences.sort( numericalSort );
  10125. const morphTargets = geometry.morphAttributes.position;
  10126. const morphNormals = geometry.morphAttributes.normal;
  10127. let morphInfluencesSum = 0;
  10128. for ( let i = 0; i < 8; i ++ ) {
  10129. const influence = workInfluences[ i ];
  10130. const index = influence[ 0 ];
  10131. const value = influence[ 1 ];
  10132. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10133. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10134. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10135. }
  10136. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10137. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10138. }
  10139. morphInfluences[ i ] = value;
  10140. morphInfluencesSum += value;
  10141. } else {
  10142. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10143. geometry.deleteAttribute( 'morphTarget' + i );
  10144. }
  10145. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10146. geometry.deleteAttribute( 'morphNormal' + i );
  10147. }
  10148. morphInfluences[ i ] = 0;
  10149. }
  10150. }
  10151. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10152. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10153. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10154. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10155. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10156. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10157. }
  10158. }
  10159. return {
  10160. update: update
  10161. };
  10162. }
  10163. function WebGLObjects( gl, geometries, attributes, info ) {
  10164. let updateMap = new WeakMap();
  10165. function update( object ) {
  10166. const frame = info.render.frame;
  10167. const geometry = object.geometry;
  10168. const buffergeometry = geometries.get( object, geometry );
  10169. // Update once per frame
  10170. if ( updateMap.get( buffergeometry ) !== frame ) {
  10171. geometries.update( buffergeometry );
  10172. updateMap.set( buffergeometry, frame );
  10173. }
  10174. if ( object.isInstancedMesh ) {
  10175. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10176. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10177. }
  10178. attributes.update( object.instanceMatrix, 34962 );
  10179. if ( object.instanceColor !== null ) {
  10180. attributes.update( object.instanceColor, 34962 );
  10181. }
  10182. }
  10183. return buffergeometry;
  10184. }
  10185. function dispose() {
  10186. updateMap = new WeakMap();
  10187. }
  10188. function onInstancedMeshDispose( event ) {
  10189. const instancedMesh = event.target;
  10190. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10191. attributes.remove( instancedMesh.instanceMatrix );
  10192. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10193. }
  10194. return {
  10195. update: update,
  10196. dispose: dispose
  10197. };
  10198. }
  10199. /**
  10200. * Uniforms of a program.
  10201. * Those form a tree structure with a special top-level container for the root,
  10202. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10203. *
  10204. *
  10205. * Properties of inner nodes including the top-level container:
  10206. *
  10207. * .seq - array of nested uniforms
  10208. * .map - nested uniforms by name
  10209. *
  10210. *
  10211. * Methods of all nodes except the top-level container:
  10212. *
  10213. * .setValue( gl, value, [textures] )
  10214. *
  10215. * uploads a uniform value(s)
  10216. * the 'textures' parameter is needed for sampler uniforms
  10217. *
  10218. *
  10219. * Static methods of the top-level container (textures factorizations):
  10220. *
  10221. * .upload( gl, seq, values, textures )
  10222. *
  10223. * sets uniforms in 'seq' to 'values[id].value'
  10224. *
  10225. * .seqWithValue( seq, values ) : filteredSeq
  10226. *
  10227. * filters 'seq' entries with corresponding entry in values
  10228. *
  10229. *
  10230. * Methods of the top-level container (textures factorizations):
  10231. *
  10232. * .setValue( gl, name, value, textures )
  10233. *
  10234. * sets uniform with name 'name' to 'value'
  10235. *
  10236. * .setOptional( gl, obj, prop )
  10237. *
  10238. * like .set for an optional property of the object
  10239. *
  10240. */
  10241. const emptyTexture = /*@__PURE__*/ new Texture();
  10242. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10243. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10244. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10245. // --- Utilities ---
  10246. // Array Caches (provide typed arrays for temporary by size)
  10247. const arrayCacheF32 = [];
  10248. const arrayCacheI32 = [];
  10249. // Float32Array caches used for uploading Matrix uniforms
  10250. const mat4array = new Float32Array( 16 );
  10251. const mat3array = new Float32Array( 9 );
  10252. const mat2array = new Float32Array( 4 );
  10253. // Flattening for arrays of vectors and matrices
  10254. function flatten( array, nBlocks, blockSize ) {
  10255. const firstElem = array[ 0 ];
  10256. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10257. // unoptimized: ! isNaN( firstElem )
  10258. // see http://jacksondunstan.com/articles/983
  10259. const n = nBlocks * blockSize;
  10260. let r = arrayCacheF32[ n ];
  10261. if ( r === undefined ) {
  10262. r = new Float32Array( n );
  10263. arrayCacheF32[ n ] = r;
  10264. }
  10265. if ( nBlocks !== 0 ) {
  10266. firstElem.toArray( r, 0 );
  10267. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10268. offset += blockSize;
  10269. array[ i ].toArray( r, offset );
  10270. }
  10271. }
  10272. return r;
  10273. }
  10274. function arraysEqual( a, b ) {
  10275. if ( a.length !== b.length ) return false;
  10276. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10277. if ( a[ i ] !== b[ i ] ) return false;
  10278. }
  10279. return true;
  10280. }
  10281. function copyArray( a, b ) {
  10282. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10283. a[ i ] = b[ i ];
  10284. }
  10285. }
  10286. // Texture unit allocation
  10287. function allocTexUnits( textures, n ) {
  10288. let r = arrayCacheI32[ n ];
  10289. if ( r === undefined ) {
  10290. r = new Int32Array( n );
  10291. arrayCacheI32[ n ] = r;
  10292. }
  10293. for ( let i = 0; i !== n; ++ i ) {
  10294. r[ i ] = textures.allocateTextureUnit();
  10295. }
  10296. return r;
  10297. }
  10298. // --- Setters ---
  10299. // Note: Defining these methods externally, because they come in a bunch
  10300. // and this way their names minify.
  10301. // Single scalar
  10302. function setValueV1f( gl, v ) {
  10303. const cache = this.cache;
  10304. if ( cache[ 0 ] === v ) return;
  10305. gl.uniform1f( this.addr, v );
  10306. cache[ 0 ] = v;
  10307. }
  10308. // Single float vector (from flat array or THREE.VectorN)
  10309. function setValueV2f( gl, v ) {
  10310. const cache = this.cache;
  10311. if ( v.x !== undefined ) {
  10312. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10313. gl.uniform2f( this.addr, v.x, v.y );
  10314. cache[ 0 ] = v.x;
  10315. cache[ 1 ] = v.y;
  10316. }
  10317. } else {
  10318. if ( arraysEqual( cache, v ) ) return;
  10319. gl.uniform2fv( this.addr, v );
  10320. copyArray( cache, v );
  10321. }
  10322. }
  10323. function setValueV3f( gl, v ) {
  10324. const cache = this.cache;
  10325. if ( v.x !== undefined ) {
  10326. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10327. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10328. cache[ 0 ] = v.x;
  10329. cache[ 1 ] = v.y;
  10330. cache[ 2 ] = v.z;
  10331. }
  10332. } else if ( v.r !== undefined ) {
  10333. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10334. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10335. cache[ 0 ] = v.r;
  10336. cache[ 1 ] = v.g;
  10337. cache[ 2 ] = v.b;
  10338. }
  10339. } else {
  10340. if ( arraysEqual( cache, v ) ) return;
  10341. gl.uniform3fv( this.addr, v );
  10342. copyArray( cache, v );
  10343. }
  10344. }
  10345. function setValueV4f( gl, v ) {
  10346. const cache = this.cache;
  10347. if ( v.x !== undefined ) {
  10348. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10349. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10350. cache[ 0 ] = v.x;
  10351. cache[ 1 ] = v.y;
  10352. cache[ 2 ] = v.z;
  10353. cache[ 3 ] = v.w;
  10354. }
  10355. } else {
  10356. if ( arraysEqual( cache, v ) ) return;
  10357. gl.uniform4fv( this.addr, v );
  10358. copyArray( cache, v );
  10359. }
  10360. }
  10361. // Single matrix (from flat array or THREE.MatrixN)
  10362. function setValueM2( gl, v ) {
  10363. const cache = this.cache;
  10364. const elements = v.elements;
  10365. if ( elements === undefined ) {
  10366. if ( arraysEqual( cache, v ) ) return;
  10367. gl.uniformMatrix2fv( this.addr, false, v );
  10368. copyArray( cache, v );
  10369. } else {
  10370. if ( arraysEqual( cache, elements ) ) return;
  10371. mat2array.set( elements );
  10372. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10373. copyArray( cache, elements );
  10374. }
  10375. }
  10376. function setValueM3( gl, v ) {
  10377. const cache = this.cache;
  10378. const elements = v.elements;
  10379. if ( elements === undefined ) {
  10380. if ( arraysEqual( cache, v ) ) return;
  10381. gl.uniformMatrix3fv( this.addr, false, v );
  10382. copyArray( cache, v );
  10383. } else {
  10384. if ( arraysEqual( cache, elements ) ) return;
  10385. mat3array.set( elements );
  10386. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10387. copyArray( cache, elements );
  10388. }
  10389. }
  10390. function setValueM4( gl, v ) {
  10391. const cache = this.cache;
  10392. const elements = v.elements;
  10393. if ( elements === undefined ) {
  10394. if ( arraysEqual( cache, v ) ) return;
  10395. gl.uniformMatrix4fv( this.addr, false, v );
  10396. copyArray( cache, v );
  10397. } else {
  10398. if ( arraysEqual( cache, elements ) ) return;
  10399. mat4array.set( elements );
  10400. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10401. copyArray( cache, elements );
  10402. }
  10403. }
  10404. // Single integer / boolean
  10405. function setValueV1i( gl, v ) {
  10406. const cache = this.cache;
  10407. if ( cache[ 0 ] === v ) return;
  10408. gl.uniform1i( this.addr, v );
  10409. cache[ 0 ] = v;
  10410. }
  10411. // Single integer / boolean vector (from flat array)
  10412. function setValueV2i( gl, v ) {
  10413. const cache = this.cache;
  10414. if ( arraysEqual( cache, v ) ) return;
  10415. gl.uniform2iv( this.addr, v );
  10416. copyArray( cache, v );
  10417. }
  10418. function setValueV3i( gl, v ) {
  10419. const cache = this.cache;
  10420. if ( arraysEqual( cache, v ) ) return;
  10421. gl.uniform3iv( this.addr, v );
  10422. copyArray( cache, v );
  10423. }
  10424. function setValueV4i( gl, v ) {
  10425. const cache = this.cache;
  10426. if ( arraysEqual( cache, v ) ) return;
  10427. gl.uniform4iv( this.addr, v );
  10428. copyArray( cache, v );
  10429. }
  10430. // Single unsigned integer
  10431. function setValueV1ui( gl, v ) {
  10432. const cache = this.cache;
  10433. if ( cache[ 0 ] === v ) return;
  10434. gl.uniform1ui( this.addr, v );
  10435. cache[ 0 ] = v;
  10436. }
  10437. // Single unsigned integer vector (from flat array)
  10438. function setValueV2ui( gl, v ) {
  10439. const cache = this.cache;
  10440. if ( arraysEqual( cache, v ) ) return;
  10441. gl.uniform2uiv( this.addr, v );
  10442. copyArray( cache, v );
  10443. }
  10444. function setValueV3ui( gl, v ) {
  10445. const cache = this.cache;
  10446. if ( arraysEqual( cache, v ) ) return;
  10447. gl.uniform3uiv( this.addr, v );
  10448. copyArray( cache, v );
  10449. }
  10450. function setValueV4ui( gl, v ) {
  10451. const cache = this.cache;
  10452. if ( arraysEqual( cache, v ) ) return;
  10453. gl.uniform4uiv( this.addr, v );
  10454. copyArray( cache, v );
  10455. }
  10456. // Single texture (2D / Cube)
  10457. function setValueT1( gl, v, textures ) {
  10458. const cache = this.cache;
  10459. const unit = textures.allocateTextureUnit();
  10460. if ( cache[ 0 ] !== unit ) {
  10461. gl.uniform1i( this.addr, unit );
  10462. cache[ 0 ] = unit;
  10463. }
  10464. textures.setTexture2D( v || emptyTexture, unit );
  10465. }
  10466. function setValueT3D1( gl, v, textures ) {
  10467. const cache = this.cache;
  10468. const unit = textures.allocateTextureUnit();
  10469. if ( cache[ 0 ] !== unit ) {
  10470. gl.uniform1i( this.addr, unit );
  10471. cache[ 0 ] = unit;
  10472. }
  10473. textures.setTexture3D( v || empty3dTexture, unit );
  10474. }
  10475. function setValueT6( gl, v, textures ) {
  10476. const cache = this.cache;
  10477. const unit = textures.allocateTextureUnit();
  10478. if ( cache[ 0 ] !== unit ) {
  10479. gl.uniform1i( this.addr, unit );
  10480. cache[ 0 ] = unit;
  10481. }
  10482. textures.setTextureCube( v || emptyCubeTexture, unit );
  10483. }
  10484. function setValueT2DArray1( gl, v, textures ) {
  10485. const cache = this.cache;
  10486. const unit = textures.allocateTextureUnit();
  10487. if ( cache[ 0 ] !== unit ) {
  10488. gl.uniform1i( this.addr, unit );
  10489. cache[ 0 ] = unit;
  10490. }
  10491. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10492. }
  10493. // Helper to pick the right setter for the singular case
  10494. function getSingularSetter( type ) {
  10495. switch ( type ) {
  10496. case 0x1406: return setValueV1f; // FLOAT
  10497. case 0x8b50: return setValueV2f; // _VEC2
  10498. case 0x8b51: return setValueV3f; // _VEC3
  10499. case 0x8b52: return setValueV4f; // _VEC4
  10500. case 0x8b5a: return setValueM2; // _MAT2
  10501. case 0x8b5b: return setValueM3; // _MAT3
  10502. case 0x8b5c: return setValueM4; // _MAT4
  10503. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10504. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10505. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10506. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10507. case 0x1405: return setValueV1ui; // UINT
  10508. case 0x8dc6: return setValueV2ui; // _VEC2
  10509. case 0x8dc7: return setValueV3ui; // _VEC3
  10510. case 0x8dc8: return setValueV4ui; // _VEC4
  10511. case 0x8b5e: // SAMPLER_2D
  10512. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10513. case 0x8dca: // INT_SAMPLER_2D
  10514. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10515. case 0x8b62: // SAMPLER_2D_SHADOW
  10516. return setValueT1;
  10517. case 0x8b5f: // SAMPLER_3D
  10518. case 0x8dcb: // INT_SAMPLER_3D
  10519. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10520. return setValueT3D1;
  10521. case 0x8b60: // SAMPLER_CUBE
  10522. case 0x8dcc: // INT_SAMPLER_CUBE
  10523. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10524. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10525. return setValueT6;
  10526. case 0x8dc1: // SAMPLER_2D_ARRAY
  10527. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10528. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10529. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10530. return setValueT2DArray1;
  10531. }
  10532. }
  10533. // Array of scalars
  10534. function setValueV1fArray( gl, v ) {
  10535. gl.uniform1fv( this.addr, v );
  10536. }
  10537. // Array of vectors (from flat array or array of THREE.VectorN)
  10538. function setValueV2fArray( gl, v ) {
  10539. const data = flatten( v, this.size, 2 );
  10540. gl.uniform2fv( this.addr, data );
  10541. }
  10542. function setValueV3fArray( gl, v ) {
  10543. const data = flatten( v, this.size, 3 );
  10544. gl.uniform3fv( this.addr, data );
  10545. }
  10546. function setValueV4fArray( gl, v ) {
  10547. const data = flatten( v, this.size, 4 );
  10548. gl.uniform4fv( this.addr, data );
  10549. }
  10550. // Array of matrices (from flat array or array of THREE.MatrixN)
  10551. function setValueM2Array( gl, v ) {
  10552. const data = flatten( v, this.size, 4 );
  10553. gl.uniformMatrix2fv( this.addr, false, data );
  10554. }
  10555. function setValueM3Array( gl, v ) {
  10556. const data = flatten( v, this.size, 9 );
  10557. gl.uniformMatrix3fv( this.addr, false, data );
  10558. }
  10559. function setValueM4Array( gl, v ) {
  10560. const data = flatten( v, this.size, 16 );
  10561. gl.uniformMatrix4fv( this.addr, false, data );
  10562. }
  10563. // Array of integer / boolean
  10564. function setValueV1iArray( gl, v ) {
  10565. gl.uniform1iv( this.addr, v );
  10566. }
  10567. // Array of integer / boolean vectors (from flat array)
  10568. function setValueV2iArray( gl, v ) {
  10569. gl.uniform2iv( this.addr, v );
  10570. }
  10571. function setValueV3iArray( gl, v ) {
  10572. gl.uniform3iv( this.addr, v );
  10573. }
  10574. function setValueV4iArray( gl, v ) {
  10575. gl.uniform4iv( this.addr, v );
  10576. }
  10577. // Array of unsigned integer
  10578. function setValueV1uiArray( gl, v ) {
  10579. gl.uniform1uiv( this.addr, v );
  10580. }
  10581. // Array of unsigned integer vectors (from flat array)
  10582. function setValueV2uiArray( gl, v ) {
  10583. gl.uniform2uiv( this.addr, v );
  10584. }
  10585. function setValueV3uiArray( gl, v ) {
  10586. gl.uniform3uiv( this.addr, v );
  10587. }
  10588. function setValueV4uiArray( gl, v ) {
  10589. gl.uniform4uiv( this.addr, v );
  10590. }
  10591. // Array of textures (2D / 3D / Cube / 2DArray)
  10592. function setValueT1Array( gl, v, textures ) {
  10593. const cache = this.cache;
  10594. const n = v.length;
  10595. const units = allocTexUnits( textures, n );
  10596. if ( ! arraysEqual( cache, units ) ) {
  10597. gl.uniform1iv( this.addr, units );
  10598. copyArray( cache, units );
  10599. }
  10600. for ( let i = 0; i !== n; ++ i ) {
  10601. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10602. }
  10603. }
  10604. function setValueT3DArray( gl, v, textures ) {
  10605. const cache = this.cache;
  10606. const n = v.length;
  10607. const units = allocTexUnits( textures, n );
  10608. if ( ! arraysEqual( cache, units ) ) {
  10609. gl.uniform1iv( this.addr, units );
  10610. copyArray( cache, units );
  10611. }
  10612. for ( let i = 0; i !== n; ++ i ) {
  10613. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10614. }
  10615. }
  10616. function setValueT6Array( gl, v, textures ) {
  10617. const cache = this.cache;
  10618. const n = v.length;
  10619. const units = allocTexUnits( textures, n );
  10620. if ( ! arraysEqual( cache, units ) ) {
  10621. gl.uniform1iv( this.addr, units );
  10622. copyArray( cache, units );
  10623. }
  10624. for ( let i = 0; i !== n; ++ i ) {
  10625. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10626. }
  10627. }
  10628. function setValueT2DArrayArray( gl, v, textures ) {
  10629. const cache = this.cache;
  10630. const n = v.length;
  10631. const units = allocTexUnits( textures, n );
  10632. if ( ! arraysEqual( cache, units ) ) {
  10633. gl.uniform1iv( this.addr, units );
  10634. copyArray( cache, units );
  10635. }
  10636. for ( let i = 0; i !== n; ++ i ) {
  10637. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10638. }
  10639. }
  10640. // Helper to pick the right setter for a pure (bottom-level) array
  10641. function getPureArraySetter( type ) {
  10642. switch ( type ) {
  10643. case 0x1406: return setValueV1fArray; // FLOAT
  10644. case 0x8b50: return setValueV2fArray; // _VEC2
  10645. case 0x8b51: return setValueV3fArray; // _VEC3
  10646. case 0x8b52: return setValueV4fArray; // _VEC4
  10647. case 0x8b5a: return setValueM2Array; // _MAT2
  10648. case 0x8b5b: return setValueM3Array; // _MAT3
  10649. case 0x8b5c: return setValueM4Array; // _MAT4
  10650. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10651. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10652. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10653. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10654. case 0x1405: return setValueV1uiArray; // UINT
  10655. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10656. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10657. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10658. case 0x8b5e: // SAMPLER_2D
  10659. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10660. case 0x8dca: // INT_SAMPLER_2D
  10661. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10662. case 0x8b62: // SAMPLER_2D_SHADOW
  10663. return setValueT1Array;
  10664. case 0x8b5f: // SAMPLER_3D
  10665. case 0x8dcb: // INT_SAMPLER_3D
  10666. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10667. return setValueT3DArray;
  10668. case 0x8b60: // SAMPLER_CUBE
  10669. case 0x8dcc: // INT_SAMPLER_CUBE
  10670. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10671. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10672. return setValueT6Array;
  10673. case 0x8dc1: // SAMPLER_2D_ARRAY
  10674. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10675. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10676. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10677. return setValueT2DArrayArray;
  10678. }
  10679. }
  10680. // --- Uniform Classes ---
  10681. class SingleUniform {
  10682. constructor( id, activeInfo, addr ) {
  10683. this.id = id;
  10684. this.addr = addr;
  10685. this.cache = [];
  10686. this.setValue = getSingularSetter( activeInfo.type );
  10687. // this.path = activeInfo.name; // DEBUG
  10688. }
  10689. }
  10690. class PureArrayUniform {
  10691. constructor( id, activeInfo, addr ) {
  10692. this.id = id;
  10693. this.addr = addr;
  10694. this.cache = [];
  10695. this.size = activeInfo.size;
  10696. this.setValue = getPureArraySetter( activeInfo.type );
  10697. // this.path = activeInfo.name; // DEBUG
  10698. }
  10699. }
  10700. class StructuredUniform {
  10701. constructor( id ) {
  10702. this.id = id;
  10703. this.seq = [];
  10704. this.map = {};
  10705. }
  10706. setValue( gl, value, textures ) {
  10707. const seq = this.seq;
  10708. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10709. const u = seq[ i ];
  10710. u.setValue( gl, value[ u.id ], textures );
  10711. }
  10712. }
  10713. }
  10714. // --- Top-level ---
  10715. // Parser - builds up the property tree from the path strings
  10716. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10717. // extracts
  10718. // - the identifier (member name or array index)
  10719. // - followed by an optional right bracket (found when array index)
  10720. // - followed by an optional left bracket or dot (type of subscript)
  10721. //
  10722. // Note: These portions can be read in a non-overlapping fashion and
  10723. // allow straightforward parsing of the hierarchy that WebGL encodes
  10724. // in the uniform names.
  10725. function addUniform( container, uniformObject ) {
  10726. container.seq.push( uniformObject );
  10727. container.map[ uniformObject.id ] = uniformObject;
  10728. }
  10729. function parseUniform( activeInfo, addr, container ) {
  10730. const path = activeInfo.name,
  10731. pathLength = path.length;
  10732. // reset RegExp object, because of the early exit of a previous run
  10733. RePathPart.lastIndex = 0;
  10734. while ( true ) {
  10735. const match = RePathPart.exec( path ),
  10736. matchEnd = RePathPart.lastIndex;
  10737. let id = match[ 1 ];
  10738. const idIsIndex = match[ 2 ] === ']',
  10739. subscript = match[ 3 ];
  10740. if ( idIsIndex ) id = id | 0; // convert to integer
  10741. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10742. // bare name or "pure" bottom-level array "[0]" suffix
  10743. addUniform( container, subscript === undefined ?
  10744. new SingleUniform( id, activeInfo, addr ) :
  10745. new PureArrayUniform( id, activeInfo, addr ) );
  10746. break;
  10747. } else {
  10748. // step into inner node / create it in case it doesn't exist
  10749. const map = container.map;
  10750. let next = map[ id ];
  10751. if ( next === undefined ) {
  10752. next = new StructuredUniform( id );
  10753. addUniform( container, next );
  10754. }
  10755. container = next;
  10756. }
  10757. }
  10758. }
  10759. // Root Container
  10760. class WebGLUniforms {
  10761. constructor( gl, program ) {
  10762. this.seq = [];
  10763. this.map = {};
  10764. const n = gl.getProgramParameter( program, 35718 );
  10765. for ( let i = 0; i < n; ++ i ) {
  10766. const info = gl.getActiveUniform( program, i ),
  10767. addr = gl.getUniformLocation( program, info.name );
  10768. parseUniform( info, addr, this );
  10769. }
  10770. }
  10771. setValue( gl, name, value, textures ) {
  10772. const u = this.map[ name ];
  10773. if ( u !== undefined ) u.setValue( gl, value, textures );
  10774. }
  10775. setOptional( gl, object, name ) {
  10776. const v = object[ name ];
  10777. if ( v !== undefined ) this.setValue( gl, name, v );
  10778. }
  10779. static upload( gl, seq, values, textures ) {
  10780. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10781. const u = seq[ i ],
  10782. v = values[ u.id ];
  10783. if ( v.needsUpdate !== false ) {
  10784. // note: always updating when .needsUpdate is undefined
  10785. u.setValue( gl, v.value, textures );
  10786. }
  10787. }
  10788. }
  10789. static seqWithValue( seq, values ) {
  10790. const r = [];
  10791. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10792. const u = seq[ i ];
  10793. if ( u.id in values ) r.push( u );
  10794. }
  10795. return r;
  10796. }
  10797. }
  10798. function WebGLShader( gl, type, string ) {
  10799. const shader = gl.createShader( type );
  10800. gl.shaderSource( shader, string );
  10801. gl.compileShader( shader );
  10802. return shader;
  10803. }
  10804. let programIdCount = 0;
  10805. function handleSource( string, errorLine ) {
  10806. const lines = string.split( '\n' );
  10807. const lines2 = [];
  10808. const from = Math.max( errorLine - 6, 0 );
  10809. const to = Math.min( errorLine + 6, lines.length );
  10810. for ( let i = from; i < to; i ++ ) {
  10811. const line = i + 1;
  10812. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10813. }
  10814. return lines2.join( '\n' );
  10815. }
  10816. function getEncodingComponents( encoding ) {
  10817. switch ( encoding ) {
  10818. case LinearEncoding:
  10819. return [ 'Linear', '( value )' ];
  10820. case sRGBEncoding:
  10821. return [ 'sRGB', '( value )' ];
  10822. default:
  10823. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10824. return [ 'Linear', '( value )' ];
  10825. }
  10826. }
  10827. function getShaderErrors( gl, shader, type ) {
  10828. const status = gl.getShaderParameter( shader, 35713 );
  10829. const errors = gl.getShaderInfoLog( shader ).trim();
  10830. if ( status && errors === '' ) return '';
  10831. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10832. if ( errorMatches ) {
  10833. // --enable-privileged-webgl-extension
  10834. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10835. const errorLine = parseInt( errorMatches[ 1 ] );
  10836. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10837. } else {
  10838. return errors;
  10839. }
  10840. }
  10841. function getTexelEncodingFunction( functionName, encoding ) {
  10842. const components = getEncodingComponents( encoding );
  10843. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10844. }
  10845. function getToneMappingFunction( functionName, toneMapping ) {
  10846. let toneMappingName;
  10847. switch ( toneMapping ) {
  10848. case LinearToneMapping:
  10849. toneMappingName = 'Linear';
  10850. break;
  10851. case ReinhardToneMapping:
  10852. toneMappingName = 'Reinhard';
  10853. break;
  10854. case CineonToneMapping:
  10855. toneMappingName = 'OptimizedCineon';
  10856. break;
  10857. case ACESFilmicToneMapping:
  10858. toneMappingName = 'ACESFilmic';
  10859. break;
  10860. case CustomToneMapping:
  10861. toneMappingName = 'Custom';
  10862. break;
  10863. default:
  10864. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10865. toneMappingName = 'Linear';
  10866. }
  10867. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10868. }
  10869. function generateExtensions( parameters ) {
  10870. const chunks = [
  10871. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10872. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10873. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10874. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10875. ];
  10876. return chunks.filter( filterEmptyLine ).join( '\n' );
  10877. }
  10878. function generateDefines( defines ) {
  10879. const chunks = [];
  10880. for ( const name in defines ) {
  10881. const value = defines[ name ];
  10882. if ( value === false ) continue;
  10883. chunks.push( '#define ' + name + ' ' + value );
  10884. }
  10885. return chunks.join( '\n' );
  10886. }
  10887. function fetchAttributeLocations( gl, program ) {
  10888. const attributes = {};
  10889. const n = gl.getProgramParameter( program, 35721 );
  10890. for ( let i = 0; i < n; i ++ ) {
  10891. const info = gl.getActiveAttrib( program, i );
  10892. const name = info.name;
  10893. let locationSize = 1;
  10894. if ( info.type === 35674 ) locationSize = 2;
  10895. if ( info.type === 35675 ) locationSize = 3;
  10896. if ( info.type === 35676 ) locationSize = 4;
  10897. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10898. attributes[ name ] = {
  10899. type: info.type,
  10900. location: gl.getAttribLocation( program, name ),
  10901. locationSize: locationSize
  10902. };
  10903. }
  10904. return attributes;
  10905. }
  10906. function filterEmptyLine( string ) {
  10907. return string !== '';
  10908. }
  10909. function replaceLightNums( string, parameters ) {
  10910. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  10911. return string
  10912. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10913. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10914. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  10915. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  10916. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10917. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10918. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10919. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10920. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  10921. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10922. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10923. }
  10924. function replaceClippingPlaneNums( string, parameters ) {
  10925. return string
  10926. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10927. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10928. }
  10929. // Resolve Includes
  10930. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10931. function resolveIncludes( string ) {
  10932. return string.replace( includePattern, includeReplacer );
  10933. }
  10934. function includeReplacer( match, include ) {
  10935. const string = ShaderChunk[ include ];
  10936. if ( string === undefined ) {
  10937. throw new Error( 'Can not resolve #include <' + include + '>' );
  10938. }
  10939. return resolveIncludes( string );
  10940. }
  10941. // Unroll Loops
  10942. 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;
  10943. function unrollLoops( string ) {
  10944. return string.replace( unrollLoopPattern, loopReplacer );
  10945. }
  10946. function loopReplacer( match, start, end, snippet ) {
  10947. let string = '';
  10948. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10949. string += snippet
  10950. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10951. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10952. }
  10953. return string;
  10954. }
  10955. //
  10956. function generatePrecision( parameters ) {
  10957. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10958. if ( parameters.precision === 'highp' ) {
  10959. precisionstring += '\n#define HIGH_PRECISION';
  10960. } else if ( parameters.precision === 'mediump' ) {
  10961. precisionstring += '\n#define MEDIUM_PRECISION';
  10962. } else if ( parameters.precision === 'lowp' ) {
  10963. precisionstring += '\n#define LOW_PRECISION';
  10964. }
  10965. return precisionstring;
  10966. }
  10967. function generateShadowMapTypeDefine( parameters ) {
  10968. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10969. if ( parameters.shadowMapType === PCFShadowMap ) {
  10970. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10971. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10972. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10973. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10974. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10975. }
  10976. return shadowMapTypeDefine;
  10977. }
  10978. function generateEnvMapTypeDefine( parameters ) {
  10979. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10980. if ( parameters.envMap ) {
  10981. switch ( parameters.envMapMode ) {
  10982. case CubeReflectionMapping:
  10983. case CubeRefractionMapping:
  10984. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10985. break;
  10986. case CubeUVReflectionMapping:
  10987. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10988. break;
  10989. }
  10990. }
  10991. return envMapTypeDefine;
  10992. }
  10993. function generateEnvMapModeDefine( parameters ) {
  10994. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10995. if ( parameters.envMap ) {
  10996. switch ( parameters.envMapMode ) {
  10997. case CubeRefractionMapping:
  10998. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10999. break;
  11000. }
  11001. }
  11002. return envMapModeDefine;
  11003. }
  11004. function generateEnvMapBlendingDefine( parameters ) {
  11005. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11006. if ( parameters.envMap ) {
  11007. switch ( parameters.combine ) {
  11008. case MultiplyOperation:
  11009. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11010. break;
  11011. case MixOperation:
  11012. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11013. break;
  11014. case AddOperation:
  11015. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11016. break;
  11017. }
  11018. }
  11019. return envMapBlendingDefine;
  11020. }
  11021. function generateCubeUVSize( parameters ) {
  11022. const imageHeight = parameters.envMapCubeUVHeight;
  11023. if ( imageHeight === null ) return null;
  11024. const maxMip = Math.log2( imageHeight ) - 2;
  11025. const texelHeight = 1.0 / imageHeight;
  11026. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11027. return { texelWidth, texelHeight, maxMip };
  11028. }
  11029. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11030. // TODO Send this event to Three.js DevTools
  11031. // console.log( 'WebGLProgram', cacheKey );
  11032. const gl = renderer.getContext();
  11033. const defines = parameters.defines;
  11034. let vertexShader = parameters.vertexShader;
  11035. let fragmentShader = parameters.fragmentShader;
  11036. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11037. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11038. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11039. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11040. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11041. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11042. const customDefines = generateDefines( defines );
  11043. const program = gl.createProgram();
  11044. let prefixVertex, prefixFragment;
  11045. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11046. if ( parameters.isRawShaderMaterial ) {
  11047. prefixVertex = [
  11048. customDefines
  11049. ].filter( filterEmptyLine ).join( '\n' );
  11050. if ( prefixVertex.length > 0 ) {
  11051. prefixVertex += '\n';
  11052. }
  11053. prefixFragment = [
  11054. customExtensions,
  11055. customDefines
  11056. ].filter( filterEmptyLine ).join( '\n' );
  11057. if ( prefixFragment.length > 0 ) {
  11058. prefixFragment += '\n';
  11059. }
  11060. } else {
  11061. prefixVertex = [
  11062. generatePrecision( parameters ),
  11063. '#define SHADER_NAME ' + parameters.shaderName,
  11064. customDefines,
  11065. parameters.instancing ? '#define USE_INSTANCING' : '',
  11066. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11067. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11068. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11069. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11070. parameters.map ? '#define USE_MAP' : '',
  11071. parameters.envMap ? '#define USE_ENVMAP' : '',
  11072. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11073. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11074. parameters.aoMap ? '#define USE_AOMAP' : '',
  11075. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11076. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11077. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11078. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11079. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11080. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11081. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11082. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11083. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11084. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11085. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11086. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11087. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11088. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11089. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11090. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11091. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11092. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11093. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11094. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11095. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11096. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11097. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11098. parameters.vertexColors ? '#define USE_COLOR' : '',
  11099. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11100. parameters.vertexUvs ? '#define USE_UV' : '',
  11101. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11102. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11103. parameters.skinning ? '#define USE_SKINNING' : '',
  11104. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11105. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11106. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11107. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11108. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11109. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11110. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11111. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11112. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11113. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11114. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11115. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11116. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11117. 'uniform mat4 modelMatrix;',
  11118. 'uniform mat4 modelViewMatrix;',
  11119. 'uniform mat4 projectionMatrix;',
  11120. 'uniform mat4 viewMatrix;',
  11121. 'uniform mat3 normalMatrix;',
  11122. 'uniform vec3 cameraPosition;',
  11123. 'uniform bool isOrthographic;',
  11124. '#ifdef USE_INSTANCING',
  11125. ' attribute mat4 instanceMatrix;',
  11126. '#endif',
  11127. '#ifdef USE_INSTANCING_COLOR',
  11128. ' attribute vec3 instanceColor;',
  11129. '#endif',
  11130. 'attribute vec3 position;',
  11131. 'attribute vec3 normal;',
  11132. 'attribute vec2 uv;',
  11133. '#ifdef USE_TANGENT',
  11134. ' attribute vec4 tangent;',
  11135. '#endif',
  11136. '#if defined( USE_COLOR_ALPHA )',
  11137. ' attribute vec4 color;',
  11138. '#elif defined( USE_COLOR )',
  11139. ' attribute vec3 color;',
  11140. '#endif',
  11141. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11142. ' attribute vec3 morphTarget0;',
  11143. ' attribute vec3 morphTarget1;',
  11144. ' attribute vec3 morphTarget2;',
  11145. ' attribute vec3 morphTarget3;',
  11146. ' #ifdef USE_MORPHNORMALS',
  11147. ' attribute vec3 morphNormal0;',
  11148. ' attribute vec3 morphNormal1;',
  11149. ' attribute vec3 morphNormal2;',
  11150. ' attribute vec3 morphNormal3;',
  11151. ' #else',
  11152. ' attribute vec3 morphTarget4;',
  11153. ' attribute vec3 morphTarget5;',
  11154. ' attribute vec3 morphTarget6;',
  11155. ' attribute vec3 morphTarget7;',
  11156. ' #endif',
  11157. '#endif',
  11158. '#ifdef USE_SKINNING',
  11159. ' attribute vec4 skinIndex;',
  11160. ' attribute vec4 skinWeight;',
  11161. '#endif',
  11162. '\n'
  11163. ].filter( filterEmptyLine ).join( '\n' );
  11164. prefixFragment = [
  11165. customExtensions,
  11166. generatePrecision( parameters ),
  11167. '#define SHADER_NAME ' + parameters.shaderName,
  11168. customDefines,
  11169. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11170. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11171. parameters.map ? '#define USE_MAP' : '',
  11172. parameters.matcap ? '#define USE_MATCAP' : '',
  11173. parameters.envMap ? '#define USE_ENVMAP' : '',
  11174. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11175. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11176. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11177. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11178. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11179. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  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.clearcoat ? '#define USE_CLEARCOAT' : '',
  11188. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11189. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11190. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11191. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11192. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11193. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11194. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11195. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11196. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11197. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11198. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11199. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11200. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11201. parameters.sheen ? '#define USE_SHEEN' : '',
  11202. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11203. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11204. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11205. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11206. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11207. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11208. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11209. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11210. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11211. parameters.vertexUvs ? '#define USE_UV' : '',
  11212. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11213. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11214. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11215. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11216. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11217. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11218. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11219. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11220. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11221. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11222. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11223. 'uniform mat4 viewMatrix;',
  11224. 'uniform vec3 cameraPosition;',
  11225. 'uniform bool isOrthographic;',
  11226. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11227. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11228. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11229. parameters.dithering ? '#define DITHERING' : '',
  11230. parameters.opaque ? '#define OPAQUE' : '',
  11231. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11232. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11233. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11234. '\n'
  11235. ].filter( filterEmptyLine ).join( '\n' );
  11236. }
  11237. vertexShader = resolveIncludes( vertexShader );
  11238. vertexShader = replaceLightNums( vertexShader, parameters );
  11239. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11240. fragmentShader = resolveIncludes( fragmentShader );
  11241. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11242. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11243. vertexShader = unrollLoops( vertexShader );
  11244. fragmentShader = unrollLoops( fragmentShader );
  11245. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11246. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11247. versionString = '#version 300 es\n';
  11248. prefixVertex = [
  11249. 'precision mediump sampler2DArray;',
  11250. '#define attribute in',
  11251. '#define varying out',
  11252. '#define texture2D texture'
  11253. ].join( '\n' ) + '\n' + prefixVertex;
  11254. prefixFragment = [
  11255. '#define varying in',
  11256. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11257. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11258. '#define gl_FragDepthEXT gl_FragDepth',
  11259. '#define texture2D texture',
  11260. '#define textureCube texture',
  11261. '#define texture2DProj textureProj',
  11262. '#define texture2DLodEXT textureLod',
  11263. '#define texture2DProjLodEXT textureProjLod',
  11264. '#define textureCubeLodEXT textureLod',
  11265. '#define texture2DGradEXT textureGrad',
  11266. '#define texture2DProjGradEXT textureProjGrad',
  11267. '#define textureCubeGradEXT textureGrad'
  11268. ].join( '\n' ) + '\n' + prefixFragment;
  11269. }
  11270. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11271. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11272. // console.log( '*VERTEX*', vertexGlsl );
  11273. // console.log( '*FRAGMENT*', fragmentGlsl );
  11274. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11275. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11276. gl.attachShader( program, glVertexShader );
  11277. gl.attachShader( program, glFragmentShader );
  11278. // Force a particular attribute to index 0.
  11279. if ( parameters.index0AttributeName !== undefined ) {
  11280. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11281. } else if ( parameters.morphTargets === true ) {
  11282. // programs with morphTargets displace position out of attribute 0
  11283. gl.bindAttribLocation( program, 0, 'position' );
  11284. }
  11285. gl.linkProgram( program );
  11286. // check for link errors
  11287. if ( renderer.debug.checkShaderErrors ) {
  11288. const programLog = gl.getProgramInfoLog( program ).trim();
  11289. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11290. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11291. let runnable = true;
  11292. let haveDiagnostics = true;
  11293. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11294. runnable = false;
  11295. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11296. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11297. console.error(
  11298. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11299. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11300. 'Program Info Log: ' + programLog + '\n' +
  11301. vertexErrors + '\n' +
  11302. fragmentErrors
  11303. );
  11304. } else if ( programLog !== '' ) {
  11305. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11306. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11307. haveDiagnostics = false;
  11308. }
  11309. if ( haveDiagnostics ) {
  11310. this.diagnostics = {
  11311. runnable: runnable,
  11312. programLog: programLog,
  11313. vertexShader: {
  11314. log: vertexLog,
  11315. prefix: prefixVertex
  11316. },
  11317. fragmentShader: {
  11318. log: fragmentLog,
  11319. prefix: prefixFragment
  11320. }
  11321. };
  11322. }
  11323. }
  11324. // Clean up
  11325. // Crashes in iOS9 and iOS10. #18402
  11326. // gl.detachShader( program, glVertexShader );
  11327. // gl.detachShader( program, glFragmentShader );
  11328. gl.deleteShader( glVertexShader );
  11329. gl.deleteShader( glFragmentShader );
  11330. // set up caching for uniform locations
  11331. let cachedUniforms;
  11332. this.getUniforms = function () {
  11333. if ( cachedUniforms === undefined ) {
  11334. cachedUniforms = new WebGLUniforms( gl, program );
  11335. }
  11336. return cachedUniforms;
  11337. };
  11338. // set up caching for attribute locations
  11339. let cachedAttributes;
  11340. this.getAttributes = function () {
  11341. if ( cachedAttributes === undefined ) {
  11342. cachedAttributes = fetchAttributeLocations( gl, program );
  11343. }
  11344. return cachedAttributes;
  11345. };
  11346. // free resource
  11347. this.destroy = function () {
  11348. bindingStates.releaseStatesOfProgram( this );
  11349. gl.deleteProgram( program );
  11350. this.program = undefined;
  11351. };
  11352. //
  11353. this.name = parameters.shaderName;
  11354. this.id = programIdCount ++;
  11355. this.cacheKey = cacheKey;
  11356. this.usedTimes = 1;
  11357. this.program = program;
  11358. this.vertexShader = glVertexShader;
  11359. this.fragmentShader = glFragmentShader;
  11360. return this;
  11361. }
  11362. let _id = 0;
  11363. class WebGLShaderCache {
  11364. constructor() {
  11365. this.shaderCache = new Map();
  11366. this.materialCache = new Map();
  11367. }
  11368. update( material ) {
  11369. const vertexShader = material.vertexShader;
  11370. const fragmentShader = material.fragmentShader;
  11371. const vertexShaderStage = this._getShaderStage( vertexShader );
  11372. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11373. const materialShaders = this._getShaderCacheForMaterial( material );
  11374. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11375. materialShaders.add( vertexShaderStage );
  11376. vertexShaderStage.usedTimes ++;
  11377. }
  11378. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11379. materialShaders.add( fragmentShaderStage );
  11380. fragmentShaderStage.usedTimes ++;
  11381. }
  11382. return this;
  11383. }
  11384. remove( material ) {
  11385. const materialShaders = this.materialCache.get( material );
  11386. for ( const shaderStage of materialShaders ) {
  11387. shaderStage.usedTimes --;
  11388. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11389. }
  11390. this.materialCache.delete( material );
  11391. return this;
  11392. }
  11393. getVertexShaderID( material ) {
  11394. return this._getShaderStage( material.vertexShader ).id;
  11395. }
  11396. getFragmentShaderID( material ) {
  11397. return this._getShaderStage( material.fragmentShader ).id;
  11398. }
  11399. dispose() {
  11400. this.shaderCache.clear();
  11401. this.materialCache.clear();
  11402. }
  11403. _getShaderCacheForMaterial( material ) {
  11404. const cache = this.materialCache;
  11405. let set = cache.get( material );
  11406. if ( set === undefined ) {
  11407. set = new Set();
  11408. cache.set( material, set );
  11409. }
  11410. return set;
  11411. }
  11412. _getShaderStage( code ) {
  11413. const cache = this.shaderCache;
  11414. let stage = cache.get( code );
  11415. if ( stage === undefined ) {
  11416. stage = new WebGLShaderStage( code );
  11417. cache.set( code, stage );
  11418. }
  11419. return stage;
  11420. }
  11421. }
  11422. class WebGLShaderStage {
  11423. constructor( code ) {
  11424. this.id = _id ++;
  11425. this.code = code;
  11426. this.usedTimes = 0;
  11427. }
  11428. }
  11429. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11430. const _programLayers = new Layers();
  11431. const _customShaders = new WebGLShaderCache();
  11432. const programs = [];
  11433. const isWebGL2 = capabilities.isWebGL2;
  11434. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11435. const vertexTextures = capabilities.vertexTextures;
  11436. let precision = capabilities.precision;
  11437. const shaderIDs = {
  11438. MeshDepthMaterial: 'depth',
  11439. MeshDistanceMaterial: 'distanceRGBA',
  11440. MeshNormalMaterial: 'normal',
  11441. MeshBasicMaterial: 'basic',
  11442. MeshLambertMaterial: 'lambert',
  11443. MeshPhongMaterial: 'phong',
  11444. MeshToonMaterial: 'toon',
  11445. MeshStandardMaterial: 'physical',
  11446. MeshPhysicalMaterial: 'physical',
  11447. MeshMatcapMaterial: 'matcap',
  11448. LineBasicMaterial: 'basic',
  11449. LineDashedMaterial: 'dashed',
  11450. PointsMaterial: 'points',
  11451. ShadowMaterial: 'shadow',
  11452. SpriteMaterial: 'sprite'
  11453. };
  11454. function getParameters( material, lights, shadows, scene, object ) {
  11455. const fog = scene.fog;
  11456. const geometry = object.geometry;
  11457. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11458. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11459. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11460. const shaderID = shaderIDs[ material.type ];
  11461. // heuristics to create shader parameters according to lights in the scene
  11462. // (not to blow over maxLights budget)
  11463. if ( material.precision !== null ) {
  11464. precision = capabilities.getMaxPrecision( material.precision );
  11465. if ( precision !== material.precision ) {
  11466. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11467. }
  11468. }
  11469. //
  11470. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11471. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11472. let morphTextureStride = 0;
  11473. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11474. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11475. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11476. //
  11477. let vertexShader, fragmentShader;
  11478. let customVertexShaderID, customFragmentShaderID;
  11479. if ( shaderID ) {
  11480. const shader = ShaderLib[ shaderID ];
  11481. vertexShader = shader.vertexShader;
  11482. fragmentShader = shader.fragmentShader;
  11483. } else {
  11484. vertexShader = material.vertexShader;
  11485. fragmentShader = material.fragmentShader;
  11486. _customShaders.update( material );
  11487. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11488. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11489. }
  11490. const currentRenderTarget = renderer.getRenderTarget();
  11491. const useAlphaTest = material.alphaTest > 0;
  11492. const useClearcoat = material.clearcoat > 0;
  11493. const useIridescence = material.iridescence > 0;
  11494. const parameters = {
  11495. isWebGL2: isWebGL2,
  11496. shaderID: shaderID,
  11497. shaderName: material.type,
  11498. vertexShader: vertexShader,
  11499. fragmentShader: fragmentShader,
  11500. defines: material.defines,
  11501. customVertexShaderID: customVertexShaderID,
  11502. customFragmentShaderID: customFragmentShaderID,
  11503. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11504. glslVersion: material.glslVersion,
  11505. precision: precision,
  11506. instancing: object.isInstancedMesh === true,
  11507. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11508. supportsVertexTextures: vertexTextures,
  11509. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11510. map: !! material.map,
  11511. matcap: !! material.matcap,
  11512. envMap: !! envMap,
  11513. envMapMode: envMap && envMap.mapping,
  11514. envMapCubeUVHeight: envMapCubeUVHeight,
  11515. lightMap: !! material.lightMap,
  11516. aoMap: !! material.aoMap,
  11517. emissiveMap: !! material.emissiveMap,
  11518. bumpMap: !! material.bumpMap,
  11519. normalMap: !! material.normalMap,
  11520. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11521. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11522. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11523. clearcoat: useClearcoat,
  11524. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11525. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11526. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11527. iridescence: useIridescence,
  11528. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11529. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11530. displacementMap: !! material.displacementMap,
  11531. roughnessMap: !! material.roughnessMap,
  11532. metalnessMap: !! material.metalnessMap,
  11533. specularMap: !! material.specularMap,
  11534. specularIntensityMap: !! material.specularIntensityMap,
  11535. specularColorMap: !! material.specularColorMap,
  11536. opaque: material.transparent === false && material.blending === NormalBlending,
  11537. alphaMap: !! material.alphaMap,
  11538. alphaTest: useAlphaTest,
  11539. gradientMap: !! material.gradientMap,
  11540. sheen: material.sheen > 0,
  11541. sheenColorMap: !! material.sheenColorMap,
  11542. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11543. transmission: material.transmission > 0,
  11544. transmissionMap: !! material.transmissionMap,
  11545. thicknessMap: !! material.thicknessMap,
  11546. combine: material.combine,
  11547. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11548. vertexColors: material.vertexColors,
  11549. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11550. 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,
  11551. 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,
  11552. fog: !! fog,
  11553. useFog: material.fog === true,
  11554. fogExp2: ( fog && fog.isFogExp2 ),
  11555. flatShading: !! material.flatShading,
  11556. sizeAttenuation: material.sizeAttenuation,
  11557. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11558. skinning: object.isSkinnedMesh === true,
  11559. morphTargets: geometry.morphAttributes.position !== undefined,
  11560. morphNormals: geometry.morphAttributes.normal !== undefined,
  11561. morphColors: geometry.morphAttributes.color !== undefined,
  11562. morphTargetsCount: morphTargetsCount,
  11563. morphTextureStride: morphTextureStride,
  11564. numDirLights: lights.directional.length,
  11565. numPointLights: lights.point.length,
  11566. numSpotLights: lights.spot.length,
  11567. numSpotLightMaps: lights.spotLightMap.length,
  11568. numRectAreaLights: lights.rectArea.length,
  11569. numHemiLights: lights.hemi.length,
  11570. numDirLightShadows: lights.directionalShadowMap.length,
  11571. numPointLightShadows: lights.pointShadowMap.length,
  11572. numSpotLightShadows: lights.spotShadowMap.length,
  11573. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11574. numClippingPlanes: clipping.numPlanes,
  11575. numClipIntersection: clipping.numIntersection,
  11576. dithering: material.dithering,
  11577. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11578. shadowMapType: renderer.shadowMap.type,
  11579. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11580. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11581. premultipliedAlpha: material.premultipliedAlpha,
  11582. doubleSided: material.side === DoubleSide,
  11583. flipSided: material.side === BackSide,
  11584. useDepthPacking: !! material.depthPacking,
  11585. depthPacking: material.depthPacking || 0,
  11586. index0AttributeName: material.index0AttributeName,
  11587. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11588. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11589. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11590. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11591. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11592. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11593. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11594. customProgramCacheKey: material.customProgramCacheKey()
  11595. };
  11596. return parameters;
  11597. }
  11598. function getProgramCacheKey( parameters ) {
  11599. const array = [];
  11600. if ( parameters.shaderID ) {
  11601. array.push( parameters.shaderID );
  11602. } else {
  11603. array.push( parameters.customVertexShaderID );
  11604. array.push( parameters.customFragmentShaderID );
  11605. }
  11606. if ( parameters.defines !== undefined ) {
  11607. for ( const name in parameters.defines ) {
  11608. array.push( name );
  11609. array.push( parameters.defines[ name ] );
  11610. }
  11611. }
  11612. if ( parameters.isRawShaderMaterial === false ) {
  11613. getProgramCacheKeyParameters( array, parameters );
  11614. getProgramCacheKeyBooleans( array, parameters );
  11615. array.push( renderer.outputEncoding );
  11616. }
  11617. array.push( parameters.customProgramCacheKey );
  11618. return array.join();
  11619. }
  11620. function getProgramCacheKeyParameters( array, parameters ) {
  11621. array.push( parameters.precision );
  11622. array.push( parameters.outputEncoding );
  11623. array.push( parameters.envMapMode );
  11624. array.push( parameters.envMapCubeUVHeight );
  11625. array.push( parameters.combine );
  11626. array.push( parameters.vertexUvs );
  11627. array.push( parameters.fogExp2 );
  11628. array.push( parameters.sizeAttenuation );
  11629. array.push( parameters.morphTargetsCount );
  11630. array.push( parameters.morphAttributeCount );
  11631. array.push( parameters.numDirLights );
  11632. array.push( parameters.numPointLights );
  11633. array.push( parameters.numSpotLights );
  11634. array.push( parameters.numSpotLightMaps );
  11635. array.push( parameters.numHemiLights );
  11636. array.push( parameters.numRectAreaLights );
  11637. array.push( parameters.numDirLightShadows );
  11638. array.push( parameters.numPointLightShadows );
  11639. array.push( parameters.numSpotLightShadows );
  11640. array.push( parameters.numSpotLightShadowsWithMaps );
  11641. array.push( parameters.shadowMapType );
  11642. array.push( parameters.toneMapping );
  11643. array.push( parameters.numClippingPlanes );
  11644. array.push( parameters.numClipIntersection );
  11645. array.push( parameters.depthPacking );
  11646. }
  11647. function getProgramCacheKeyBooleans( array, parameters ) {
  11648. _programLayers.disableAll();
  11649. if ( parameters.isWebGL2 )
  11650. _programLayers.enable( 0 );
  11651. if ( parameters.supportsVertexTextures )
  11652. _programLayers.enable( 1 );
  11653. if ( parameters.instancing )
  11654. _programLayers.enable( 2 );
  11655. if ( parameters.instancingColor )
  11656. _programLayers.enable( 3 );
  11657. if ( parameters.map )
  11658. _programLayers.enable( 4 );
  11659. if ( parameters.matcap )
  11660. _programLayers.enable( 5 );
  11661. if ( parameters.envMap )
  11662. _programLayers.enable( 6 );
  11663. if ( parameters.lightMap )
  11664. _programLayers.enable( 7 );
  11665. if ( parameters.aoMap )
  11666. _programLayers.enable( 8 );
  11667. if ( parameters.emissiveMap )
  11668. _programLayers.enable( 9 );
  11669. if ( parameters.bumpMap )
  11670. _programLayers.enable( 10 );
  11671. if ( parameters.normalMap )
  11672. _programLayers.enable( 11 );
  11673. if ( parameters.objectSpaceNormalMap )
  11674. _programLayers.enable( 12 );
  11675. if ( parameters.tangentSpaceNormalMap )
  11676. _programLayers.enable( 13 );
  11677. if ( parameters.clearcoat )
  11678. _programLayers.enable( 14 );
  11679. if ( parameters.clearcoatMap )
  11680. _programLayers.enable( 15 );
  11681. if ( parameters.clearcoatRoughnessMap )
  11682. _programLayers.enable( 16 );
  11683. if ( parameters.clearcoatNormalMap )
  11684. _programLayers.enable( 17 );
  11685. if ( parameters.iridescence )
  11686. _programLayers.enable( 18 );
  11687. if ( parameters.iridescenceMap )
  11688. _programLayers.enable( 19 );
  11689. if ( parameters.iridescenceThicknessMap )
  11690. _programLayers.enable( 20 );
  11691. if ( parameters.displacementMap )
  11692. _programLayers.enable( 21 );
  11693. if ( parameters.specularMap )
  11694. _programLayers.enable( 22 );
  11695. if ( parameters.roughnessMap )
  11696. _programLayers.enable( 23 );
  11697. if ( parameters.metalnessMap )
  11698. _programLayers.enable( 24 );
  11699. if ( parameters.gradientMap )
  11700. _programLayers.enable( 25 );
  11701. if ( parameters.alphaMap )
  11702. _programLayers.enable( 26 );
  11703. if ( parameters.alphaTest )
  11704. _programLayers.enable( 27 );
  11705. if ( parameters.vertexColors )
  11706. _programLayers.enable( 28 );
  11707. if ( parameters.vertexAlphas )
  11708. _programLayers.enable( 29 );
  11709. if ( parameters.vertexUvs )
  11710. _programLayers.enable( 30 );
  11711. if ( parameters.vertexTangents )
  11712. _programLayers.enable( 31 );
  11713. if ( parameters.uvsVertexOnly )
  11714. _programLayers.enable( 32 );
  11715. array.push( _programLayers.mask );
  11716. _programLayers.disableAll();
  11717. if ( parameters.fog )
  11718. _programLayers.enable( 0 );
  11719. if ( parameters.useFog )
  11720. _programLayers.enable( 1 );
  11721. if ( parameters.flatShading )
  11722. _programLayers.enable( 2 );
  11723. if ( parameters.logarithmicDepthBuffer )
  11724. _programLayers.enable( 3 );
  11725. if ( parameters.skinning )
  11726. _programLayers.enable( 4 );
  11727. if ( parameters.morphTargets )
  11728. _programLayers.enable( 5 );
  11729. if ( parameters.morphNormals )
  11730. _programLayers.enable( 6 );
  11731. if ( parameters.morphColors )
  11732. _programLayers.enable( 7 );
  11733. if ( parameters.premultipliedAlpha )
  11734. _programLayers.enable( 8 );
  11735. if ( parameters.shadowMapEnabled )
  11736. _programLayers.enable( 9 );
  11737. if ( parameters.physicallyCorrectLights )
  11738. _programLayers.enable( 10 );
  11739. if ( parameters.doubleSided )
  11740. _programLayers.enable( 11 );
  11741. if ( parameters.flipSided )
  11742. _programLayers.enable( 12 );
  11743. if ( parameters.useDepthPacking )
  11744. _programLayers.enable( 13 );
  11745. if ( parameters.dithering )
  11746. _programLayers.enable( 14 );
  11747. if ( parameters.specularIntensityMap )
  11748. _programLayers.enable( 15 );
  11749. if ( parameters.specularColorMap )
  11750. _programLayers.enable( 16 );
  11751. if ( parameters.transmission )
  11752. _programLayers.enable( 17 );
  11753. if ( parameters.transmissionMap )
  11754. _programLayers.enable( 18 );
  11755. if ( parameters.thicknessMap )
  11756. _programLayers.enable( 19 );
  11757. if ( parameters.sheen )
  11758. _programLayers.enable( 20 );
  11759. if ( parameters.sheenColorMap )
  11760. _programLayers.enable( 21 );
  11761. if ( parameters.sheenRoughnessMap )
  11762. _programLayers.enable( 22 );
  11763. if ( parameters.decodeVideoTexture )
  11764. _programLayers.enable( 23 );
  11765. if ( parameters.opaque )
  11766. _programLayers.enable( 24 );
  11767. array.push( _programLayers.mask );
  11768. }
  11769. function getUniforms( material ) {
  11770. const shaderID = shaderIDs[ material.type ];
  11771. let uniforms;
  11772. if ( shaderID ) {
  11773. const shader = ShaderLib[ shaderID ];
  11774. uniforms = UniformsUtils.clone( shader.uniforms );
  11775. } else {
  11776. uniforms = material.uniforms;
  11777. }
  11778. return uniforms;
  11779. }
  11780. function acquireProgram( parameters, cacheKey ) {
  11781. let program;
  11782. // Check if code has been already compiled
  11783. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11784. const preexistingProgram = programs[ p ];
  11785. if ( preexistingProgram.cacheKey === cacheKey ) {
  11786. program = preexistingProgram;
  11787. ++ program.usedTimes;
  11788. break;
  11789. }
  11790. }
  11791. if ( program === undefined ) {
  11792. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11793. programs.push( program );
  11794. }
  11795. return program;
  11796. }
  11797. function releaseProgram( program ) {
  11798. if ( -- program.usedTimes === 0 ) {
  11799. // Remove from unordered set
  11800. const i = programs.indexOf( program );
  11801. programs[ i ] = programs[ programs.length - 1 ];
  11802. programs.pop();
  11803. // Free WebGL resources
  11804. program.destroy();
  11805. }
  11806. }
  11807. function releaseShaderCache( material ) {
  11808. _customShaders.remove( material );
  11809. }
  11810. function dispose() {
  11811. _customShaders.dispose();
  11812. }
  11813. return {
  11814. getParameters: getParameters,
  11815. getProgramCacheKey: getProgramCacheKey,
  11816. getUniforms: getUniforms,
  11817. acquireProgram: acquireProgram,
  11818. releaseProgram: releaseProgram,
  11819. releaseShaderCache: releaseShaderCache,
  11820. // Exposed for resource monitoring & error feedback via renderer.info:
  11821. programs: programs,
  11822. dispose: dispose
  11823. };
  11824. }
  11825. function WebGLProperties() {
  11826. let properties = new WeakMap();
  11827. function get( object ) {
  11828. let map = properties.get( object );
  11829. if ( map === undefined ) {
  11830. map = {};
  11831. properties.set( object, map );
  11832. }
  11833. return map;
  11834. }
  11835. function remove( object ) {
  11836. properties.delete( object );
  11837. }
  11838. function update( object, key, value ) {
  11839. properties.get( object )[ key ] = value;
  11840. }
  11841. function dispose() {
  11842. properties = new WeakMap();
  11843. }
  11844. return {
  11845. get: get,
  11846. remove: remove,
  11847. update: update,
  11848. dispose: dispose
  11849. };
  11850. }
  11851. function painterSortStable( a, b ) {
  11852. if ( a.groupOrder !== b.groupOrder ) {
  11853. return a.groupOrder - b.groupOrder;
  11854. } else if ( a.renderOrder !== b.renderOrder ) {
  11855. return a.renderOrder - b.renderOrder;
  11856. } else if ( a.material.id !== b.material.id ) {
  11857. return a.material.id - b.material.id;
  11858. } else if ( a.z !== b.z ) {
  11859. return a.z - b.z;
  11860. } else {
  11861. return a.id - b.id;
  11862. }
  11863. }
  11864. function reversePainterSortStable( a, b ) {
  11865. if ( a.groupOrder !== b.groupOrder ) {
  11866. return a.groupOrder - b.groupOrder;
  11867. } else if ( a.renderOrder !== b.renderOrder ) {
  11868. return a.renderOrder - b.renderOrder;
  11869. } else if ( a.z !== b.z ) {
  11870. return b.z - a.z;
  11871. } else {
  11872. return a.id - b.id;
  11873. }
  11874. }
  11875. function WebGLRenderList() {
  11876. const renderItems = [];
  11877. let renderItemsIndex = 0;
  11878. const opaque = [];
  11879. const transmissive = [];
  11880. const transparent = [];
  11881. function init() {
  11882. renderItemsIndex = 0;
  11883. opaque.length = 0;
  11884. transmissive.length = 0;
  11885. transparent.length = 0;
  11886. }
  11887. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11888. let renderItem = renderItems[ renderItemsIndex ];
  11889. if ( renderItem === undefined ) {
  11890. renderItem = {
  11891. id: object.id,
  11892. object: object,
  11893. geometry: geometry,
  11894. material: material,
  11895. groupOrder: groupOrder,
  11896. renderOrder: object.renderOrder,
  11897. z: z,
  11898. group: group
  11899. };
  11900. renderItems[ renderItemsIndex ] = renderItem;
  11901. } else {
  11902. renderItem.id = object.id;
  11903. renderItem.object = object;
  11904. renderItem.geometry = geometry;
  11905. renderItem.material = material;
  11906. renderItem.groupOrder = groupOrder;
  11907. renderItem.renderOrder = object.renderOrder;
  11908. renderItem.z = z;
  11909. renderItem.group = group;
  11910. }
  11911. renderItemsIndex ++;
  11912. return renderItem;
  11913. }
  11914. function push( object, geometry, material, groupOrder, z, group ) {
  11915. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11916. if ( material.transmission > 0.0 ) {
  11917. transmissive.push( renderItem );
  11918. } else if ( material.transparent === true ) {
  11919. transparent.push( renderItem );
  11920. } else {
  11921. opaque.push( renderItem );
  11922. }
  11923. }
  11924. function unshift( object, geometry, material, groupOrder, z, group ) {
  11925. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11926. if ( material.transmission > 0.0 ) {
  11927. transmissive.unshift( renderItem );
  11928. } else if ( material.transparent === true ) {
  11929. transparent.unshift( renderItem );
  11930. } else {
  11931. opaque.unshift( renderItem );
  11932. }
  11933. }
  11934. function sort( customOpaqueSort, customTransparentSort ) {
  11935. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11936. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  11937. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11938. }
  11939. function finish() {
  11940. // Clear references from inactive renderItems in the list
  11941. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11942. const renderItem = renderItems[ i ];
  11943. if ( renderItem.id === null ) break;
  11944. renderItem.id = null;
  11945. renderItem.object = null;
  11946. renderItem.geometry = null;
  11947. renderItem.material = null;
  11948. renderItem.group = null;
  11949. }
  11950. }
  11951. return {
  11952. opaque: opaque,
  11953. transmissive: transmissive,
  11954. transparent: transparent,
  11955. init: init,
  11956. push: push,
  11957. unshift: unshift,
  11958. finish: finish,
  11959. sort: sort
  11960. };
  11961. }
  11962. function WebGLRenderLists() {
  11963. let lists = new WeakMap();
  11964. function get( scene, renderCallDepth ) {
  11965. const listArray = lists.get( scene );
  11966. let list;
  11967. if ( listArray === undefined ) {
  11968. list = new WebGLRenderList();
  11969. lists.set( scene, [ list ] );
  11970. } else {
  11971. if ( renderCallDepth >= listArray.length ) {
  11972. list = new WebGLRenderList();
  11973. listArray.push( list );
  11974. } else {
  11975. list = listArray[ renderCallDepth ];
  11976. }
  11977. }
  11978. return list;
  11979. }
  11980. function dispose() {
  11981. lists = new WeakMap();
  11982. }
  11983. return {
  11984. get: get,
  11985. dispose: dispose
  11986. };
  11987. }
  11988. function UniformsCache() {
  11989. const lights = {};
  11990. return {
  11991. get: function ( light ) {
  11992. if ( lights[ light.id ] !== undefined ) {
  11993. return lights[ light.id ];
  11994. }
  11995. let uniforms;
  11996. switch ( light.type ) {
  11997. case 'DirectionalLight':
  11998. uniforms = {
  11999. direction: new Vector3(),
  12000. color: new Color()
  12001. };
  12002. break;
  12003. case 'SpotLight':
  12004. uniforms = {
  12005. position: new Vector3(),
  12006. direction: new Vector3(),
  12007. color: new Color(),
  12008. distance: 0,
  12009. coneCos: 0,
  12010. penumbraCos: 0,
  12011. decay: 0
  12012. };
  12013. break;
  12014. case 'PointLight':
  12015. uniforms = {
  12016. position: new Vector3(),
  12017. color: new Color(),
  12018. distance: 0,
  12019. decay: 0
  12020. };
  12021. break;
  12022. case 'HemisphereLight':
  12023. uniforms = {
  12024. direction: new Vector3(),
  12025. skyColor: new Color(),
  12026. groundColor: new Color()
  12027. };
  12028. break;
  12029. case 'RectAreaLight':
  12030. uniforms = {
  12031. color: new Color(),
  12032. position: new Vector3(),
  12033. halfWidth: new Vector3(),
  12034. halfHeight: new Vector3()
  12035. };
  12036. break;
  12037. }
  12038. lights[ light.id ] = uniforms;
  12039. return uniforms;
  12040. }
  12041. };
  12042. }
  12043. function ShadowUniformsCache() {
  12044. const lights = {};
  12045. return {
  12046. get: function ( light ) {
  12047. if ( lights[ light.id ] !== undefined ) {
  12048. return lights[ light.id ];
  12049. }
  12050. let uniforms;
  12051. switch ( light.type ) {
  12052. case 'DirectionalLight':
  12053. uniforms = {
  12054. shadowBias: 0,
  12055. shadowNormalBias: 0,
  12056. shadowRadius: 1,
  12057. shadowMapSize: new Vector2()
  12058. };
  12059. break;
  12060. case 'SpotLight':
  12061. uniforms = {
  12062. shadowBias: 0,
  12063. shadowNormalBias: 0,
  12064. shadowRadius: 1,
  12065. shadowMapSize: new Vector2()
  12066. };
  12067. break;
  12068. case 'PointLight':
  12069. uniforms = {
  12070. shadowBias: 0,
  12071. shadowNormalBias: 0,
  12072. shadowRadius: 1,
  12073. shadowMapSize: new Vector2(),
  12074. shadowCameraNear: 1,
  12075. shadowCameraFar: 1000
  12076. };
  12077. break;
  12078. // TODO (abelnation): set RectAreaLight shadow uniforms
  12079. }
  12080. lights[ light.id ] = uniforms;
  12081. return uniforms;
  12082. }
  12083. };
  12084. }
  12085. let nextVersion = 0;
  12086. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12087. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12088. }
  12089. function WebGLLights( extensions, capabilities ) {
  12090. const cache = new UniformsCache();
  12091. const shadowCache = ShadowUniformsCache();
  12092. const state = {
  12093. version: 0,
  12094. hash: {
  12095. directionalLength: - 1,
  12096. pointLength: - 1,
  12097. spotLength: - 1,
  12098. rectAreaLength: - 1,
  12099. hemiLength: - 1,
  12100. numDirectionalShadows: - 1,
  12101. numPointShadows: - 1,
  12102. numSpotShadows: - 1,
  12103. numSpotMaps: - 1
  12104. },
  12105. ambient: [ 0, 0, 0 ],
  12106. probe: [],
  12107. directional: [],
  12108. directionalShadow: [],
  12109. directionalShadowMap: [],
  12110. directionalShadowMatrix: [],
  12111. spot: [],
  12112. spotLightMap: [],
  12113. spotShadow: [],
  12114. spotShadowMap: [],
  12115. spotLightMatrix: [],
  12116. rectArea: [],
  12117. rectAreaLTC1: null,
  12118. rectAreaLTC2: null,
  12119. point: [],
  12120. pointShadow: [],
  12121. pointShadowMap: [],
  12122. pointShadowMatrix: [],
  12123. hemi: [],
  12124. numSpotLightShadowsWithMaps: 0
  12125. };
  12126. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12127. const vector3 = new Vector3();
  12128. const matrix4 = new Matrix4();
  12129. const matrix42 = new Matrix4();
  12130. function setup( lights, physicallyCorrectLights ) {
  12131. let r = 0, g = 0, b = 0;
  12132. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12133. let directionalLength = 0;
  12134. let pointLength = 0;
  12135. let spotLength = 0;
  12136. let rectAreaLength = 0;
  12137. let hemiLength = 0;
  12138. let numDirectionalShadows = 0;
  12139. let numPointShadows = 0;
  12140. let numSpotShadows = 0;
  12141. let numSpotMaps = 0;
  12142. let numSpotShadowsWithMaps = 0;
  12143. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12144. lights.sort( shadowCastingAndTexturingLightsFirst );
  12145. // artist-friendly light intensity scaling factor
  12146. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12147. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12148. const light = lights[ i ];
  12149. const color = light.color;
  12150. const intensity = light.intensity;
  12151. const distance = light.distance;
  12152. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12153. if ( light.isAmbientLight ) {
  12154. r += color.r * intensity * scaleFactor;
  12155. g += color.g * intensity * scaleFactor;
  12156. b += color.b * intensity * scaleFactor;
  12157. } else if ( light.isLightProbe ) {
  12158. for ( let j = 0; j < 9; j ++ ) {
  12159. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12160. }
  12161. } else if ( light.isDirectionalLight ) {
  12162. const uniforms = cache.get( light );
  12163. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12164. if ( light.castShadow ) {
  12165. const shadow = light.shadow;
  12166. const shadowUniforms = shadowCache.get( light );
  12167. shadowUniforms.shadowBias = shadow.bias;
  12168. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12169. shadowUniforms.shadowRadius = shadow.radius;
  12170. shadowUniforms.shadowMapSize = shadow.mapSize;
  12171. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12172. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12173. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12174. numDirectionalShadows ++;
  12175. }
  12176. state.directional[ directionalLength ] = uniforms;
  12177. directionalLength ++;
  12178. } else if ( light.isSpotLight ) {
  12179. const uniforms = cache.get( light );
  12180. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12181. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12182. uniforms.distance = distance;
  12183. uniforms.coneCos = Math.cos( light.angle );
  12184. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12185. uniforms.decay = light.decay;
  12186. state.spot[ spotLength ] = uniforms;
  12187. const shadow = light.shadow;
  12188. if ( light.map ) {
  12189. state.spotLightMap[ numSpotMaps ] = light.map;
  12190. numSpotMaps ++;
  12191. // make sure the lightMatrix is up to date
  12192. // TODO : do it if required only
  12193. shadow.updateMatrices( light );
  12194. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12195. }
  12196. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12197. if ( light.castShadow ) {
  12198. const shadowUniforms = shadowCache.get( light );
  12199. shadowUniforms.shadowBias = shadow.bias;
  12200. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12201. shadowUniforms.shadowRadius = shadow.radius;
  12202. shadowUniforms.shadowMapSize = shadow.mapSize;
  12203. state.spotShadow[ spotLength ] = shadowUniforms;
  12204. state.spotShadowMap[ spotLength ] = shadowMap;
  12205. numSpotShadows ++;
  12206. }
  12207. spotLength ++;
  12208. } else if ( light.isRectAreaLight ) {
  12209. const uniforms = cache.get( light );
  12210. // (a) intensity is the total visible light emitted
  12211. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12212. // (b) intensity is the brightness of the light
  12213. uniforms.color.copy( color ).multiplyScalar( intensity );
  12214. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12215. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12216. state.rectArea[ rectAreaLength ] = uniforms;
  12217. rectAreaLength ++;
  12218. } else if ( light.isPointLight ) {
  12219. const uniforms = cache.get( light );
  12220. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12221. uniforms.distance = light.distance;
  12222. uniforms.decay = light.decay;
  12223. if ( light.castShadow ) {
  12224. const shadow = light.shadow;
  12225. const shadowUniforms = shadowCache.get( light );
  12226. shadowUniforms.shadowBias = shadow.bias;
  12227. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12228. shadowUniforms.shadowRadius = shadow.radius;
  12229. shadowUniforms.shadowMapSize = shadow.mapSize;
  12230. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12231. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12232. state.pointShadow[ pointLength ] = shadowUniforms;
  12233. state.pointShadowMap[ pointLength ] = shadowMap;
  12234. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12235. numPointShadows ++;
  12236. }
  12237. state.point[ pointLength ] = uniforms;
  12238. pointLength ++;
  12239. } else if ( light.isHemisphereLight ) {
  12240. const uniforms = cache.get( light );
  12241. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12242. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12243. state.hemi[ hemiLength ] = uniforms;
  12244. hemiLength ++;
  12245. }
  12246. }
  12247. if ( rectAreaLength > 0 ) {
  12248. if ( capabilities.isWebGL2 ) {
  12249. // WebGL 2
  12250. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12251. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12252. } else {
  12253. // WebGL 1
  12254. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12255. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12256. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12257. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12258. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12259. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12260. } else {
  12261. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12262. }
  12263. }
  12264. }
  12265. state.ambient[ 0 ] = r;
  12266. state.ambient[ 1 ] = g;
  12267. state.ambient[ 2 ] = b;
  12268. const hash = state.hash;
  12269. if ( hash.directionalLength !== directionalLength ||
  12270. hash.pointLength !== pointLength ||
  12271. hash.spotLength !== spotLength ||
  12272. hash.rectAreaLength !== rectAreaLength ||
  12273. hash.hemiLength !== hemiLength ||
  12274. hash.numDirectionalShadows !== numDirectionalShadows ||
  12275. hash.numPointShadows !== numPointShadows ||
  12276. hash.numSpotShadows !== numSpotShadows ||
  12277. hash.numSpotMaps !== numSpotMaps ) {
  12278. state.directional.length = directionalLength;
  12279. state.spot.length = spotLength;
  12280. state.rectArea.length = rectAreaLength;
  12281. state.point.length = pointLength;
  12282. state.hemi.length = hemiLength;
  12283. state.directionalShadow.length = numDirectionalShadows;
  12284. state.directionalShadowMap.length = numDirectionalShadows;
  12285. state.pointShadow.length = numPointShadows;
  12286. state.pointShadowMap.length = numPointShadows;
  12287. state.spotShadow.length = numSpotShadows;
  12288. state.spotShadowMap.length = numSpotShadows;
  12289. state.directionalShadowMatrix.length = numDirectionalShadows;
  12290. state.pointShadowMatrix.length = numPointShadows;
  12291. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12292. state.spotLightMap.length = numSpotMaps;
  12293. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12294. hash.directionalLength = directionalLength;
  12295. hash.pointLength = pointLength;
  12296. hash.spotLength = spotLength;
  12297. hash.rectAreaLength = rectAreaLength;
  12298. hash.hemiLength = hemiLength;
  12299. hash.numDirectionalShadows = numDirectionalShadows;
  12300. hash.numPointShadows = numPointShadows;
  12301. hash.numSpotShadows = numSpotShadows;
  12302. hash.numSpotMaps = numSpotMaps;
  12303. state.version = nextVersion ++;
  12304. }
  12305. }
  12306. function setupView( lights, camera ) {
  12307. let directionalLength = 0;
  12308. let pointLength = 0;
  12309. let spotLength = 0;
  12310. let rectAreaLength = 0;
  12311. let hemiLength = 0;
  12312. const viewMatrix = camera.matrixWorldInverse;
  12313. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12314. const light = lights[ i ];
  12315. if ( light.isDirectionalLight ) {
  12316. const uniforms = state.directional[ directionalLength ];
  12317. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12318. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12319. uniforms.direction.sub( vector3 );
  12320. uniforms.direction.transformDirection( viewMatrix );
  12321. directionalLength ++;
  12322. } else if ( light.isSpotLight ) {
  12323. const uniforms = state.spot[ spotLength ];
  12324. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12325. uniforms.position.applyMatrix4( viewMatrix );
  12326. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12327. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12328. uniforms.direction.sub( vector3 );
  12329. uniforms.direction.transformDirection( viewMatrix );
  12330. spotLength ++;
  12331. } else if ( light.isRectAreaLight ) {
  12332. const uniforms = state.rectArea[ rectAreaLength ];
  12333. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12334. uniforms.position.applyMatrix4( viewMatrix );
  12335. // extract local rotation of light to derive width/height half vectors
  12336. matrix42.identity();
  12337. matrix4.copy( light.matrixWorld );
  12338. matrix4.premultiply( viewMatrix );
  12339. matrix42.extractRotation( matrix4 );
  12340. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12341. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12342. uniforms.halfWidth.applyMatrix4( matrix42 );
  12343. uniforms.halfHeight.applyMatrix4( matrix42 );
  12344. rectAreaLength ++;
  12345. } else if ( light.isPointLight ) {
  12346. const uniforms = state.point[ pointLength ];
  12347. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12348. uniforms.position.applyMatrix4( viewMatrix );
  12349. pointLength ++;
  12350. } else if ( light.isHemisphereLight ) {
  12351. const uniforms = state.hemi[ hemiLength ];
  12352. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12353. uniforms.direction.transformDirection( viewMatrix );
  12354. hemiLength ++;
  12355. }
  12356. }
  12357. }
  12358. return {
  12359. setup: setup,
  12360. setupView: setupView,
  12361. state: state
  12362. };
  12363. }
  12364. function WebGLRenderState( extensions, capabilities ) {
  12365. const lights = new WebGLLights( extensions, capabilities );
  12366. const lightsArray = [];
  12367. const shadowsArray = [];
  12368. function init() {
  12369. lightsArray.length = 0;
  12370. shadowsArray.length = 0;
  12371. }
  12372. function pushLight( light ) {
  12373. lightsArray.push( light );
  12374. }
  12375. function pushShadow( shadowLight ) {
  12376. shadowsArray.push( shadowLight );
  12377. }
  12378. function setupLights( physicallyCorrectLights ) {
  12379. lights.setup( lightsArray, physicallyCorrectLights );
  12380. }
  12381. function setupLightsView( camera ) {
  12382. lights.setupView( lightsArray, camera );
  12383. }
  12384. const state = {
  12385. lightsArray: lightsArray,
  12386. shadowsArray: shadowsArray,
  12387. lights: lights
  12388. };
  12389. return {
  12390. init: init,
  12391. state: state,
  12392. setupLights: setupLights,
  12393. setupLightsView: setupLightsView,
  12394. pushLight: pushLight,
  12395. pushShadow: pushShadow
  12396. };
  12397. }
  12398. function WebGLRenderStates( extensions, capabilities ) {
  12399. let renderStates = new WeakMap();
  12400. function get( scene, renderCallDepth = 0 ) {
  12401. const renderStateArray = renderStates.get( scene );
  12402. let renderState;
  12403. if ( renderStateArray === undefined ) {
  12404. renderState = new WebGLRenderState( extensions, capabilities );
  12405. renderStates.set( scene, [ renderState ] );
  12406. } else {
  12407. if ( renderCallDepth >= renderStateArray.length ) {
  12408. renderState = new WebGLRenderState( extensions, capabilities );
  12409. renderStateArray.push( renderState );
  12410. } else {
  12411. renderState = renderStateArray[ renderCallDepth ];
  12412. }
  12413. }
  12414. return renderState;
  12415. }
  12416. function dispose() {
  12417. renderStates = new WeakMap();
  12418. }
  12419. return {
  12420. get: get,
  12421. dispose: dispose
  12422. };
  12423. }
  12424. class MeshDepthMaterial extends Material {
  12425. constructor( parameters ) {
  12426. super();
  12427. this.isMeshDepthMaterial = true;
  12428. this.type = 'MeshDepthMaterial';
  12429. this.depthPacking = BasicDepthPacking;
  12430. this.map = null;
  12431. this.alphaMap = null;
  12432. this.displacementMap = null;
  12433. this.displacementScale = 1;
  12434. this.displacementBias = 0;
  12435. this.wireframe = false;
  12436. this.wireframeLinewidth = 1;
  12437. this.setValues( parameters );
  12438. }
  12439. copy( source ) {
  12440. super.copy( source );
  12441. this.depthPacking = source.depthPacking;
  12442. this.map = source.map;
  12443. this.alphaMap = source.alphaMap;
  12444. this.displacementMap = source.displacementMap;
  12445. this.displacementScale = source.displacementScale;
  12446. this.displacementBias = source.displacementBias;
  12447. this.wireframe = source.wireframe;
  12448. this.wireframeLinewidth = source.wireframeLinewidth;
  12449. return this;
  12450. }
  12451. }
  12452. class MeshDistanceMaterial extends Material {
  12453. constructor( parameters ) {
  12454. super();
  12455. this.isMeshDistanceMaterial = true;
  12456. this.type = 'MeshDistanceMaterial';
  12457. this.referencePosition = new Vector3();
  12458. this.nearDistance = 1;
  12459. this.farDistance = 1000;
  12460. this.map = null;
  12461. this.alphaMap = null;
  12462. this.displacementMap = null;
  12463. this.displacementScale = 1;
  12464. this.displacementBias = 0;
  12465. this.setValues( parameters );
  12466. }
  12467. copy( source ) {
  12468. super.copy( source );
  12469. this.referencePosition.copy( source.referencePosition );
  12470. this.nearDistance = source.nearDistance;
  12471. this.farDistance = source.farDistance;
  12472. this.map = source.map;
  12473. this.alphaMap = source.alphaMap;
  12474. this.displacementMap = source.displacementMap;
  12475. this.displacementScale = source.displacementScale;
  12476. this.displacementBias = source.displacementBias;
  12477. return this;
  12478. }
  12479. }
  12480. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12481. 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}";
  12482. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12483. let _frustum = new Frustum();
  12484. const _shadowMapSize = new Vector2(),
  12485. _viewportSize = new Vector2(),
  12486. _viewport = new Vector4(),
  12487. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12488. _distanceMaterial = new MeshDistanceMaterial(),
  12489. _materialCache = {},
  12490. _maxTextureSize = _capabilities.maxTextureSize;
  12491. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12492. const shadowMaterialVertical = new ShaderMaterial( {
  12493. defines: {
  12494. VSM_SAMPLES: 8
  12495. },
  12496. uniforms: {
  12497. shadow_pass: { value: null },
  12498. resolution: { value: new Vector2() },
  12499. radius: { value: 4.0 }
  12500. },
  12501. vertexShader: vertex,
  12502. fragmentShader: fragment
  12503. } );
  12504. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12505. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12506. const fullScreenTri = new BufferGeometry();
  12507. fullScreenTri.setAttribute(
  12508. 'position',
  12509. new BufferAttribute(
  12510. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12511. 3
  12512. )
  12513. );
  12514. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12515. const scope = this;
  12516. this.enabled = false;
  12517. this.autoUpdate = true;
  12518. this.needsUpdate = false;
  12519. this.type = PCFShadowMap;
  12520. this.render = function ( lights, scene, camera ) {
  12521. if ( scope.enabled === false ) return;
  12522. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12523. if ( lights.length === 0 ) return;
  12524. const currentRenderTarget = _renderer.getRenderTarget();
  12525. const activeCubeFace = _renderer.getActiveCubeFace();
  12526. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12527. const _state = _renderer.state;
  12528. // Set GL state for depth map.
  12529. _state.setBlending( NoBlending );
  12530. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12531. _state.buffers.depth.setTest( true );
  12532. _state.setScissorTest( false );
  12533. // render depth map
  12534. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12535. const light = lights[ i ];
  12536. const shadow = light.shadow;
  12537. if ( shadow === undefined ) {
  12538. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12539. continue;
  12540. }
  12541. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12542. _shadowMapSize.copy( shadow.mapSize );
  12543. const shadowFrameExtents = shadow.getFrameExtents();
  12544. _shadowMapSize.multiply( shadowFrameExtents );
  12545. _viewportSize.copy( shadow.mapSize );
  12546. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12547. if ( _shadowMapSize.x > _maxTextureSize ) {
  12548. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12549. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12550. shadow.mapSize.x = _viewportSize.x;
  12551. }
  12552. if ( _shadowMapSize.y > _maxTextureSize ) {
  12553. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12554. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12555. shadow.mapSize.y = _viewportSize.y;
  12556. }
  12557. }
  12558. if ( shadow.map === null ) {
  12559. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12560. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12561. shadow.map.texture.name = light.name + '.shadowMap';
  12562. shadow.camera.updateProjectionMatrix();
  12563. }
  12564. _renderer.setRenderTarget( shadow.map );
  12565. _renderer.clear();
  12566. const viewportCount = shadow.getViewportCount();
  12567. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12568. const viewport = shadow.getViewport( vp );
  12569. _viewport.set(
  12570. _viewportSize.x * viewport.x,
  12571. _viewportSize.y * viewport.y,
  12572. _viewportSize.x * viewport.z,
  12573. _viewportSize.y * viewport.w
  12574. );
  12575. _state.viewport( _viewport );
  12576. shadow.updateMatrices( light, vp );
  12577. _frustum = shadow.getFrustum();
  12578. renderObject( scene, camera, shadow.camera, light, this.type );
  12579. }
  12580. // do blur pass for VSM
  12581. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12582. VSMPass( shadow, camera );
  12583. }
  12584. shadow.needsUpdate = false;
  12585. }
  12586. scope.needsUpdate = false;
  12587. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12588. };
  12589. function VSMPass( shadow, camera ) {
  12590. const geometry = _objects.update( fullScreenMesh );
  12591. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12592. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12593. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12594. shadowMaterialVertical.needsUpdate = true;
  12595. shadowMaterialHorizontal.needsUpdate = true;
  12596. }
  12597. if ( shadow.mapPass === null ) {
  12598. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12599. }
  12600. // vertical pass
  12601. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12602. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12603. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12604. _renderer.setRenderTarget( shadow.mapPass );
  12605. _renderer.clear();
  12606. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12607. // horizontal pass
  12608. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12609. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12610. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12611. _renderer.setRenderTarget( shadow.map );
  12612. _renderer.clear();
  12613. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12614. }
  12615. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12616. let result = null;
  12617. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12618. if ( customMaterial !== undefined ) {
  12619. result = customMaterial;
  12620. } else {
  12621. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12622. }
  12623. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12624. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12625. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12626. // in this case we need a unique material instance reflecting the
  12627. // appropriate state
  12628. const keyA = result.uuid, keyB = material.uuid;
  12629. let materialsForVariant = _materialCache[ keyA ];
  12630. if ( materialsForVariant === undefined ) {
  12631. materialsForVariant = {};
  12632. _materialCache[ keyA ] = materialsForVariant;
  12633. }
  12634. let cachedMaterial = materialsForVariant[ keyB ];
  12635. if ( cachedMaterial === undefined ) {
  12636. cachedMaterial = result.clone();
  12637. materialsForVariant[ keyB ] = cachedMaterial;
  12638. }
  12639. result = cachedMaterial;
  12640. }
  12641. result.visible = material.visible;
  12642. result.wireframe = material.wireframe;
  12643. if ( type === VSMShadowMap ) {
  12644. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12645. } else {
  12646. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12647. }
  12648. result.alphaMap = material.alphaMap;
  12649. result.alphaTest = material.alphaTest;
  12650. result.clipShadows = material.clipShadows;
  12651. result.clippingPlanes = material.clippingPlanes;
  12652. result.clipIntersection = material.clipIntersection;
  12653. result.displacementMap = material.displacementMap;
  12654. result.displacementScale = material.displacementScale;
  12655. result.displacementBias = material.displacementBias;
  12656. result.wireframeLinewidth = material.wireframeLinewidth;
  12657. result.linewidth = material.linewidth;
  12658. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12659. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12660. result.nearDistance = shadowCameraNear;
  12661. result.farDistance = shadowCameraFar;
  12662. }
  12663. return result;
  12664. }
  12665. function renderObject( object, camera, shadowCamera, light, type ) {
  12666. if ( object.visible === false ) return;
  12667. const visible = object.layers.test( camera.layers );
  12668. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12669. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12670. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12671. const geometry = _objects.update( object );
  12672. const material = object.material;
  12673. if ( Array.isArray( material ) ) {
  12674. const groups = geometry.groups;
  12675. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12676. const group = groups[ k ];
  12677. const groupMaterial = material[ group.materialIndex ];
  12678. if ( groupMaterial && groupMaterial.visible ) {
  12679. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12680. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12681. }
  12682. }
  12683. } else if ( material.visible ) {
  12684. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12685. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12686. }
  12687. }
  12688. }
  12689. const children = object.children;
  12690. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12691. renderObject( children[ i ], camera, shadowCamera, light, type );
  12692. }
  12693. }
  12694. }
  12695. function WebGLState( gl, extensions, capabilities ) {
  12696. const isWebGL2 = capabilities.isWebGL2;
  12697. function ColorBuffer() {
  12698. let locked = false;
  12699. const color = new Vector4();
  12700. let currentColorMask = null;
  12701. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12702. return {
  12703. setMask: function ( colorMask ) {
  12704. if ( currentColorMask !== colorMask && ! locked ) {
  12705. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12706. currentColorMask = colorMask;
  12707. }
  12708. },
  12709. setLocked: function ( lock ) {
  12710. locked = lock;
  12711. },
  12712. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12713. if ( premultipliedAlpha === true ) {
  12714. r *= a; g *= a; b *= a;
  12715. }
  12716. color.set( r, g, b, a );
  12717. if ( currentColorClear.equals( color ) === false ) {
  12718. gl.clearColor( r, g, b, a );
  12719. currentColorClear.copy( color );
  12720. }
  12721. },
  12722. reset: function () {
  12723. locked = false;
  12724. currentColorMask = null;
  12725. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12726. }
  12727. };
  12728. }
  12729. function DepthBuffer() {
  12730. let locked = false;
  12731. let currentDepthMask = null;
  12732. let currentDepthFunc = null;
  12733. let currentDepthClear = null;
  12734. return {
  12735. setTest: function ( depthTest ) {
  12736. if ( depthTest ) {
  12737. enable( 2929 );
  12738. } else {
  12739. disable( 2929 );
  12740. }
  12741. },
  12742. setMask: function ( depthMask ) {
  12743. if ( currentDepthMask !== depthMask && ! locked ) {
  12744. gl.depthMask( depthMask );
  12745. currentDepthMask = depthMask;
  12746. }
  12747. },
  12748. setFunc: function ( depthFunc ) {
  12749. if ( currentDepthFunc !== depthFunc ) {
  12750. switch ( depthFunc ) {
  12751. case NeverDepth:
  12752. gl.depthFunc( 512 );
  12753. break;
  12754. case AlwaysDepth:
  12755. gl.depthFunc( 519 );
  12756. break;
  12757. case LessDepth:
  12758. gl.depthFunc( 513 );
  12759. break;
  12760. case LessEqualDepth:
  12761. gl.depthFunc( 515 );
  12762. break;
  12763. case EqualDepth:
  12764. gl.depthFunc( 514 );
  12765. break;
  12766. case GreaterEqualDepth:
  12767. gl.depthFunc( 518 );
  12768. break;
  12769. case GreaterDepth:
  12770. gl.depthFunc( 516 );
  12771. break;
  12772. case NotEqualDepth:
  12773. gl.depthFunc( 517 );
  12774. break;
  12775. default:
  12776. gl.depthFunc( 515 );
  12777. }
  12778. currentDepthFunc = depthFunc;
  12779. }
  12780. },
  12781. setLocked: function ( lock ) {
  12782. locked = lock;
  12783. },
  12784. setClear: function ( depth ) {
  12785. if ( currentDepthClear !== depth ) {
  12786. gl.clearDepth( depth );
  12787. currentDepthClear = depth;
  12788. }
  12789. },
  12790. reset: function () {
  12791. locked = false;
  12792. currentDepthMask = null;
  12793. currentDepthFunc = null;
  12794. currentDepthClear = null;
  12795. }
  12796. };
  12797. }
  12798. function StencilBuffer() {
  12799. let locked = false;
  12800. let currentStencilMask = null;
  12801. let currentStencilFunc = null;
  12802. let currentStencilRef = null;
  12803. let currentStencilFuncMask = null;
  12804. let currentStencilFail = null;
  12805. let currentStencilZFail = null;
  12806. let currentStencilZPass = null;
  12807. let currentStencilClear = null;
  12808. return {
  12809. setTest: function ( stencilTest ) {
  12810. if ( ! locked ) {
  12811. if ( stencilTest ) {
  12812. enable( 2960 );
  12813. } else {
  12814. disable( 2960 );
  12815. }
  12816. }
  12817. },
  12818. setMask: function ( stencilMask ) {
  12819. if ( currentStencilMask !== stencilMask && ! locked ) {
  12820. gl.stencilMask( stencilMask );
  12821. currentStencilMask = stencilMask;
  12822. }
  12823. },
  12824. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12825. if ( currentStencilFunc !== stencilFunc ||
  12826. currentStencilRef !== stencilRef ||
  12827. currentStencilFuncMask !== stencilMask ) {
  12828. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12829. currentStencilFunc = stencilFunc;
  12830. currentStencilRef = stencilRef;
  12831. currentStencilFuncMask = stencilMask;
  12832. }
  12833. },
  12834. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12835. if ( currentStencilFail !== stencilFail ||
  12836. currentStencilZFail !== stencilZFail ||
  12837. currentStencilZPass !== stencilZPass ) {
  12838. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12839. currentStencilFail = stencilFail;
  12840. currentStencilZFail = stencilZFail;
  12841. currentStencilZPass = stencilZPass;
  12842. }
  12843. },
  12844. setLocked: function ( lock ) {
  12845. locked = lock;
  12846. },
  12847. setClear: function ( stencil ) {
  12848. if ( currentStencilClear !== stencil ) {
  12849. gl.clearStencil( stencil );
  12850. currentStencilClear = stencil;
  12851. }
  12852. },
  12853. reset: function () {
  12854. locked = false;
  12855. currentStencilMask = null;
  12856. currentStencilFunc = null;
  12857. currentStencilRef = null;
  12858. currentStencilFuncMask = null;
  12859. currentStencilFail = null;
  12860. currentStencilZFail = null;
  12861. currentStencilZPass = null;
  12862. currentStencilClear = null;
  12863. }
  12864. };
  12865. }
  12866. //
  12867. const colorBuffer = new ColorBuffer();
  12868. const depthBuffer = new DepthBuffer();
  12869. const stencilBuffer = new StencilBuffer();
  12870. const uboBindings = new WeakMap();
  12871. const uboProgamMap = new WeakMap();
  12872. let enabledCapabilities = {};
  12873. let currentBoundFramebuffers = {};
  12874. let currentDrawbuffers = new WeakMap();
  12875. let defaultDrawbuffers = [];
  12876. let currentProgram = null;
  12877. let currentBlendingEnabled = false;
  12878. let currentBlending = null;
  12879. let currentBlendEquation = null;
  12880. let currentBlendSrc = null;
  12881. let currentBlendDst = null;
  12882. let currentBlendEquationAlpha = null;
  12883. let currentBlendSrcAlpha = null;
  12884. let currentBlendDstAlpha = null;
  12885. let currentPremultipledAlpha = false;
  12886. let currentFlipSided = null;
  12887. let currentCullFace = null;
  12888. let currentLineWidth = null;
  12889. let currentPolygonOffsetFactor = null;
  12890. let currentPolygonOffsetUnits = null;
  12891. const maxTextures = gl.getParameter( 35661 );
  12892. let lineWidthAvailable = false;
  12893. let version = 0;
  12894. const glVersion = gl.getParameter( 7938 );
  12895. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12896. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12897. lineWidthAvailable = ( version >= 1.0 );
  12898. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12899. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12900. lineWidthAvailable = ( version >= 2.0 );
  12901. }
  12902. let currentTextureSlot = null;
  12903. let currentBoundTextures = {};
  12904. const scissorParam = gl.getParameter( 3088 );
  12905. const viewportParam = gl.getParameter( 2978 );
  12906. const currentScissor = new Vector4().fromArray( scissorParam );
  12907. const currentViewport = new Vector4().fromArray( viewportParam );
  12908. function createTexture( type, target, count ) {
  12909. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12910. const texture = gl.createTexture();
  12911. gl.bindTexture( type, texture );
  12912. gl.texParameteri( type, 10241, 9728 );
  12913. gl.texParameteri( type, 10240, 9728 );
  12914. for ( let i = 0; i < count; i ++ ) {
  12915. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12916. }
  12917. return texture;
  12918. }
  12919. const emptyTextures = {};
  12920. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12921. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12922. // init
  12923. colorBuffer.setClear( 0, 0, 0, 1 );
  12924. depthBuffer.setClear( 1 );
  12925. stencilBuffer.setClear( 0 );
  12926. enable( 2929 );
  12927. depthBuffer.setFunc( LessEqualDepth );
  12928. setFlipSided( false );
  12929. setCullFace( CullFaceBack );
  12930. enable( 2884 );
  12931. setBlending( NoBlending );
  12932. //
  12933. function enable( id ) {
  12934. if ( enabledCapabilities[ id ] !== true ) {
  12935. gl.enable( id );
  12936. enabledCapabilities[ id ] = true;
  12937. }
  12938. }
  12939. function disable( id ) {
  12940. if ( enabledCapabilities[ id ] !== false ) {
  12941. gl.disable( id );
  12942. enabledCapabilities[ id ] = false;
  12943. }
  12944. }
  12945. function bindFramebuffer( target, framebuffer ) {
  12946. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12947. gl.bindFramebuffer( target, framebuffer );
  12948. currentBoundFramebuffers[ target ] = framebuffer;
  12949. if ( isWebGL2 ) {
  12950. // 36009 is equivalent to 36160
  12951. if ( target === 36009 ) {
  12952. currentBoundFramebuffers[ 36160 ] = framebuffer;
  12953. }
  12954. if ( target === 36160 ) {
  12955. currentBoundFramebuffers[ 36009 ] = framebuffer;
  12956. }
  12957. }
  12958. return true;
  12959. }
  12960. return false;
  12961. }
  12962. function drawBuffers( renderTarget, framebuffer ) {
  12963. let drawBuffers = defaultDrawbuffers;
  12964. let needsUpdate = false;
  12965. if ( renderTarget ) {
  12966. drawBuffers = currentDrawbuffers.get( framebuffer );
  12967. if ( drawBuffers === undefined ) {
  12968. drawBuffers = [];
  12969. currentDrawbuffers.set( framebuffer, drawBuffers );
  12970. }
  12971. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  12972. const textures = renderTarget.texture;
  12973. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  12974. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12975. drawBuffers[ i ] = 36064 + i;
  12976. }
  12977. drawBuffers.length = textures.length;
  12978. needsUpdate = true;
  12979. }
  12980. } else {
  12981. if ( drawBuffers[ 0 ] !== 36064 ) {
  12982. drawBuffers[ 0 ] = 36064;
  12983. needsUpdate = true;
  12984. }
  12985. }
  12986. } else {
  12987. if ( drawBuffers[ 0 ] !== 1029 ) {
  12988. drawBuffers[ 0 ] = 1029;
  12989. needsUpdate = true;
  12990. }
  12991. }
  12992. if ( needsUpdate ) {
  12993. if ( capabilities.isWebGL2 ) {
  12994. gl.drawBuffers( drawBuffers );
  12995. } else {
  12996. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  12997. }
  12998. }
  12999. }
  13000. function useProgram( program ) {
  13001. if ( currentProgram !== program ) {
  13002. gl.useProgram( program );
  13003. currentProgram = program;
  13004. return true;
  13005. }
  13006. return false;
  13007. }
  13008. const equationToGL = {
  13009. [ AddEquation ]: 32774,
  13010. [ SubtractEquation ]: 32778,
  13011. [ ReverseSubtractEquation ]: 32779
  13012. };
  13013. if ( isWebGL2 ) {
  13014. equationToGL[ MinEquation ] = 32775;
  13015. equationToGL[ MaxEquation ] = 32776;
  13016. } else {
  13017. const extension = extensions.get( 'EXT_blend_minmax' );
  13018. if ( extension !== null ) {
  13019. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13020. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13021. }
  13022. }
  13023. const factorToGL = {
  13024. [ ZeroFactor ]: 0,
  13025. [ OneFactor ]: 1,
  13026. [ SrcColorFactor ]: 768,
  13027. [ SrcAlphaFactor ]: 770,
  13028. [ SrcAlphaSaturateFactor ]: 776,
  13029. [ DstColorFactor ]: 774,
  13030. [ DstAlphaFactor ]: 772,
  13031. [ OneMinusSrcColorFactor ]: 769,
  13032. [ OneMinusSrcAlphaFactor ]: 771,
  13033. [ OneMinusDstColorFactor ]: 775,
  13034. [ OneMinusDstAlphaFactor ]: 773
  13035. };
  13036. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13037. if ( blending === NoBlending ) {
  13038. if ( currentBlendingEnabled === true ) {
  13039. disable( 3042 );
  13040. currentBlendingEnabled = false;
  13041. }
  13042. return;
  13043. }
  13044. if ( currentBlendingEnabled === false ) {
  13045. enable( 3042 );
  13046. currentBlendingEnabled = true;
  13047. }
  13048. if ( blending !== CustomBlending ) {
  13049. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13050. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13051. gl.blendEquation( 32774 );
  13052. currentBlendEquation = AddEquation;
  13053. currentBlendEquationAlpha = AddEquation;
  13054. }
  13055. if ( premultipliedAlpha ) {
  13056. switch ( blending ) {
  13057. case NormalBlending:
  13058. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13059. break;
  13060. case AdditiveBlending:
  13061. gl.blendFunc( 1, 1 );
  13062. break;
  13063. case SubtractiveBlending:
  13064. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13065. break;
  13066. case MultiplyBlending:
  13067. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13068. break;
  13069. default:
  13070. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13071. break;
  13072. }
  13073. } else {
  13074. switch ( blending ) {
  13075. case NormalBlending:
  13076. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13077. break;
  13078. case AdditiveBlending:
  13079. gl.blendFunc( 770, 1 );
  13080. break;
  13081. case SubtractiveBlending:
  13082. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13083. break;
  13084. case MultiplyBlending:
  13085. gl.blendFunc( 0, 768 );
  13086. break;
  13087. default:
  13088. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13089. break;
  13090. }
  13091. }
  13092. currentBlendSrc = null;
  13093. currentBlendDst = null;
  13094. currentBlendSrcAlpha = null;
  13095. currentBlendDstAlpha = null;
  13096. currentBlending = blending;
  13097. currentPremultipledAlpha = premultipliedAlpha;
  13098. }
  13099. return;
  13100. }
  13101. // custom blending
  13102. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13103. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13104. blendDstAlpha = blendDstAlpha || blendDst;
  13105. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13106. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13107. currentBlendEquation = blendEquation;
  13108. currentBlendEquationAlpha = blendEquationAlpha;
  13109. }
  13110. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13111. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13112. currentBlendSrc = blendSrc;
  13113. currentBlendDst = blendDst;
  13114. currentBlendSrcAlpha = blendSrcAlpha;
  13115. currentBlendDstAlpha = blendDstAlpha;
  13116. }
  13117. currentBlending = blending;
  13118. currentPremultipledAlpha = null;
  13119. }
  13120. function setMaterial( material, frontFaceCW ) {
  13121. material.side === DoubleSide
  13122. ? disable( 2884 )
  13123. : enable( 2884 );
  13124. let flipSided = ( material.side === BackSide );
  13125. if ( frontFaceCW ) flipSided = ! flipSided;
  13126. setFlipSided( flipSided );
  13127. ( material.blending === NormalBlending && material.transparent === false )
  13128. ? setBlending( NoBlending )
  13129. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13130. depthBuffer.setFunc( material.depthFunc );
  13131. depthBuffer.setTest( material.depthTest );
  13132. depthBuffer.setMask( material.depthWrite );
  13133. colorBuffer.setMask( material.colorWrite );
  13134. const stencilWrite = material.stencilWrite;
  13135. stencilBuffer.setTest( stencilWrite );
  13136. if ( stencilWrite ) {
  13137. stencilBuffer.setMask( material.stencilWriteMask );
  13138. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13139. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13140. }
  13141. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13142. material.alphaToCoverage === true
  13143. ? enable( 32926 )
  13144. : disable( 32926 );
  13145. }
  13146. //
  13147. function setFlipSided( flipSided ) {
  13148. if ( currentFlipSided !== flipSided ) {
  13149. if ( flipSided ) {
  13150. gl.frontFace( 2304 );
  13151. } else {
  13152. gl.frontFace( 2305 );
  13153. }
  13154. currentFlipSided = flipSided;
  13155. }
  13156. }
  13157. function setCullFace( cullFace ) {
  13158. if ( cullFace !== CullFaceNone ) {
  13159. enable( 2884 );
  13160. if ( cullFace !== currentCullFace ) {
  13161. if ( cullFace === CullFaceBack ) {
  13162. gl.cullFace( 1029 );
  13163. } else if ( cullFace === CullFaceFront ) {
  13164. gl.cullFace( 1028 );
  13165. } else {
  13166. gl.cullFace( 1032 );
  13167. }
  13168. }
  13169. } else {
  13170. disable( 2884 );
  13171. }
  13172. currentCullFace = cullFace;
  13173. }
  13174. function setLineWidth( width ) {
  13175. if ( width !== currentLineWidth ) {
  13176. if ( lineWidthAvailable ) gl.lineWidth( width );
  13177. currentLineWidth = width;
  13178. }
  13179. }
  13180. function setPolygonOffset( polygonOffset, factor, units ) {
  13181. if ( polygonOffset ) {
  13182. enable( 32823 );
  13183. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13184. gl.polygonOffset( factor, units );
  13185. currentPolygonOffsetFactor = factor;
  13186. currentPolygonOffsetUnits = units;
  13187. }
  13188. } else {
  13189. disable( 32823 );
  13190. }
  13191. }
  13192. function setScissorTest( scissorTest ) {
  13193. if ( scissorTest ) {
  13194. enable( 3089 );
  13195. } else {
  13196. disable( 3089 );
  13197. }
  13198. }
  13199. // texture
  13200. function activeTexture( webglSlot ) {
  13201. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13202. if ( currentTextureSlot !== webglSlot ) {
  13203. gl.activeTexture( webglSlot );
  13204. currentTextureSlot = webglSlot;
  13205. }
  13206. }
  13207. function bindTexture( webglType, webglTexture, webglSlot ) {
  13208. if ( webglSlot === undefined ) {
  13209. if ( currentTextureSlot === null ) {
  13210. webglSlot = 33984 + maxTextures - 1;
  13211. } else {
  13212. webglSlot = currentTextureSlot;
  13213. }
  13214. }
  13215. let boundTexture = currentBoundTextures[ webglSlot ];
  13216. if ( boundTexture === undefined ) {
  13217. boundTexture = { type: undefined, texture: undefined };
  13218. currentBoundTextures[ webglSlot ] = boundTexture;
  13219. }
  13220. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13221. if ( currentTextureSlot !== webglSlot ) {
  13222. gl.activeTexture( webglSlot );
  13223. currentTextureSlot = webglSlot;
  13224. }
  13225. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13226. boundTexture.type = webglType;
  13227. boundTexture.texture = webglTexture;
  13228. }
  13229. }
  13230. function unbindTexture() {
  13231. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13232. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13233. gl.bindTexture( boundTexture.type, null );
  13234. boundTexture.type = undefined;
  13235. boundTexture.texture = undefined;
  13236. }
  13237. }
  13238. function compressedTexImage2D() {
  13239. try {
  13240. gl.compressedTexImage2D.apply( gl, arguments );
  13241. } catch ( error ) {
  13242. console.error( 'THREE.WebGLState:', error );
  13243. }
  13244. }
  13245. function texSubImage2D() {
  13246. try {
  13247. gl.texSubImage2D.apply( gl, arguments );
  13248. } catch ( error ) {
  13249. console.error( 'THREE.WebGLState:', error );
  13250. }
  13251. }
  13252. function texSubImage3D() {
  13253. try {
  13254. gl.texSubImage3D.apply( gl, arguments );
  13255. } catch ( error ) {
  13256. console.error( 'THREE.WebGLState:', error );
  13257. }
  13258. }
  13259. function compressedTexSubImage2D() {
  13260. try {
  13261. gl.compressedTexSubImage2D.apply( gl, arguments );
  13262. } catch ( error ) {
  13263. console.error( 'THREE.WebGLState:', error );
  13264. }
  13265. }
  13266. function texStorage2D() {
  13267. try {
  13268. gl.texStorage2D.apply( gl, arguments );
  13269. } catch ( error ) {
  13270. console.error( 'THREE.WebGLState:', error );
  13271. }
  13272. }
  13273. function texStorage3D() {
  13274. try {
  13275. gl.texStorage3D.apply( gl, arguments );
  13276. } catch ( error ) {
  13277. console.error( 'THREE.WebGLState:', error );
  13278. }
  13279. }
  13280. function texImage2D() {
  13281. try {
  13282. gl.texImage2D.apply( gl, arguments );
  13283. } catch ( error ) {
  13284. console.error( 'THREE.WebGLState:', error );
  13285. }
  13286. }
  13287. function texImage3D() {
  13288. try {
  13289. gl.texImage3D.apply( gl, arguments );
  13290. } catch ( error ) {
  13291. console.error( 'THREE.WebGLState:', error );
  13292. }
  13293. }
  13294. //
  13295. function scissor( scissor ) {
  13296. if ( currentScissor.equals( scissor ) === false ) {
  13297. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13298. currentScissor.copy( scissor );
  13299. }
  13300. }
  13301. function viewport( viewport ) {
  13302. if ( currentViewport.equals( viewport ) === false ) {
  13303. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13304. currentViewport.copy( viewport );
  13305. }
  13306. }
  13307. function updateUBOMapping( uniformsGroup, program ) {
  13308. let mapping = uboProgamMap.get( program );
  13309. if ( mapping === undefined ) {
  13310. mapping = new WeakMap();
  13311. uboProgamMap.set( program, mapping );
  13312. }
  13313. let blockIndex = mapping.get( uniformsGroup );
  13314. if ( blockIndex === undefined ) {
  13315. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13316. mapping.set( uniformsGroup, blockIndex );
  13317. }
  13318. }
  13319. function uniformBlockBinding( uniformsGroup, program ) {
  13320. const mapping = uboProgamMap.get( program );
  13321. const blockIndex = mapping.get( uniformsGroup );
  13322. if ( uboBindings.get( uniformsGroup ) !== blockIndex ) {
  13323. // bind shader specific block index to global block point
  13324. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13325. uboBindings.set( uniformsGroup, blockIndex );
  13326. }
  13327. }
  13328. //
  13329. function reset() {
  13330. // reset state
  13331. gl.disable( 3042 );
  13332. gl.disable( 2884 );
  13333. gl.disable( 2929 );
  13334. gl.disable( 32823 );
  13335. gl.disable( 3089 );
  13336. gl.disable( 2960 );
  13337. gl.disable( 32926 );
  13338. gl.blendEquation( 32774 );
  13339. gl.blendFunc( 1, 0 );
  13340. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13341. gl.colorMask( true, true, true, true );
  13342. gl.clearColor( 0, 0, 0, 0 );
  13343. gl.depthMask( true );
  13344. gl.depthFunc( 513 );
  13345. gl.clearDepth( 1 );
  13346. gl.stencilMask( 0xffffffff );
  13347. gl.stencilFunc( 519, 0, 0xffffffff );
  13348. gl.stencilOp( 7680, 7680, 7680 );
  13349. gl.clearStencil( 0 );
  13350. gl.cullFace( 1029 );
  13351. gl.frontFace( 2305 );
  13352. gl.polygonOffset( 0, 0 );
  13353. gl.activeTexture( 33984 );
  13354. gl.bindFramebuffer( 36160, null );
  13355. if ( isWebGL2 === true ) {
  13356. gl.bindFramebuffer( 36009, null );
  13357. gl.bindFramebuffer( 36008, null );
  13358. }
  13359. gl.useProgram( null );
  13360. gl.lineWidth( 1 );
  13361. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13362. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13363. // reset internals
  13364. enabledCapabilities = {};
  13365. currentTextureSlot = null;
  13366. currentBoundTextures = {};
  13367. currentBoundFramebuffers = {};
  13368. currentDrawbuffers = new WeakMap();
  13369. defaultDrawbuffers = [];
  13370. currentProgram = null;
  13371. currentBlendingEnabled = false;
  13372. currentBlending = null;
  13373. currentBlendEquation = null;
  13374. currentBlendSrc = null;
  13375. currentBlendDst = null;
  13376. currentBlendEquationAlpha = null;
  13377. currentBlendSrcAlpha = null;
  13378. currentBlendDstAlpha = null;
  13379. currentPremultipledAlpha = false;
  13380. currentFlipSided = null;
  13381. currentCullFace = null;
  13382. currentLineWidth = null;
  13383. currentPolygonOffsetFactor = null;
  13384. currentPolygonOffsetUnits = null;
  13385. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13386. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13387. colorBuffer.reset();
  13388. depthBuffer.reset();
  13389. stencilBuffer.reset();
  13390. }
  13391. return {
  13392. buffers: {
  13393. color: colorBuffer,
  13394. depth: depthBuffer,
  13395. stencil: stencilBuffer
  13396. },
  13397. enable: enable,
  13398. disable: disable,
  13399. bindFramebuffer: bindFramebuffer,
  13400. drawBuffers: drawBuffers,
  13401. useProgram: useProgram,
  13402. setBlending: setBlending,
  13403. setMaterial: setMaterial,
  13404. setFlipSided: setFlipSided,
  13405. setCullFace: setCullFace,
  13406. setLineWidth: setLineWidth,
  13407. setPolygonOffset: setPolygonOffset,
  13408. setScissorTest: setScissorTest,
  13409. activeTexture: activeTexture,
  13410. bindTexture: bindTexture,
  13411. unbindTexture: unbindTexture,
  13412. compressedTexImage2D: compressedTexImage2D,
  13413. texImage2D: texImage2D,
  13414. texImage3D: texImage3D,
  13415. updateUBOMapping: updateUBOMapping,
  13416. uniformBlockBinding: uniformBlockBinding,
  13417. texStorage2D: texStorage2D,
  13418. texStorage3D: texStorage3D,
  13419. texSubImage2D: texSubImage2D,
  13420. texSubImage3D: texSubImage3D,
  13421. compressedTexSubImage2D: compressedTexSubImage2D,
  13422. scissor: scissor,
  13423. viewport: viewport,
  13424. reset: reset
  13425. };
  13426. }
  13427. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13428. const isWebGL2 = capabilities.isWebGL2;
  13429. const maxTextures = capabilities.maxTextures;
  13430. const maxCubemapSize = capabilities.maxCubemapSize;
  13431. const maxTextureSize = capabilities.maxTextureSize;
  13432. const maxSamples = capabilities.maxSamples;
  13433. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13434. const supportsInvalidateFramebuffer = /OculusBrowser/g.test( navigator.userAgent );
  13435. const _videoTextures = new WeakMap();
  13436. let _canvas;
  13437. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13438. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13439. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13440. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13441. let useOffscreenCanvas = false;
  13442. try {
  13443. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13444. // eslint-disable-next-line compat/compat
  13445. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13446. } catch ( err ) {
  13447. // Ignore any errors
  13448. }
  13449. function createCanvas( width, height ) {
  13450. // Use OffscreenCanvas when available. Specially needed in web workers
  13451. return useOffscreenCanvas ?
  13452. // eslint-disable-next-line compat/compat
  13453. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13454. }
  13455. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13456. let scale = 1;
  13457. // handle case if texture exceeds max size
  13458. if ( image.width > maxSize || image.height > maxSize ) {
  13459. scale = maxSize / Math.max( image.width, image.height );
  13460. }
  13461. // only perform resize if necessary
  13462. if ( scale < 1 || needsPowerOfTwo === true ) {
  13463. // only perform resize for certain image types
  13464. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13465. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13466. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13467. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13468. const width = floor( scale * image.width );
  13469. const height = floor( scale * image.height );
  13470. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13471. // cube textures can't reuse the same canvas
  13472. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13473. canvas.width = width;
  13474. canvas.height = height;
  13475. const context = canvas.getContext( '2d' );
  13476. context.drawImage( image, 0, 0, width, height );
  13477. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13478. return canvas;
  13479. } else {
  13480. if ( 'data' in image ) {
  13481. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13482. }
  13483. return image;
  13484. }
  13485. }
  13486. return image;
  13487. }
  13488. function isPowerOfTwo$1( image ) {
  13489. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13490. }
  13491. function textureNeedsPowerOfTwo( texture ) {
  13492. if ( isWebGL2 ) return false;
  13493. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13494. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13495. }
  13496. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13497. return texture.generateMipmaps && supportsMips &&
  13498. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13499. }
  13500. function generateMipmap( target ) {
  13501. _gl.generateMipmap( target );
  13502. }
  13503. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13504. if ( isWebGL2 === false ) return glFormat;
  13505. if ( internalFormatName !== null ) {
  13506. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13507. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13508. }
  13509. let internalFormat = glFormat;
  13510. if ( glFormat === 6403 ) {
  13511. if ( glType === 5126 ) internalFormat = 33326;
  13512. if ( glType === 5131 ) internalFormat = 33325;
  13513. if ( glType === 5121 ) internalFormat = 33321;
  13514. }
  13515. if ( glFormat === 33319 ) {
  13516. if ( glType === 5126 ) internalFormat = 33328;
  13517. if ( glType === 5131 ) internalFormat = 33327;
  13518. if ( glType === 5121 ) internalFormat = 33323;
  13519. }
  13520. if ( glFormat === 6408 ) {
  13521. if ( glType === 5126 ) internalFormat = 34836;
  13522. if ( glType === 5131 ) internalFormat = 34842;
  13523. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856;
  13524. if ( glType === 32819 ) internalFormat = 32854;
  13525. if ( glType === 32820 ) internalFormat = 32855;
  13526. }
  13527. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13528. internalFormat === 33327 || internalFormat === 33328 ||
  13529. internalFormat === 34842 || internalFormat === 34836 ) {
  13530. extensions.get( 'EXT_color_buffer_float' );
  13531. }
  13532. return internalFormat;
  13533. }
  13534. function getMipLevels( texture, image, supportsMips ) {
  13535. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13536. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13537. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13538. // user-defined mipmaps
  13539. return texture.mipmaps.length;
  13540. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13541. return image.mipmaps.length;
  13542. } else {
  13543. // texture without mipmaps (only base level)
  13544. return 1;
  13545. }
  13546. }
  13547. // Fallback filters for non-power-of-2 textures
  13548. function filterFallback( f ) {
  13549. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13550. return 9728;
  13551. }
  13552. return 9729;
  13553. }
  13554. //
  13555. function onTextureDispose( event ) {
  13556. const texture = event.target;
  13557. texture.removeEventListener( 'dispose', onTextureDispose );
  13558. deallocateTexture( texture );
  13559. if ( texture.isVideoTexture ) {
  13560. _videoTextures.delete( texture );
  13561. }
  13562. }
  13563. function onRenderTargetDispose( event ) {
  13564. const renderTarget = event.target;
  13565. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13566. deallocateRenderTarget( renderTarget );
  13567. }
  13568. //
  13569. function deallocateTexture( texture ) {
  13570. const textureProperties = properties.get( texture );
  13571. if ( textureProperties.__webglInit === undefined ) return;
  13572. // check if it's necessary to remove the WebGLTexture object
  13573. const source = texture.source;
  13574. const webglTextures = _sources.get( source );
  13575. if ( webglTextures ) {
  13576. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13577. webglTexture.usedTimes --;
  13578. // the WebGLTexture object is not used anymore, remove it
  13579. if ( webglTexture.usedTimes === 0 ) {
  13580. deleteTexture( texture );
  13581. }
  13582. // remove the weak map entry if no WebGLTexture uses the source anymore
  13583. if ( Object.keys( webglTextures ).length === 0 ) {
  13584. _sources.delete( source );
  13585. }
  13586. }
  13587. properties.remove( texture );
  13588. }
  13589. function deleteTexture( texture ) {
  13590. const textureProperties = properties.get( texture );
  13591. _gl.deleteTexture( textureProperties.__webglTexture );
  13592. const source = texture.source;
  13593. const webglTextures = _sources.get( source );
  13594. delete webglTextures[ textureProperties.__cacheKey ];
  13595. info.memory.textures --;
  13596. }
  13597. function deallocateRenderTarget( renderTarget ) {
  13598. const texture = renderTarget.texture;
  13599. const renderTargetProperties = properties.get( renderTarget );
  13600. const textureProperties = properties.get( texture );
  13601. if ( textureProperties.__webglTexture !== undefined ) {
  13602. _gl.deleteTexture( textureProperties.__webglTexture );
  13603. info.memory.textures --;
  13604. }
  13605. if ( renderTarget.depthTexture ) {
  13606. renderTarget.depthTexture.dispose();
  13607. }
  13608. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13609. for ( let i = 0; i < 6; i ++ ) {
  13610. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13611. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13612. }
  13613. } else {
  13614. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13615. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13616. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13617. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13618. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13619. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13620. }
  13621. }
  13622. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13623. }
  13624. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13625. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13626. const attachmentProperties = properties.get( texture[ i ] );
  13627. if ( attachmentProperties.__webglTexture ) {
  13628. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13629. info.memory.textures --;
  13630. }
  13631. properties.remove( texture[ i ] );
  13632. }
  13633. }
  13634. properties.remove( texture );
  13635. properties.remove( renderTarget );
  13636. }
  13637. //
  13638. let textureUnits = 0;
  13639. function resetTextureUnits() {
  13640. textureUnits = 0;
  13641. }
  13642. function allocateTextureUnit() {
  13643. const textureUnit = textureUnits;
  13644. if ( textureUnit >= maxTextures ) {
  13645. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13646. }
  13647. textureUnits += 1;
  13648. return textureUnit;
  13649. }
  13650. function getTextureCacheKey( texture ) {
  13651. const array = [];
  13652. array.push( texture.wrapS );
  13653. array.push( texture.wrapT );
  13654. array.push( texture.magFilter );
  13655. array.push( texture.minFilter );
  13656. array.push( texture.anisotropy );
  13657. array.push( texture.internalFormat );
  13658. array.push( texture.format );
  13659. array.push( texture.type );
  13660. array.push( texture.generateMipmaps );
  13661. array.push( texture.premultiplyAlpha );
  13662. array.push( texture.flipY );
  13663. array.push( texture.unpackAlignment );
  13664. array.push( texture.encoding );
  13665. return array.join();
  13666. }
  13667. //
  13668. function setTexture2D( texture, slot ) {
  13669. const textureProperties = properties.get( texture );
  13670. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13671. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13672. const image = texture.image;
  13673. if ( image === null ) {
  13674. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13675. } else if ( image.complete === false ) {
  13676. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13677. } else {
  13678. uploadTexture( textureProperties, texture, slot );
  13679. return;
  13680. }
  13681. }
  13682. state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot );
  13683. }
  13684. function setTexture2DArray( texture, slot ) {
  13685. const textureProperties = properties.get( texture );
  13686. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13687. uploadTexture( textureProperties, texture, slot );
  13688. return;
  13689. }
  13690. state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot );
  13691. }
  13692. function setTexture3D( texture, slot ) {
  13693. const textureProperties = properties.get( texture );
  13694. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13695. uploadTexture( textureProperties, texture, slot );
  13696. return;
  13697. }
  13698. state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot );
  13699. }
  13700. function setTextureCube( texture, slot ) {
  13701. const textureProperties = properties.get( texture );
  13702. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13703. uploadCubeTexture( textureProperties, texture, slot );
  13704. return;
  13705. }
  13706. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  13707. }
  13708. const wrappingToGL = {
  13709. [ RepeatWrapping ]: 10497,
  13710. [ ClampToEdgeWrapping ]: 33071,
  13711. [ MirroredRepeatWrapping ]: 33648
  13712. };
  13713. const filterToGL = {
  13714. [ NearestFilter ]: 9728,
  13715. [ NearestMipmapNearestFilter ]: 9984,
  13716. [ NearestMipmapLinearFilter ]: 9986,
  13717. [ LinearFilter ]: 9729,
  13718. [ LinearMipmapNearestFilter ]: 9985,
  13719. [ LinearMipmapLinearFilter ]: 9987
  13720. };
  13721. function setTextureParameters( textureType, texture, supportsMips ) {
  13722. if ( supportsMips ) {
  13723. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13724. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13725. if ( textureType === 32879 || textureType === 35866 ) {
  13726. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13727. }
  13728. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13729. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13730. } else {
  13731. _gl.texParameteri( textureType, 10242, 33071 );
  13732. _gl.texParameteri( textureType, 10243, 33071 );
  13733. if ( textureType === 32879 || textureType === 35866 ) {
  13734. _gl.texParameteri( textureType, 32882, 33071 );
  13735. }
  13736. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13737. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13738. }
  13739. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13740. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13741. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13742. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13743. }
  13744. }
  13745. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13746. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13747. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13748. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13749. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13750. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13751. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13752. }
  13753. }
  13754. }
  13755. function initTexture( textureProperties, texture ) {
  13756. let forceUpload = false;
  13757. if ( textureProperties.__webglInit === undefined ) {
  13758. textureProperties.__webglInit = true;
  13759. texture.addEventListener( 'dispose', onTextureDispose );
  13760. }
  13761. // create Source <-> WebGLTextures mapping if necessary
  13762. const source = texture.source;
  13763. let webglTextures = _sources.get( source );
  13764. if ( webglTextures === undefined ) {
  13765. webglTextures = {};
  13766. _sources.set( source, webglTextures );
  13767. }
  13768. // check if there is already a WebGLTexture object for the given texture parameters
  13769. const textureCacheKey = getTextureCacheKey( texture );
  13770. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13771. // if not, create a new instance of WebGLTexture
  13772. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13773. // create new entry
  13774. webglTextures[ textureCacheKey ] = {
  13775. texture: _gl.createTexture(),
  13776. usedTimes: 0
  13777. };
  13778. info.memory.textures ++;
  13779. // when a new instance of WebGLTexture was created, a texture upload is required
  13780. // even if the image contents are identical
  13781. forceUpload = true;
  13782. }
  13783. webglTextures[ textureCacheKey ].usedTimes ++;
  13784. // every time the texture cache key changes, it's necessary to check if an instance of
  13785. // WebGLTexture can be deleted in order to avoid a memory leak.
  13786. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13787. if ( webglTexture !== undefined ) {
  13788. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13789. if ( webglTexture.usedTimes === 0 ) {
  13790. deleteTexture( texture );
  13791. }
  13792. }
  13793. // store references to cache key and WebGLTexture object
  13794. textureProperties.__cacheKey = textureCacheKey;
  13795. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13796. }
  13797. return forceUpload;
  13798. }
  13799. function uploadTexture( textureProperties, texture, slot ) {
  13800. let textureType = 3553;
  13801. if ( texture.isDataArrayTexture ) textureType = 35866;
  13802. if ( texture.isData3DTexture ) textureType = 32879;
  13803. const forceUpload = initTexture( textureProperties, texture );
  13804. const source = texture.source;
  13805. state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot );
  13806. const sourceProperties = properties.get( source );
  13807. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  13808. state.activeTexture( 33984 + slot );
  13809. _gl.pixelStorei( 37440, texture.flipY );
  13810. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13811. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13812. _gl.pixelStorei( 37443, 0 );
  13813. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13814. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13815. image = verifyColorSpace( texture, image );
  13816. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13817. glFormat = utils.convert( texture.format, texture.encoding );
  13818. let glType = utils.convert( texture.type ),
  13819. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13820. setTextureParameters( textureType, texture, supportsMips );
  13821. let mipmap;
  13822. const mipmaps = texture.mipmaps;
  13823. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13824. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  13825. const levels = getMipLevels( texture, image, supportsMips );
  13826. if ( texture.isDepthTexture ) {
  13827. // populate depth texture with dummy data
  13828. glInternalFormat = 6402;
  13829. if ( isWebGL2 ) {
  13830. if ( texture.type === FloatType ) {
  13831. glInternalFormat = 36012;
  13832. } else if ( texture.type === UnsignedIntType ) {
  13833. glInternalFormat = 33190;
  13834. } else if ( texture.type === UnsignedInt248Type ) {
  13835. glInternalFormat = 35056;
  13836. } else {
  13837. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13838. }
  13839. } else {
  13840. if ( texture.type === FloatType ) {
  13841. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13842. }
  13843. }
  13844. // validation checks for WebGL 1
  13845. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13846. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13847. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13848. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13849. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13850. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13851. texture.type = UnsignedIntType;
  13852. glType = utils.convert( texture.type );
  13853. }
  13854. }
  13855. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13856. // Depth stencil textures need the DEPTH_STENCIL internal format
  13857. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13858. glInternalFormat = 34041;
  13859. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13860. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13861. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13862. if ( texture.type !== UnsignedInt248Type ) {
  13863. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13864. texture.type = UnsignedInt248Type;
  13865. glType = utils.convert( texture.type );
  13866. }
  13867. }
  13868. //
  13869. if ( allocateMemory ) {
  13870. if ( useTexStorage ) {
  13871. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  13872. } else {
  13873. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13874. }
  13875. }
  13876. } else if ( texture.isDataTexture ) {
  13877. // use manually created mipmaps if available
  13878. // if there are no manual mipmaps
  13879. // set 0 level mipmap and then use GL to generate other mipmap levels
  13880. if ( mipmaps.length > 0 && supportsMips ) {
  13881. if ( useTexStorage && allocateMemory ) {
  13882. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13883. }
  13884. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13885. mipmap = mipmaps[ i ];
  13886. if ( useTexStorage ) {
  13887. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13888. } else {
  13889. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13890. }
  13891. }
  13892. texture.generateMipmaps = false;
  13893. } else {
  13894. if ( useTexStorage ) {
  13895. if ( allocateMemory ) {
  13896. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13897. }
  13898. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  13899. } else {
  13900. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13901. }
  13902. }
  13903. } else if ( texture.isCompressedTexture ) {
  13904. if ( useTexStorage && allocateMemory ) {
  13905. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13906. }
  13907. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13908. mipmap = mipmaps[ i ];
  13909. if ( texture.format !== RGBAFormat ) {
  13910. if ( glFormat !== null ) {
  13911. if ( useTexStorage ) {
  13912. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  13913. } else {
  13914. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13915. }
  13916. } else {
  13917. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13918. }
  13919. } else {
  13920. if ( useTexStorage ) {
  13921. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13922. } else {
  13923. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13924. }
  13925. }
  13926. }
  13927. } else if ( texture.isDataArrayTexture ) {
  13928. if ( useTexStorage ) {
  13929. if ( allocateMemory ) {
  13930. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  13931. }
  13932. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13933. } else {
  13934. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13935. }
  13936. } else if ( texture.isData3DTexture ) {
  13937. if ( useTexStorage ) {
  13938. if ( allocateMemory ) {
  13939. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  13940. }
  13941. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13942. } else {
  13943. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13944. }
  13945. } else if ( texture.isFramebufferTexture ) {
  13946. if ( allocateMemory ) {
  13947. if ( useTexStorage ) {
  13948. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13949. } else {
  13950. let width = image.width, height = image.height;
  13951. for ( let i = 0; i < levels; i ++ ) {
  13952. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  13953. width >>= 1;
  13954. height >>= 1;
  13955. }
  13956. }
  13957. }
  13958. } else {
  13959. // regular Texture (image, video, canvas)
  13960. // use manually created mipmaps if available
  13961. // if there are no manual mipmaps
  13962. // set 0 level mipmap and then use GL to generate other mipmap levels
  13963. if ( mipmaps.length > 0 && supportsMips ) {
  13964. if ( useTexStorage && allocateMemory ) {
  13965. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13966. }
  13967. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13968. mipmap = mipmaps[ i ];
  13969. if ( useTexStorage ) {
  13970. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  13971. } else {
  13972. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13973. }
  13974. }
  13975. texture.generateMipmaps = false;
  13976. } else {
  13977. if ( useTexStorage ) {
  13978. if ( allocateMemory ) {
  13979. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13980. }
  13981. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  13982. } else {
  13983. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13984. }
  13985. }
  13986. }
  13987. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13988. generateMipmap( textureType );
  13989. }
  13990. sourceProperties.__version = source.version;
  13991. if ( texture.onUpdate ) texture.onUpdate( texture );
  13992. }
  13993. textureProperties.__version = texture.version;
  13994. }
  13995. function uploadCubeTexture( textureProperties, texture, slot ) {
  13996. if ( texture.image.length !== 6 ) return;
  13997. const forceUpload = initTexture( textureProperties, texture );
  13998. const source = texture.source;
  13999. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14000. const sourceProperties = properties.get( source );
  14001. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14002. state.activeTexture( 33984 + slot );
  14003. _gl.pixelStorei( 37440, texture.flipY );
  14004. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14005. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14006. _gl.pixelStorei( 37443, 0 );
  14007. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14008. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14009. const cubeImage = [];
  14010. for ( let i = 0; i < 6; i ++ ) {
  14011. if ( ! isCompressed && ! isDataTexture ) {
  14012. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14013. } else {
  14014. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14015. }
  14016. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14017. }
  14018. const image = cubeImage[ 0 ],
  14019. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14020. glFormat = utils.convert( texture.format, texture.encoding ),
  14021. glType = utils.convert( texture.type ),
  14022. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14023. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14024. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14025. let levels = getMipLevels( texture, image, supportsMips );
  14026. setTextureParameters( 34067, texture, supportsMips );
  14027. let mipmaps;
  14028. if ( isCompressed ) {
  14029. if ( useTexStorage && allocateMemory ) {
  14030. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14031. }
  14032. for ( let i = 0; i < 6; i ++ ) {
  14033. mipmaps = cubeImage[ i ].mipmaps;
  14034. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14035. const mipmap = mipmaps[ j ];
  14036. if ( texture.format !== RGBAFormat ) {
  14037. if ( glFormat !== null ) {
  14038. if ( useTexStorage ) {
  14039. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14040. } else {
  14041. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14042. }
  14043. } else {
  14044. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14045. }
  14046. } else {
  14047. if ( useTexStorage ) {
  14048. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14049. } else {
  14050. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14051. }
  14052. }
  14053. }
  14054. }
  14055. } else {
  14056. mipmaps = texture.mipmaps;
  14057. if ( useTexStorage && allocateMemory ) {
  14058. // TODO: Uniformly handle mipmap definitions
  14059. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14060. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14061. if ( mipmaps.length > 0 ) levels ++;
  14062. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14063. }
  14064. for ( let i = 0; i < 6; i ++ ) {
  14065. if ( isDataTexture ) {
  14066. if ( useTexStorage ) {
  14067. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14068. } else {
  14069. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14070. }
  14071. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14072. const mipmap = mipmaps[ j ];
  14073. const mipmapImage = mipmap.image[ i ].image;
  14074. if ( useTexStorage ) {
  14075. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14076. } else {
  14077. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14078. }
  14079. }
  14080. } else {
  14081. if ( useTexStorage ) {
  14082. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14083. } else {
  14084. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14085. }
  14086. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14087. const mipmap = mipmaps[ j ];
  14088. if ( useTexStorage ) {
  14089. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14090. } else {
  14091. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14092. }
  14093. }
  14094. }
  14095. }
  14096. }
  14097. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14098. // We assume images for cube map have the same size.
  14099. generateMipmap( 34067 );
  14100. }
  14101. sourceProperties.__version = source.version;
  14102. if ( texture.onUpdate ) texture.onUpdate( texture );
  14103. }
  14104. textureProperties.__version = texture.version;
  14105. }
  14106. // Render targets
  14107. // Setup storage for target texture and bind it to correct framebuffer
  14108. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14109. const glFormat = utils.convert( texture.format, texture.encoding );
  14110. const glType = utils.convert( texture.type );
  14111. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14112. const renderTargetProperties = properties.get( renderTarget );
  14113. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14114. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14115. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14116. } else {
  14117. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14118. }
  14119. }
  14120. state.bindFramebuffer( 36160, framebuffer );
  14121. if ( useMultisampledRTT( renderTarget ) ) {
  14122. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14123. } else {
  14124. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14125. }
  14126. state.bindFramebuffer( 36160, null );
  14127. }
  14128. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14129. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14130. _gl.bindRenderbuffer( 36161, renderbuffer );
  14131. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14132. let glInternalFormat = 33189;
  14133. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14134. const depthTexture = renderTarget.depthTexture;
  14135. if ( depthTexture && depthTexture.isDepthTexture ) {
  14136. if ( depthTexture.type === FloatType ) {
  14137. glInternalFormat = 36012;
  14138. } else if ( depthTexture.type === UnsignedIntType ) {
  14139. glInternalFormat = 33190;
  14140. }
  14141. }
  14142. const samples = getRenderTargetSamples( renderTarget );
  14143. if ( useMultisampledRTT( renderTarget ) ) {
  14144. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14145. } else {
  14146. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14147. }
  14148. } else {
  14149. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14150. }
  14151. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14152. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14153. const samples = getRenderTargetSamples( renderTarget );
  14154. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14155. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14156. } else if ( useMultisampledRTT( renderTarget ) ) {
  14157. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14158. } else {
  14159. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14160. }
  14161. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14162. } else {
  14163. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14164. for ( let i = 0; i < textures.length; i ++ ) {
  14165. const texture = textures[ i ];
  14166. const glFormat = utils.convert( texture.format, texture.encoding );
  14167. const glType = utils.convert( texture.type );
  14168. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14169. const samples = getRenderTargetSamples( renderTarget );
  14170. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14171. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14172. } else if ( useMultisampledRTT( renderTarget ) ) {
  14173. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14174. } else {
  14175. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14176. }
  14177. }
  14178. }
  14179. _gl.bindRenderbuffer( 36161, null );
  14180. }
  14181. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14182. function setupDepthTexture( framebuffer, renderTarget ) {
  14183. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14184. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14185. state.bindFramebuffer( 36160, framebuffer );
  14186. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14187. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14188. }
  14189. // upload an empty depth texture with framebuffer size
  14190. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14191. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14192. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14193. renderTarget.depthTexture.image.width = renderTarget.width;
  14194. renderTarget.depthTexture.image.height = renderTarget.height;
  14195. renderTarget.depthTexture.needsUpdate = true;
  14196. }
  14197. setTexture2D( renderTarget.depthTexture, 0 );
  14198. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14199. const samples = getRenderTargetSamples( renderTarget );
  14200. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14201. if ( useMultisampledRTT( renderTarget ) ) {
  14202. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14203. } else {
  14204. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14205. }
  14206. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14207. if ( useMultisampledRTT( renderTarget ) ) {
  14208. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14209. } else {
  14210. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14211. }
  14212. } else {
  14213. throw new Error( 'Unknown depthTexture format' );
  14214. }
  14215. }
  14216. // Setup GL resources for a non-texture depth buffer
  14217. function setupDepthRenderbuffer( renderTarget ) {
  14218. const renderTargetProperties = properties.get( renderTarget );
  14219. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14220. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14221. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14222. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14223. } else {
  14224. if ( isCube ) {
  14225. renderTargetProperties.__webglDepthbuffer = [];
  14226. for ( let i = 0; i < 6; i ++ ) {
  14227. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14228. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14229. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14230. }
  14231. } else {
  14232. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14233. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14234. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14235. }
  14236. }
  14237. state.bindFramebuffer( 36160, null );
  14238. }
  14239. // rebind framebuffer with external textures
  14240. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14241. const renderTargetProperties = properties.get( renderTarget );
  14242. if ( colorTexture !== undefined ) {
  14243. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14244. }
  14245. if ( depthTexture !== undefined ) {
  14246. setupDepthRenderbuffer( renderTarget );
  14247. }
  14248. }
  14249. // Set up GL resources for the render target
  14250. function setupRenderTarget( renderTarget ) {
  14251. const texture = renderTarget.texture;
  14252. const renderTargetProperties = properties.get( renderTarget );
  14253. const textureProperties = properties.get( texture );
  14254. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14255. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14256. if ( textureProperties.__webglTexture === undefined ) {
  14257. textureProperties.__webglTexture = _gl.createTexture();
  14258. }
  14259. textureProperties.__version = texture.version;
  14260. info.memory.textures ++;
  14261. }
  14262. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14263. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14264. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14265. // Setup framebuffer
  14266. if ( isCube ) {
  14267. renderTargetProperties.__webglFramebuffer = [];
  14268. for ( let i = 0; i < 6; i ++ ) {
  14269. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14270. }
  14271. } else {
  14272. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14273. if ( isMultipleRenderTargets ) {
  14274. if ( capabilities.drawBuffers ) {
  14275. const textures = renderTarget.texture;
  14276. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14277. const attachmentProperties = properties.get( textures[ i ] );
  14278. if ( attachmentProperties.__webglTexture === undefined ) {
  14279. attachmentProperties.__webglTexture = _gl.createTexture();
  14280. info.memory.textures ++;
  14281. }
  14282. }
  14283. } else {
  14284. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14285. }
  14286. }
  14287. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14288. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14289. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14290. renderTargetProperties.__webglColorRenderbuffer = [];
  14291. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14292. for ( let i = 0; i < textures.length; i ++ ) {
  14293. const texture = textures[ i ];
  14294. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14295. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14296. const glFormat = utils.convert( texture.format, texture.encoding );
  14297. const glType = utils.convert( texture.type );
  14298. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14299. const samples = getRenderTargetSamples( renderTarget );
  14300. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14301. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14302. }
  14303. _gl.bindRenderbuffer( 36161, null );
  14304. if ( renderTarget.depthBuffer ) {
  14305. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14306. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14307. }
  14308. state.bindFramebuffer( 36160, null );
  14309. }
  14310. }
  14311. // Setup color buffer
  14312. if ( isCube ) {
  14313. state.bindTexture( 34067, textureProperties.__webglTexture );
  14314. setTextureParameters( 34067, texture, supportsMips );
  14315. for ( let i = 0; i < 6; i ++ ) {
  14316. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14317. }
  14318. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14319. generateMipmap( 34067 );
  14320. }
  14321. state.unbindTexture();
  14322. } else if ( isMultipleRenderTargets ) {
  14323. const textures = renderTarget.texture;
  14324. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14325. const attachment = textures[ i ];
  14326. const attachmentProperties = properties.get( attachment );
  14327. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14328. setTextureParameters( 3553, attachment, supportsMips );
  14329. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14330. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14331. generateMipmap( 3553 );
  14332. }
  14333. }
  14334. state.unbindTexture();
  14335. } else {
  14336. let glTextureType = 3553;
  14337. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14338. if ( isWebGL2 ) {
  14339. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14340. } else {
  14341. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14342. }
  14343. }
  14344. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14345. setTextureParameters( glTextureType, texture, supportsMips );
  14346. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14347. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14348. generateMipmap( glTextureType );
  14349. }
  14350. state.unbindTexture();
  14351. }
  14352. // Setup depth and stencil buffers
  14353. if ( renderTarget.depthBuffer ) {
  14354. setupDepthRenderbuffer( renderTarget );
  14355. }
  14356. }
  14357. function updateRenderTargetMipmap( renderTarget ) {
  14358. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14359. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14360. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14361. const texture = textures[ i ];
  14362. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14363. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14364. const webglTexture = properties.get( texture ).__webglTexture;
  14365. state.bindTexture( target, webglTexture );
  14366. generateMipmap( target );
  14367. state.unbindTexture();
  14368. }
  14369. }
  14370. }
  14371. function updateMultisampleRenderTarget( renderTarget ) {
  14372. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14373. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14374. const width = renderTarget.width;
  14375. const height = renderTarget.height;
  14376. let mask = 16384;
  14377. const invalidationArray = [];
  14378. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14379. const renderTargetProperties = properties.get( renderTarget );
  14380. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14381. // If MRT we need to remove FBO attachments
  14382. if ( isMultipleRenderTargets ) {
  14383. for ( let i = 0; i < textures.length; i ++ ) {
  14384. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14385. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14386. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14387. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14388. }
  14389. }
  14390. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14391. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14392. for ( let i = 0; i < textures.length; i ++ ) {
  14393. invalidationArray.push( 36064 + i );
  14394. if ( renderTarget.depthBuffer ) {
  14395. invalidationArray.push( depthStyle );
  14396. }
  14397. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14398. if ( ignoreDepthValues === false ) {
  14399. if ( renderTarget.depthBuffer ) mask |= 256;
  14400. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14401. }
  14402. if ( isMultipleRenderTargets ) {
  14403. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14404. }
  14405. if ( ignoreDepthValues === true ) {
  14406. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14407. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14408. }
  14409. if ( isMultipleRenderTargets ) {
  14410. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14411. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14412. }
  14413. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14414. if ( supportsInvalidateFramebuffer ) {
  14415. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14416. }
  14417. }
  14418. state.bindFramebuffer( 36008, null );
  14419. state.bindFramebuffer( 36009, null );
  14420. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14421. if ( isMultipleRenderTargets ) {
  14422. for ( let i = 0; i < textures.length; i ++ ) {
  14423. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14424. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14425. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14426. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14427. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14428. }
  14429. }
  14430. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14431. }
  14432. }
  14433. function getRenderTargetSamples( renderTarget ) {
  14434. return Math.min( maxSamples, renderTarget.samples );
  14435. }
  14436. function useMultisampledRTT( renderTarget ) {
  14437. const renderTargetProperties = properties.get( renderTarget );
  14438. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14439. }
  14440. function updateVideoTexture( texture ) {
  14441. const frame = info.render.frame;
  14442. // Check the last frame we updated the VideoTexture
  14443. if ( _videoTextures.get( texture ) !== frame ) {
  14444. _videoTextures.set( texture, frame );
  14445. texture.update();
  14446. }
  14447. }
  14448. function verifyColorSpace( texture, image ) {
  14449. const encoding = texture.encoding;
  14450. const format = texture.format;
  14451. const type = texture.type;
  14452. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14453. if ( encoding !== LinearEncoding ) {
  14454. // sRGB
  14455. if ( encoding === sRGBEncoding ) {
  14456. if ( isWebGL2 === false ) {
  14457. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14458. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14459. texture.format = _SRGBAFormat;
  14460. // it's not possible to generate mips in WebGL 1 with this extension
  14461. texture.minFilter = LinearFilter;
  14462. texture.generateMipmaps = false;
  14463. } else {
  14464. // slow fallback (CPU decode)
  14465. image = ImageUtils.sRGBToLinear( image );
  14466. }
  14467. } else {
  14468. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14469. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14470. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14471. }
  14472. }
  14473. } else {
  14474. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14475. }
  14476. }
  14477. return image;
  14478. }
  14479. //
  14480. this.allocateTextureUnit = allocateTextureUnit;
  14481. this.resetTextureUnits = resetTextureUnits;
  14482. this.setTexture2D = setTexture2D;
  14483. this.setTexture2DArray = setTexture2DArray;
  14484. this.setTexture3D = setTexture3D;
  14485. this.setTextureCube = setTextureCube;
  14486. this.rebindTextures = rebindTextures;
  14487. this.setupRenderTarget = setupRenderTarget;
  14488. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14489. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14490. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14491. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14492. this.useMultisampledRTT = useMultisampledRTT;
  14493. }
  14494. function WebGLUtils( gl, extensions, capabilities ) {
  14495. const isWebGL2 = capabilities.isWebGL2;
  14496. function convert( p, encoding = null ) {
  14497. let extension;
  14498. if ( p === UnsignedByteType ) return 5121;
  14499. if ( p === UnsignedShort4444Type ) return 32819;
  14500. if ( p === UnsignedShort5551Type ) return 32820;
  14501. if ( p === ByteType ) return 5120;
  14502. if ( p === ShortType ) return 5122;
  14503. if ( p === UnsignedShortType ) return 5123;
  14504. if ( p === IntType ) return 5124;
  14505. if ( p === UnsignedIntType ) return 5125;
  14506. if ( p === FloatType ) return 5126;
  14507. if ( p === HalfFloatType ) {
  14508. if ( isWebGL2 ) return 5131;
  14509. extension = extensions.get( 'OES_texture_half_float' );
  14510. if ( extension !== null ) {
  14511. return extension.HALF_FLOAT_OES;
  14512. } else {
  14513. return null;
  14514. }
  14515. }
  14516. if ( p === AlphaFormat ) return 6406;
  14517. if ( p === RGBAFormat ) return 6408;
  14518. if ( p === LuminanceFormat ) return 6409;
  14519. if ( p === LuminanceAlphaFormat ) return 6410;
  14520. if ( p === DepthFormat ) return 6402;
  14521. if ( p === DepthStencilFormat ) return 34041;
  14522. if ( p === RedFormat ) return 6403;
  14523. // @deprecated since r137
  14524. if ( p === RGBFormat ) {
  14525. console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' );
  14526. return 6408;
  14527. }
  14528. // WebGL 1 sRGB fallback
  14529. if ( p === _SRGBAFormat ) {
  14530. extension = extensions.get( 'EXT_sRGB' );
  14531. if ( extension !== null ) {
  14532. return extension.SRGB_ALPHA_EXT;
  14533. } else {
  14534. return null;
  14535. }
  14536. }
  14537. // WebGL2 formats.
  14538. if ( p === RedIntegerFormat ) return 36244;
  14539. if ( p === RGFormat ) return 33319;
  14540. if ( p === RGIntegerFormat ) return 33320;
  14541. if ( p === RGBAIntegerFormat ) return 36249;
  14542. // S3TC
  14543. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14544. if ( encoding === sRGBEncoding ) {
  14545. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14546. if ( extension !== null ) {
  14547. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14548. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14549. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14550. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14551. } else {
  14552. return null;
  14553. }
  14554. } else {
  14555. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14556. if ( extension !== null ) {
  14557. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14558. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14559. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14560. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14561. } else {
  14562. return null;
  14563. }
  14564. }
  14565. }
  14566. // PVRTC
  14567. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14568. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14569. if ( extension !== null ) {
  14570. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14571. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14572. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14573. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14574. } else {
  14575. return null;
  14576. }
  14577. }
  14578. // ETC1
  14579. if ( p === RGB_ETC1_Format ) {
  14580. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14581. if ( extension !== null ) {
  14582. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14583. } else {
  14584. return null;
  14585. }
  14586. }
  14587. // ETC2
  14588. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14589. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14590. if ( extension !== null ) {
  14591. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14592. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14593. } else {
  14594. return null;
  14595. }
  14596. }
  14597. // ASTC
  14598. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14599. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14600. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14601. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14602. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14603. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14604. if ( extension !== null ) {
  14605. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14606. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14607. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14608. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14609. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14610. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14611. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14612. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14613. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14614. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14615. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14616. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14617. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14618. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14619. } else {
  14620. return null;
  14621. }
  14622. }
  14623. // BPTC
  14624. if ( p === RGBA_BPTC_Format ) {
  14625. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14626. if ( extension !== null ) {
  14627. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14628. } else {
  14629. return null;
  14630. }
  14631. }
  14632. //
  14633. if ( p === UnsignedInt248Type ) {
  14634. if ( isWebGL2 ) return 34042;
  14635. extension = extensions.get( 'WEBGL_depth_texture' );
  14636. if ( extension !== null ) {
  14637. return extension.UNSIGNED_INT_24_8_WEBGL;
  14638. } else {
  14639. return null;
  14640. }
  14641. }
  14642. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14643. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14644. }
  14645. return { convert: convert };
  14646. }
  14647. class ArrayCamera extends PerspectiveCamera {
  14648. constructor( array = [] ) {
  14649. super();
  14650. this.isArrayCamera = true;
  14651. this.cameras = array;
  14652. }
  14653. }
  14654. class Group extends Object3D {
  14655. constructor() {
  14656. super();
  14657. this.isGroup = true;
  14658. this.type = 'Group';
  14659. }
  14660. }
  14661. const _moveEvent = { type: 'move' };
  14662. class WebXRController {
  14663. constructor() {
  14664. this._targetRay = null;
  14665. this._grip = null;
  14666. this._hand = null;
  14667. }
  14668. getHandSpace() {
  14669. if ( this._hand === null ) {
  14670. this._hand = new Group();
  14671. this._hand.matrixAutoUpdate = false;
  14672. this._hand.visible = false;
  14673. this._hand.joints = {};
  14674. this._hand.inputState = { pinching: false };
  14675. }
  14676. return this._hand;
  14677. }
  14678. getTargetRaySpace() {
  14679. if ( this._targetRay === null ) {
  14680. this._targetRay = new Group();
  14681. this._targetRay.matrixAutoUpdate = false;
  14682. this._targetRay.visible = false;
  14683. this._targetRay.hasLinearVelocity = false;
  14684. this._targetRay.linearVelocity = new Vector3();
  14685. this._targetRay.hasAngularVelocity = false;
  14686. this._targetRay.angularVelocity = new Vector3();
  14687. }
  14688. return this._targetRay;
  14689. }
  14690. getGripSpace() {
  14691. if ( this._grip === null ) {
  14692. this._grip = new Group();
  14693. this._grip.matrixAutoUpdate = false;
  14694. this._grip.visible = false;
  14695. this._grip.hasLinearVelocity = false;
  14696. this._grip.linearVelocity = new Vector3();
  14697. this._grip.hasAngularVelocity = false;
  14698. this._grip.angularVelocity = new Vector3();
  14699. }
  14700. return this._grip;
  14701. }
  14702. dispatchEvent( event ) {
  14703. if ( this._targetRay !== null ) {
  14704. this._targetRay.dispatchEvent( event );
  14705. }
  14706. if ( this._grip !== null ) {
  14707. this._grip.dispatchEvent( event );
  14708. }
  14709. if ( this._hand !== null ) {
  14710. this._hand.dispatchEvent( event );
  14711. }
  14712. return this;
  14713. }
  14714. disconnect( inputSource ) {
  14715. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14716. if ( this._targetRay !== null ) {
  14717. this._targetRay.visible = false;
  14718. }
  14719. if ( this._grip !== null ) {
  14720. this._grip.visible = false;
  14721. }
  14722. if ( this._hand !== null ) {
  14723. this._hand.visible = false;
  14724. }
  14725. return this;
  14726. }
  14727. update( inputSource, frame, referenceSpace ) {
  14728. let inputPose = null;
  14729. let gripPose = null;
  14730. let handPose = null;
  14731. const targetRay = this._targetRay;
  14732. const grip = this._grip;
  14733. const hand = this._hand;
  14734. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14735. if ( hand && inputSource.hand ) {
  14736. handPose = true;
  14737. for ( const inputjoint of inputSource.hand.values() ) {
  14738. // Update the joints groups with the XRJoint poses
  14739. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14740. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14741. // The transform of this joint will be updated with the joint pose on each frame
  14742. const joint = new Group();
  14743. joint.matrixAutoUpdate = false;
  14744. joint.visible = false;
  14745. hand.joints[ inputjoint.jointName ] = joint;
  14746. // ??
  14747. hand.add( joint );
  14748. }
  14749. const joint = hand.joints[ inputjoint.jointName ];
  14750. if ( jointPose !== null ) {
  14751. joint.matrix.fromArray( jointPose.transform.matrix );
  14752. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14753. joint.jointRadius = jointPose.radius;
  14754. }
  14755. joint.visible = jointPose !== null;
  14756. }
  14757. // Custom events
  14758. // Check pinchz
  14759. const indexTip = hand.joints[ 'index-finger-tip' ];
  14760. const thumbTip = hand.joints[ 'thumb-tip' ];
  14761. const distance = indexTip.position.distanceTo( thumbTip.position );
  14762. const distanceToPinch = 0.02;
  14763. const threshold = 0.005;
  14764. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14765. hand.inputState.pinching = false;
  14766. this.dispatchEvent( {
  14767. type: 'pinchend',
  14768. handedness: inputSource.handedness,
  14769. target: this
  14770. } );
  14771. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14772. hand.inputState.pinching = true;
  14773. this.dispatchEvent( {
  14774. type: 'pinchstart',
  14775. handedness: inputSource.handedness,
  14776. target: this
  14777. } );
  14778. }
  14779. } else {
  14780. if ( grip !== null && inputSource.gripSpace ) {
  14781. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14782. if ( gripPose !== null ) {
  14783. grip.matrix.fromArray( gripPose.transform.matrix );
  14784. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14785. if ( gripPose.linearVelocity ) {
  14786. grip.hasLinearVelocity = true;
  14787. grip.linearVelocity.copy( gripPose.linearVelocity );
  14788. } else {
  14789. grip.hasLinearVelocity = false;
  14790. }
  14791. if ( gripPose.angularVelocity ) {
  14792. grip.hasAngularVelocity = true;
  14793. grip.angularVelocity.copy( gripPose.angularVelocity );
  14794. } else {
  14795. grip.hasAngularVelocity = false;
  14796. }
  14797. }
  14798. }
  14799. }
  14800. if ( targetRay !== null ) {
  14801. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14802. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14803. if ( inputPose === null && gripPose !== null ) {
  14804. inputPose = gripPose;
  14805. }
  14806. if ( inputPose !== null ) {
  14807. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14808. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14809. if ( inputPose.linearVelocity ) {
  14810. targetRay.hasLinearVelocity = true;
  14811. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14812. } else {
  14813. targetRay.hasLinearVelocity = false;
  14814. }
  14815. if ( inputPose.angularVelocity ) {
  14816. targetRay.hasAngularVelocity = true;
  14817. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14818. } else {
  14819. targetRay.hasAngularVelocity = false;
  14820. }
  14821. this.dispatchEvent( _moveEvent );
  14822. }
  14823. }
  14824. }
  14825. if ( targetRay !== null ) {
  14826. targetRay.visible = ( inputPose !== null );
  14827. }
  14828. if ( grip !== null ) {
  14829. grip.visible = ( gripPose !== null );
  14830. }
  14831. if ( hand !== null ) {
  14832. hand.visible = ( handPose !== null );
  14833. }
  14834. return this;
  14835. }
  14836. }
  14837. class DepthTexture extends Texture {
  14838. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14839. format = format !== undefined ? format : DepthFormat;
  14840. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14841. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14842. }
  14843. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  14844. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14845. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14846. this.isDepthTexture = true;
  14847. this.image = { width: width, height: height };
  14848. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14849. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14850. this.flipY = false;
  14851. this.generateMipmaps = false;
  14852. }
  14853. }
  14854. class WebXRManager extends EventDispatcher {
  14855. constructor( renderer, gl ) {
  14856. super();
  14857. const scope = this;
  14858. let session = null;
  14859. let framebufferScaleFactor = 1.0;
  14860. let referenceSpace = null;
  14861. let referenceSpaceType = 'local-floor';
  14862. let customReferenceSpace = null;
  14863. let pose = null;
  14864. let glBinding = null;
  14865. let glProjLayer = null;
  14866. let glBaseLayer = null;
  14867. let xrFrame = null;
  14868. const attributes = gl.getContextAttributes();
  14869. let initialRenderTarget = null;
  14870. let newRenderTarget = null;
  14871. const controllers = [];
  14872. const controllerInputSources = [];
  14873. //
  14874. const cameraL = new PerspectiveCamera();
  14875. cameraL.layers.enable( 1 );
  14876. cameraL.viewport = new Vector4();
  14877. const cameraR = new PerspectiveCamera();
  14878. cameraR.layers.enable( 2 );
  14879. cameraR.viewport = new Vector4();
  14880. const cameras = [ cameraL, cameraR ];
  14881. const cameraVR = new ArrayCamera();
  14882. cameraVR.layers.enable( 1 );
  14883. cameraVR.layers.enable( 2 );
  14884. let _currentDepthNear = null;
  14885. let _currentDepthFar = null;
  14886. //
  14887. this.cameraAutoUpdate = true;
  14888. this.enabled = false;
  14889. this.isPresenting = false;
  14890. this.getController = function ( index ) {
  14891. let controller = controllers[ index ];
  14892. if ( controller === undefined ) {
  14893. controller = new WebXRController();
  14894. controllers[ index ] = controller;
  14895. }
  14896. return controller.getTargetRaySpace();
  14897. };
  14898. this.getControllerGrip = function ( index ) {
  14899. let controller = controllers[ index ];
  14900. if ( controller === undefined ) {
  14901. controller = new WebXRController();
  14902. controllers[ index ] = controller;
  14903. }
  14904. return controller.getGripSpace();
  14905. };
  14906. this.getHand = function ( index ) {
  14907. let controller = controllers[ index ];
  14908. if ( controller === undefined ) {
  14909. controller = new WebXRController();
  14910. controllers[ index ] = controller;
  14911. }
  14912. return controller.getHandSpace();
  14913. };
  14914. //
  14915. function onSessionEvent( event ) {
  14916. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  14917. if ( controllerIndex === - 1 ) {
  14918. return;
  14919. }
  14920. const controller = controllers[ controllerIndex ];
  14921. if ( controller !== undefined ) {
  14922. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14923. }
  14924. }
  14925. function onSessionEnd() {
  14926. session.removeEventListener( 'select', onSessionEvent );
  14927. session.removeEventListener( 'selectstart', onSessionEvent );
  14928. session.removeEventListener( 'selectend', onSessionEvent );
  14929. session.removeEventListener( 'squeeze', onSessionEvent );
  14930. session.removeEventListener( 'squeezestart', onSessionEvent );
  14931. session.removeEventListener( 'squeezeend', onSessionEvent );
  14932. session.removeEventListener( 'end', onSessionEnd );
  14933. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  14934. for ( let i = 0; i < controllers.length; i ++ ) {
  14935. const inputSource = controllerInputSources[ i ];
  14936. if ( inputSource === null ) continue;
  14937. controllerInputSources[ i ] = null;
  14938. controllers[ i ].disconnect( inputSource );
  14939. }
  14940. _currentDepthNear = null;
  14941. _currentDepthFar = null;
  14942. // restore framebuffer/rendering state
  14943. renderer.setRenderTarget( initialRenderTarget );
  14944. glBaseLayer = null;
  14945. glProjLayer = null;
  14946. glBinding = null;
  14947. session = null;
  14948. newRenderTarget = null;
  14949. //
  14950. animation.stop();
  14951. scope.isPresenting = false;
  14952. scope.dispatchEvent( { type: 'sessionend' } );
  14953. }
  14954. this.setFramebufferScaleFactor = function ( value ) {
  14955. framebufferScaleFactor = value;
  14956. if ( scope.isPresenting === true ) {
  14957. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14958. }
  14959. };
  14960. this.setReferenceSpaceType = function ( value ) {
  14961. referenceSpaceType = value;
  14962. if ( scope.isPresenting === true ) {
  14963. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14964. }
  14965. };
  14966. this.getReferenceSpace = function () {
  14967. return customReferenceSpace || referenceSpace;
  14968. };
  14969. this.setReferenceSpace = function ( space ) {
  14970. customReferenceSpace = space;
  14971. };
  14972. this.getBaseLayer = function () {
  14973. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14974. };
  14975. this.getBinding = function () {
  14976. return glBinding;
  14977. };
  14978. this.getFrame = function () {
  14979. return xrFrame;
  14980. };
  14981. this.getSession = function () {
  14982. return session;
  14983. };
  14984. this.setSession = async function ( value ) {
  14985. session = value;
  14986. if ( session !== null ) {
  14987. initialRenderTarget = renderer.getRenderTarget();
  14988. session.addEventListener( 'select', onSessionEvent );
  14989. session.addEventListener( 'selectstart', onSessionEvent );
  14990. session.addEventListener( 'selectend', onSessionEvent );
  14991. session.addEventListener( 'squeeze', onSessionEvent );
  14992. session.addEventListener( 'squeezestart', onSessionEvent );
  14993. session.addEventListener( 'squeezeend', onSessionEvent );
  14994. session.addEventListener( 'end', onSessionEnd );
  14995. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14996. if ( attributes.xrCompatible !== true ) {
  14997. await gl.makeXRCompatible();
  14998. }
  14999. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15000. const layerInit = {
  15001. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15002. alpha: attributes.alpha,
  15003. depth: attributes.depth,
  15004. stencil: attributes.stencil,
  15005. framebufferScaleFactor: framebufferScaleFactor
  15006. };
  15007. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15008. session.updateRenderState( { baseLayer: glBaseLayer } );
  15009. newRenderTarget = new WebGLRenderTarget(
  15010. glBaseLayer.framebufferWidth,
  15011. glBaseLayer.framebufferHeight,
  15012. {
  15013. format: RGBAFormat,
  15014. type: UnsignedByteType,
  15015. encoding: renderer.outputEncoding,
  15016. stencilBuffer: attributes.stencil
  15017. }
  15018. );
  15019. } else {
  15020. let depthFormat = null;
  15021. let depthType = null;
  15022. let glDepthFormat = null;
  15023. if ( attributes.depth ) {
  15024. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15025. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15026. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15027. }
  15028. const projectionlayerInit = {
  15029. colorFormat: 32856,
  15030. depthFormat: glDepthFormat,
  15031. scaleFactor: framebufferScaleFactor
  15032. };
  15033. glBinding = new XRWebGLBinding( session, gl );
  15034. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15035. session.updateRenderState( { layers: [ glProjLayer ] } );
  15036. newRenderTarget = new WebGLRenderTarget(
  15037. glProjLayer.textureWidth,
  15038. glProjLayer.textureHeight,
  15039. {
  15040. format: RGBAFormat,
  15041. type: UnsignedByteType,
  15042. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15043. stencilBuffer: attributes.stencil,
  15044. encoding: renderer.outputEncoding,
  15045. samples: attributes.antialias ? 4 : 0
  15046. } );
  15047. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15048. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15049. }
  15050. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15051. // Set foveation to maximum.
  15052. this.setFoveation( 1.0 );
  15053. customReferenceSpace = null;
  15054. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15055. animation.setContext( session );
  15056. animation.start();
  15057. scope.isPresenting = true;
  15058. scope.dispatchEvent( { type: 'sessionstart' } );
  15059. }
  15060. };
  15061. function onInputSourcesChange( event ) {
  15062. // Notify disconnected
  15063. for ( let i = 0; i < event.removed.length; i ++ ) {
  15064. const inputSource = event.removed[ i ];
  15065. const index = controllerInputSources.indexOf( inputSource );
  15066. if ( index >= 0 ) {
  15067. controllerInputSources[ index ] = null;
  15068. controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } );
  15069. }
  15070. }
  15071. // Notify connected
  15072. for ( let i = 0; i < event.added.length; i ++ ) {
  15073. const inputSource = event.added[ i ];
  15074. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15075. if ( controllerIndex === - 1 ) {
  15076. // Assign input source a controller that currently has no input source
  15077. for ( let i = 0; i < controllers.length; i ++ ) {
  15078. if ( i >= controllerInputSources.length ) {
  15079. controllerInputSources.push( inputSource );
  15080. controllerIndex = i;
  15081. break;
  15082. } else if ( controllerInputSources[ i ] === null ) {
  15083. controllerInputSources[ i ] = inputSource;
  15084. controllerIndex = i;
  15085. break;
  15086. }
  15087. }
  15088. // If all controllers do currently receive input we ignore new ones
  15089. if ( controllerIndex === - 1 ) break;
  15090. }
  15091. const controller = controllers[ controllerIndex ];
  15092. if ( controller ) {
  15093. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  15094. }
  15095. }
  15096. }
  15097. //
  15098. const cameraLPos = new Vector3();
  15099. const cameraRPos = new Vector3();
  15100. /**
  15101. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15102. * the cameras' projection and world matrices have already been set.
  15103. * And that near and far planes are identical for both cameras.
  15104. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15105. */
  15106. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15107. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15108. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15109. const ipd = cameraLPos.distanceTo( cameraRPos );
  15110. const projL = cameraL.projectionMatrix.elements;
  15111. const projR = cameraR.projectionMatrix.elements;
  15112. // VR systems will have identical far and near planes, and
  15113. // most likely identical top and bottom frustum extents.
  15114. // Use the left camera for these values.
  15115. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15116. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15117. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15118. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15119. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15120. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15121. const left = near * leftFov;
  15122. const right = near * rightFov;
  15123. // Calculate the new camera's position offset from the
  15124. // left camera. xOffset should be roughly half `ipd`.
  15125. const zOffset = ipd / ( - leftFov + rightFov );
  15126. const xOffset = zOffset * - leftFov;
  15127. // TODO: Better way to apply this offset?
  15128. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15129. camera.translateX( xOffset );
  15130. camera.translateZ( zOffset );
  15131. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15132. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15133. // Find the union of the frustum values of the cameras and scale
  15134. // the values so that the near plane's position does not change in world space,
  15135. // although must now be relative to the new union camera.
  15136. const near2 = near + zOffset;
  15137. const far2 = far + zOffset;
  15138. const left2 = left - xOffset;
  15139. const right2 = right + ( ipd - xOffset );
  15140. const top2 = topFov * far / far2 * near2;
  15141. const bottom2 = bottomFov * far / far2 * near2;
  15142. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15143. }
  15144. function updateCamera( camera, parent ) {
  15145. if ( parent === null ) {
  15146. camera.matrixWorld.copy( camera.matrix );
  15147. } else {
  15148. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15149. }
  15150. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15151. }
  15152. this.updateCamera = function ( camera ) {
  15153. if ( session === null ) return;
  15154. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15155. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15156. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15157. // Note that the new renderState won't apply until the next frame. See #18320
  15158. session.updateRenderState( {
  15159. depthNear: cameraVR.near,
  15160. depthFar: cameraVR.far
  15161. } );
  15162. _currentDepthNear = cameraVR.near;
  15163. _currentDepthFar = cameraVR.far;
  15164. }
  15165. const parent = camera.parent;
  15166. const cameras = cameraVR.cameras;
  15167. updateCamera( cameraVR, parent );
  15168. for ( let i = 0; i < cameras.length; i ++ ) {
  15169. updateCamera( cameras[ i ], parent );
  15170. }
  15171. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15172. // update user camera and its children
  15173. camera.matrix.copy( cameraVR.matrix );
  15174. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15175. const children = camera.children;
  15176. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15177. children[ i ].updateMatrixWorld( true );
  15178. }
  15179. // update projection matrix for proper view frustum culling
  15180. if ( cameras.length === 2 ) {
  15181. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15182. } else {
  15183. // assume single camera setup (AR)
  15184. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15185. }
  15186. };
  15187. this.getCamera = function () {
  15188. return cameraVR;
  15189. };
  15190. this.getFoveation = function () {
  15191. if ( glProjLayer !== null ) {
  15192. return glProjLayer.fixedFoveation;
  15193. }
  15194. if ( glBaseLayer !== null ) {
  15195. return glBaseLayer.fixedFoveation;
  15196. }
  15197. return undefined;
  15198. };
  15199. this.setFoveation = function ( foveation ) {
  15200. // 0 = no foveation = full resolution
  15201. // 1 = maximum foveation = the edges render at lower resolution
  15202. if ( glProjLayer !== null ) {
  15203. glProjLayer.fixedFoveation = foveation;
  15204. }
  15205. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15206. glBaseLayer.fixedFoveation = foveation;
  15207. }
  15208. };
  15209. // Animation Loop
  15210. let onAnimationFrameCallback = null;
  15211. function onAnimationFrame( time, frame ) {
  15212. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15213. xrFrame = frame;
  15214. if ( pose !== null ) {
  15215. const views = pose.views;
  15216. if ( glBaseLayer !== null ) {
  15217. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15218. renderer.setRenderTarget( newRenderTarget );
  15219. }
  15220. let cameraVRNeedsUpdate = false;
  15221. // check if it's necessary to rebuild cameraVR's camera list
  15222. if ( views.length !== cameraVR.cameras.length ) {
  15223. cameraVR.cameras.length = 0;
  15224. cameraVRNeedsUpdate = true;
  15225. }
  15226. for ( let i = 0; i < views.length; i ++ ) {
  15227. const view = views[ i ];
  15228. let viewport = null;
  15229. if ( glBaseLayer !== null ) {
  15230. viewport = glBaseLayer.getViewport( view );
  15231. } else {
  15232. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15233. viewport = glSubImage.viewport;
  15234. // For side-by-side projection, we only produce a single texture for both eyes.
  15235. if ( i === 0 ) {
  15236. renderer.setRenderTargetTextures(
  15237. newRenderTarget,
  15238. glSubImage.colorTexture,
  15239. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15240. renderer.setRenderTarget( newRenderTarget );
  15241. }
  15242. }
  15243. let camera = cameras[ i ];
  15244. if ( camera === undefined ) {
  15245. camera = new PerspectiveCamera();
  15246. camera.layers.enable( i );
  15247. camera.viewport = new Vector4();
  15248. cameras[ i ] = camera;
  15249. }
  15250. camera.matrix.fromArray( view.transform.matrix );
  15251. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15252. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15253. if ( i === 0 ) {
  15254. cameraVR.matrix.copy( camera.matrix );
  15255. }
  15256. if ( cameraVRNeedsUpdate === true ) {
  15257. cameraVR.cameras.push( camera );
  15258. }
  15259. }
  15260. }
  15261. //
  15262. for ( let i = 0; i < controllers.length; i ++ ) {
  15263. const inputSource = controllerInputSources[ i ];
  15264. const controller = controllers[ i ];
  15265. if ( inputSource !== null && controller !== undefined ) {
  15266. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15267. }
  15268. }
  15269. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15270. xrFrame = null;
  15271. }
  15272. const animation = new WebGLAnimation();
  15273. animation.setAnimationLoop( onAnimationFrame );
  15274. this.setAnimationLoop = function ( callback ) {
  15275. onAnimationFrameCallback = callback;
  15276. };
  15277. this.dispose = function () {};
  15278. }
  15279. }
  15280. function WebGLMaterials( renderer, properties ) {
  15281. function refreshFogUniforms( uniforms, fog ) {
  15282. uniforms.fogColor.value.copy( fog.color );
  15283. if ( fog.isFog ) {
  15284. uniforms.fogNear.value = fog.near;
  15285. uniforms.fogFar.value = fog.far;
  15286. } else if ( fog.isFogExp2 ) {
  15287. uniforms.fogDensity.value = fog.density;
  15288. }
  15289. }
  15290. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15291. if ( material.isMeshBasicMaterial ) {
  15292. refreshUniformsCommon( uniforms, material );
  15293. } else if ( material.isMeshLambertMaterial ) {
  15294. refreshUniformsCommon( uniforms, material );
  15295. } else if ( material.isMeshToonMaterial ) {
  15296. refreshUniformsCommon( uniforms, material );
  15297. refreshUniformsToon( uniforms, material );
  15298. } else if ( material.isMeshPhongMaterial ) {
  15299. refreshUniformsCommon( uniforms, material );
  15300. refreshUniformsPhong( uniforms, material );
  15301. } else if ( material.isMeshStandardMaterial ) {
  15302. refreshUniformsCommon( uniforms, material );
  15303. refreshUniformsStandard( uniforms, material );
  15304. if ( material.isMeshPhysicalMaterial ) {
  15305. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15306. }
  15307. } else if ( material.isMeshMatcapMaterial ) {
  15308. refreshUniformsCommon( uniforms, material );
  15309. refreshUniformsMatcap( uniforms, material );
  15310. } else if ( material.isMeshDepthMaterial ) {
  15311. refreshUniformsCommon( uniforms, material );
  15312. } else if ( material.isMeshDistanceMaterial ) {
  15313. refreshUniformsCommon( uniforms, material );
  15314. refreshUniformsDistance( uniforms, material );
  15315. } else if ( material.isMeshNormalMaterial ) {
  15316. refreshUniformsCommon( uniforms, material );
  15317. } else if ( material.isLineBasicMaterial ) {
  15318. refreshUniformsLine( uniforms, material );
  15319. if ( material.isLineDashedMaterial ) {
  15320. refreshUniformsDash( uniforms, material );
  15321. }
  15322. } else if ( material.isPointsMaterial ) {
  15323. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15324. } else if ( material.isSpriteMaterial ) {
  15325. refreshUniformsSprites( uniforms, material );
  15326. } else if ( material.isShadowMaterial ) {
  15327. uniforms.color.value.copy( material.color );
  15328. uniforms.opacity.value = material.opacity;
  15329. } else if ( material.isShaderMaterial ) {
  15330. material.uniformsNeedUpdate = false; // #15581
  15331. }
  15332. }
  15333. function refreshUniformsCommon( uniforms, material ) {
  15334. uniforms.opacity.value = material.opacity;
  15335. if ( material.color ) {
  15336. uniforms.diffuse.value.copy( material.color );
  15337. }
  15338. if ( material.emissive ) {
  15339. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15340. }
  15341. if ( material.map ) {
  15342. uniforms.map.value = material.map;
  15343. }
  15344. if ( material.alphaMap ) {
  15345. uniforms.alphaMap.value = material.alphaMap;
  15346. }
  15347. if ( material.bumpMap ) {
  15348. uniforms.bumpMap.value = material.bumpMap;
  15349. uniforms.bumpScale.value = material.bumpScale;
  15350. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15351. }
  15352. if ( material.displacementMap ) {
  15353. uniforms.displacementMap.value = material.displacementMap;
  15354. uniforms.displacementScale.value = material.displacementScale;
  15355. uniforms.displacementBias.value = material.displacementBias;
  15356. }
  15357. if ( material.emissiveMap ) {
  15358. uniforms.emissiveMap.value = material.emissiveMap;
  15359. }
  15360. if ( material.normalMap ) {
  15361. uniforms.normalMap.value = material.normalMap;
  15362. uniforms.normalScale.value.copy( material.normalScale );
  15363. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15364. }
  15365. if ( material.specularMap ) {
  15366. uniforms.specularMap.value = material.specularMap;
  15367. }
  15368. if ( material.alphaTest > 0 ) {
  15369. uniforms.alphaTest.value = material.alphaTest;
  15370. }
  15371. const envMap = properties.get( material ).envMap;
  15372. if ( envMap ) {
  15373. uniforms.envMap.value = envMap;
  15374. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15375. uniforms.reflectivity.value = material.reflectivity;
  15376. uniforms.ior.value = material.ior;
  15377. uniforms.refractionRatio.value = material.refractionRatio;
  15378. }
  15379. if ( material.lightMap ) {
  15380. uniforms.lightMap.value = material.lightMap;
  15381. // artist-friendly light intensity scaling factor
  15382. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15383. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15384. }
  15385. if ( material.aoMap ) {
  15386. uniforms.aoMap.value = material.aoMap;
  15387. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15388. }
  15389. // uv repeat and offset setting priorities
  15390. // 1. color map
  15391. // 2. specular map
  15392. // 3. displacementMap map
  15393. // 4. normal map
  15394. // 5. bump map
  15395. // 6. roughnessMap map
  15396. // 7. metalnessMap map
  15397. // 8. alphaMap map
  15398. // 9. emissiveMap map
  15399. // 10. clearcoat map
  15400. // 11. clearcoat normal map
  15401. // 12. clearcoat roughnessMap map
  15402. // 13. iridescence map
  15403. // 14. iridescence thickness map
  15404. // 15. specular intensity map
  15405. // 16. specular tint map
  15406. // 17. transmission map
  15407. // 18. thickness map
  15408. let uvScaleMap;
  15409. if ( material.map ) {
  15410. uvScaleMap = material.map;
  15411. } else if ( material.specularMap ) {
  15412. uvScaleMap = material.specularMap;
  15413. } else if ( material.displacementMap ) {
  15414. uvScaleMap = material.displacementMap;
  15415. } else if ( material.normalMap ) {
  15416. uvScaleMap = material.normalMap;
  15417. } else if ( material.bumpMap ) {
  15418. uvScaleMap = material.bumpMap;
  15419. } else if ( material.roughnessMap ) {
  15420. uvScaleMap = material.roughnessMap;
  15421. } else if ( material.metalnessMap ) {
  15422. uvScaleMap = material.metalnessMap;
  15423. } else if ( material.alphaMap ) {
  15424. uvScaleMap = material.alphaMap;
  15425. } else if ( material.emissiveMap ) {
  15426. uvScaleMap = material.emissiveMap;
  15427. } else if ( material.clearcoatMap ) {
  15428. uvScaleMap = material.clearcoatMap;
  15429. } else if ( material.clearcoatNormalMap ) {
  15430. uvScaleMap = material.clearcoatNormalMap;
  15431. } else if ( material.clearcoatRoughnessMap ) {
  15432. uvScaleMap = material.clearcoatRoughnessMap;
  15433. } else if ( material.iridescenceMap ) {
  15434. uvScaleMap = material.iridescenceMap;
  15435. } else if ( material.iridescenceThicknessMap ) {
  15436. uvScaleMap = material.iridescenceThicknessMap;
  15437. } else if ( material.specularIntensityMap ) {
  15438. uvScaleMap = material.specularIntensityMap;
  15439. } else if ( material.specularColorMap ) {
  15440. uvScaleMap = material.specularColorMap;
  15441. } else if ( material.transmissionMap ) {
  15442. uvScaleMap = material.transmissionMap;
  15443. } else if ( material.thicknessMap ) {
  15444. uvScaleMap = material.thicknessMap;
  15445. } else if ( material.sheenColorMap ) {
  15446. uvScaleMap = material.sheenColorMap;
  15447. } else if ( material.sheenRoughnessMap ) {
  15448. uvScaleMap = material.sheenRoughnessMap;
  15449. }
  15450. if ( uvScaleMap !== undefined ) {
  15451. // backwards compatibility
  15452. if ( uvScaleMap.isWebGLRenderTarget ) {
  15453. uvScaleMap = uvScaleMap.texture;
  15454. }
  15455. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15456. uvScaleMap.updateMatrix();
  15457. }
  15458. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15459. }
  15460. // uv repeat and offset setting priorities for uv2
  15461. // 1. ao map
  15462. // 2. light map
  15463. let uv2ScaleMap;
  15464. if ( material.aoMap ) {
  15465. uv2ScaleMap = material.aoMap;
  15466. } else if ( material.lightMap ) {
  15467. uv2ScaleMap = material.lightMap;
  15468. }
  15469. if ( uv2ScaleMap !== undefined ) {
  15470. // backwards compatibility
  15471. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15472. uv2ScaleMap = uv2ScaleMap.texture;
  15473. }
  15474. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15475. uv2ScaleMap.updateMatrix();
  15476. }
  15477. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15478. }
  15479. }
  15480. function refreshUniformsLine( uniforms, material ) {
  15481. uniforms.diffuse.value.copy( material.color );
  15482. uniforms.opacity.value = material.opacity;
  15483. }
  15484. function refreshUniformsDash( uniforms, material ) {
  15485. uniforms.dashSize.value = material.dashSize;
  15486. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15487. uniforms.scale.value = material.scale;
  15488. }
  15489. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15490. uniforms.diffuse.value.copy( material.color );
  15491. uniforms.opacity.value = material.opacity;
  15492. uniforms.size.value = material.size * pixelRatio;
  15493. uniforms.scale.value = height * 0.5;
  15494. if ( material.map ) {
  15495. uniforms.map.value = material.map;
  15496. }
  15497. if ( material.alphaMap ) {
  15498. uniforms.alphaMap.value = material.alphaMap;
  15499. }
  15500. if ( material.alphaTest > 0 ) {
  15501. uniforms.alphaTest.value = material.alphaTest;
  15502. }
  15503. // uv repeat and offset setting priorities
  15504. // 1. color map
  15505. // 2. alpha map
  15506. let uvScaleMap;
  15507. if ( material.map ) {
  15508. uvScaleMap = material.map;
  15509. } else if ( material.alphaMap ) {
  15510. uvScaleMap = material.alphaMap;
  15511. }
  15512. if ( uvScaleMap !== undefined ) {
  15513. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15514. uvScaleMap.updateMatrix();
  15515. }
  15516. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15517. }
  15518. }
  15519. function refreshUniformsSprites( uniforms, material ) {
  15520. uniforms.diffuse.value.copy( material.color );
  15521. uniforms.opacity.value = material.opacity;
  15522. uniforms.rotation.value = material.rotation;
  15523. if ( material.map ) {
  15524. uniforms.map.value = material.map;
  15525. }
  15526. if ( material.alphaMap ) {
  15527. uniforms.alphaMap.value = material.alphaMap;
  15528. }
  15529. if ( material.alphaTest > 0 ) {
  15530. uniforms.alphaTest.value = material.alphaTest;
  15531. }
  15532. // uv repeat and offset setting priorities
  15533. // 1. color map
  15534. // 2. alpha map
  15535. let uvScaleMap;
  15536. if ( material.map ) {
  15537. uvScaleMap = material.map;
  15538. } else if ( material.alphaMap ) {
  15539. uvScaleMap = material.alphaMap;
  15540. }
  15541. if ( uvScaleMap !== undefined ) {
  15542. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15543. uvScaleMap.updateMatrix();
  15544. }
  15545. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15546. }
  15547. }
  15548. function refreshUniformsPhong( uniforms, material ) {
  15549. uniforms.specular.value.copy( material.specular );
  15550. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15551. }
  15552. function refreshUniformsToon( uniforms, material ) {
  15553. if ( material.gradientMap ) {
  15554. uniforms.gradientMap.value = material.gradientMap;
  15555. }
  15556. }
  15557. function refreshUniformsStandard( uniforms, material ) {
  15558. uniforms.roughness.value = material.roughness;
  15559. uniforms.metalness.value = material.metalness;
  15560. if ( material.roughnessMap ) {
  15561. uniforms.roughnessMap.value = material.roughnessMap;
  15562. }
  15563. if ( material.metalnessMap ) {
  15564. uniforms.metalnessMap.value = material.metalnessMap;
  15565. }
  15566. const envMap = properties.get( material ).envMap;
  15567. if ( envMap ) {
  15568. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15569. uniforms.envMapIntensity.value = material.envMapIntensity;
  15570. }
  15571. }
  15572. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15573. uniforms.ior.value = material.ior; // also part of uniforms common
  15574. if ( material.sheen > 0 ) {
  15575. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15576. uniforms.sheenRoughness.value = material.sheenRoughness;
  15577. if ( material.sheenColorMap ) {
  15578. uniforms.sheenColorMap.value = material.sheenColorMap;
  15579. }
  15580. if ( material.sheenRoughnessMap ) {
  15581. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15582. }
  15583. }
  15584. if ( material.clearcoat > 0 ) {
  15585. uniforms.clearcoat.value = material.clearcoat;
  15586. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15587. if ( material.clearcoatMap ) {
  15588. uniforms.clearcoatMap.value = material.clearcoatMap;
  15589. }
  15590. if ( material.clearcoatRoughnessMap ) {
  15591. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15592. }
  15593. if ( material.clearcoatNormalMap ) {
  15594. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15595. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15596. if ( material.side === BackSide ) {
  15597. uniforms.clearcoatNormalScale.value.negate();
  15598. }
  15599. }
  15600. }
  15601. if ( material.iridescence > 0 ) {
  15602. uniforms.iridescence.value = material.iridescence;
  15603. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15604. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15605. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15606. if ( material.iridescenceMap ) {
  15607. uniforms.iridescenceMap.value = material.iridescenceMap;
  15608. }
  15609. if ( material.iridescenceThicknessMap ) {
  15610. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15611. }
  15612. }
  15613. if ( material.transmission > 0 ) {
  15614. uniforms.transmission.value = material.transmission;
  15615. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15616. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15617. if ( material.transmissionMap ) {
  15618. uniforms.transmissionMap.value = material.transmissionMap;
  15619. }
  15620. uniforms.thickness.value = material.thickness;
  15621. if ( material.thicknessMap ) {
  15622. uniforms.thicknessMap.value = material.thicknessMap;
  15623. }
  15624. uniforms.attenuationDistance.value = material.attenuationDistance;
  15625. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15626. }
  15627. uniforms.specularIntensity.value = material.specularIntensity;
  15628. uniforms.specularColor.value.copy( material.specularColor );
  15629. if ( material.specularIntensityMap ) {
  15630. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15631. }
  15632. if ( material.specularColorMap ) {
  15633. uniforms.specularColorMap.value = material.specularColorMap;
  15634. }
  15635. }
  15636. function refreshUniformsMatcap( uniforms, material ) {
  15637. if ( material.matcap ) {
  15638. uniforms.matcap.value = material.matcap;
  15639. }
  15640. }
  15641. function refreshUniformsDistance( uniforms, material ) {
  15642. uniforms.referencePosition.value.copy( material.referencePosition );
  15643. uniforms.nearDistance.value = material.nearDistance;
  15644. uniforms.farDistance.value = material.farDistance;
  15645. }
  15646. return {
  15647. refreshFogUniforms: refreshFogUniforms,
  15648. refreshMaterialUniforms: refreshMaterialUniforms
  15649. };
  15650. }
  15651. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15652. let buffers = {};
  15653. let updateList = {};
  15654. let allocatedBindingPoints = [];
  15655. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  15656. function bind( uniformsGroup, program ) {
  15657. const webglProgram = program.program;
  15658. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15659. }
  15660. function update( uniformsGroup, program ) {
  15661. let buffer = buffers[ uniformsGroup.id ];
  15662. if ( buffer === undefined ) {
  15663. prepareUniformsGroup( uniformsGroup );
  15664. buffer = createBuffer( uniformsGroup );
  15665. buffers[ uniformsGroup.id ] = buffer;
  15666. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15667. }
  15668. // ensure to update the binding points/block indices mapping for this program
  15669. const webglProgram = program.program;
  15670. state.updateUBOMapping( uniformsGroup, webglProgram );
  15671. // update UBO once per frame
  15672. const frame = info.render.frame;
  15673. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15674. updateBufferData( uniformsGroup );
  15675. updateList[ uniformsGroup.id ] = frame;
  15676. }
  15677. }
  15678. function createBuffer( uniformsGroup ) {
  15679. // the setup of an UBO is independent of a particular shader program but global
  15680. const bindingPointIndex = allocateBindingPointIndex();
  15681. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15682. const buffer = gl.createBuffer();
  15683. const size = uniformsGroup.__size;
  15684. const usage = uniformsGroup.usage;
  15685. gl.bindBuffer( 35345, buffer );
  15686. gl.bufferData( 35345, size, usage );
  15687. gl.bindBuffer( 35345, null );
  15688. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  15689. return buffer;
  15690. }
  15691. function allocateBindingPointIndex() {
  15692. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15693. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15694. allocatedBindingPoints.push( i );
  15695. return i;
  15696. }
  15697. }
  15698. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15699. return 0;
  15700. }
  15701. function updateBufferData( uniformsGroup ) {
  15702. const buffer = buffers[ uniformsGroup.id ];
  15703. const uniforms = uniformsGroup.uniforms;
  15704. const cache = uniformsGroup.__cache;
  15705. gl.bindBuffer( 35345, buffer );
  15706. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15707. const uniform = uniforms[ i ];
  15708. // partly update the buffer if necessary
  15709. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15710. const value = uniform.value;
  15711. const offset = uniform.__offset;
  15712. if ( typeof value === 'number' ) {
  15713. uniform.__data[ 0 ] = value;
  15714. gl.bufferSubData( 35345, offset, uniform.__data );
  15715. } else {
  15716. if ( uniform.value.isMatrix3 ) {
  15717. // manually converting 3x3 to 3x4
  15718. uniform.__data[ 0 ] = uniform.value.elements[ 0 ];
  15719. uniform.__data[ 1 ] = uniform.value.elements[ 1 ];
  15720. uniform.__data[ 2 ] = uniform.value.elements[ 2 ];
  15721. uniform.__data[ 3 ] = uniform.value.elements[ 0 ];
  15722. uniform.__data[ 4 ] = uniform.value.elements[ 3 ];
  15723. uniform.__data[ 5 ] = uniform.value.elements[ 4 ];
  15724. uniform.__data[ 6 ] = uniform.value.elements[ 5 ];
  15725. uniform.__data[ 7 ] = uniform.value.elements[ 0 ];
  15726. uniform.__data[ 8 ] = uniform.value.elements[ 6 ];
  15727. uniform.__data[ 9 ] = uniform.value.elements[ 7 ];
  15728. uniform.__data[ 10 ] = uniform.value.elements[ 8 ];
  15729. uniform.__data[ 11 ] = uniform.value.elements[ 0 ];
  15730. } else {
  15731. value.toArray( uniform.__data );
  15732. }
  15733. gl.bufferSubData( 35345, offset, uniform.__data );
  15734. }
  15735. }
  15736. }
  15737. gl.bindBuffer( 35345, null );
  15738. }
  15739. function hasUniformChanged( uniform, index, cache ) {
  15740. const value = uniform.value;
  15741. if ( cache[ index ] === undefined ) {
  15742. // cache entry does not exist so far
  15743. if ( typeof value === 'number' ) {
  15744. cache[ index ] = value;
  15745. } else {
  15746. cache[ index ] = value.clone();
  15747. }
  15748. return true;
  15749. } else {
  15750. // compare current value with cached entry
  15751. if ( typeof value === 'number' ) {
  15752. if ( cache[ index ] !== value ) {
  15753. cache[ index ] = value;
  15754. return true;
  15755. }
  15756. } else {
  15757. const cachedObject = cache[ index ];
  15758. if ( cachedObject.equals( value ) === false ) {
  15759. cachedObject.copy( value );
  15760. return true;
  15761. }
  15762. }
  15763. }
  15764. return false;
  15765. }
  15766. function prepareUniformsGroup( uniformsGroup ) {
  15767. // determine total buffer size according to the STD140 layout
  15768. // Hint: STD140 is the only supported layout in WebGL 2
  15769. const uniforms = uniformsGroup.uniforms;
  15770. let offset = 0; // global buffer offset in bytes
  15771. const chunkSize = 16; // size of a chunk in bytes
  15772. let chunkOffset = 0; // offset within a single chunk in bytes
  15773. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  15774. const uniform = uniforms[ i ];
  15775. const info = getUniformSize( uniform );
  15776. // the following two properties will be used for partial buffer updates
  15777. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  15778. uniform.__offset = offset;
  15779. //
  15780. if ( i > 0 ) {
  15781. chunkOffset = offset % chunkSize;
  15782. const remainingSizeInChunk = chunkSize - chunkOffset;
  15783. // check for chunk overflow
  15784. if ( chunkOffset !== 0 && ( remainingSizeInChunk - info.boundary ) < 0 ) {
  15785. // add padding and adjust offset
  15786. offset += ( chunkSize - chunkOffset );
  15787. uniform.__offset = offset;
  15788. }
  15789. }
  15790. offset += info.storage;
  15791. }
  15792. // ensure correct final padding
  15793. chunkOffset = offset % chunkSize;
  15794. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  15795. //
  15796. uniformsGroup.__size = offset;
  15797. uniformsGroup.__cache = {};
  15798. return this;
  15799. }
  15800. function getUniformSize( uniform ) {
  15801. const value = uniform.value;
  15802. const info = {
  15803. boundary: 0, // bytes
  15804. storage: 0 // bytes
  15805. };
  15806. // determine sizes according to STD140
  15807. if ( typeof value === 'number' ) {
  15808. // float/int
  15809. info.boundary = 4;
  15810. info.storage = 4;
  15811. } else if ( value.isVector2 ) {
  15812. // vec2
  15813. info.boundary = 8;
  15814. info.storage = 8;
  15815. } else if ( value.isVector3 || value.isColor ) {
  15816. // vec3
  15817. info.boundary = 16;
  15818. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  15819. } else if ( value.isVector4 ) {
  15820. // vec4
  15821. info.boundary = 16;
  15822. info.storage = 16;
  15823. } else if ( value.isMatrix3 ) {
  15824. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  15825. info.boundary = 48;
  15826. info.storage = 48;
  15827. } else if ( value.isMatrix4 ) {
  15828. // mat4
  15829. info.boundary = 64;
  15830. info.storage = 64;
  15831. } else if ( value.isTexture ) {
  15832. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  15833. } else {
  15834. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  15835. }
  15836. return info;
  15837. }
  15838. function onUniformsGroupsDispose( event ) {
  15839. const uniformsGroup = event.target;
  15840. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  15841. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  15842. allocatedBindingPoints.splice( index, 1 );
  15843. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  15844. delete buffers[ uniformsGroup.id ];
  15845. delete updateList[ uniformsGroup.id ];
  15846. }
  15847. function dispose() {
  15848. for ( const id in buffers ) {
  15849. gl.deleteBuffer( buffers[ id ] );
  15850. }
  15851. allocatedBindingPoints = [];
  15852. buffers = {};
  15853. updateList = {};
  15854. }
  15855. return {
  15856. bind: bind,
  15857. update: update,
  15858. dispose: dispose
  15859. };
  15860. }
  15861. function createCanvasElement() {
  15862. const canvas = createElementNS( 'canvas' );
  15863. canvas.style.display = 'block';
  15864. return canvas;
  15865. }
  15866. function WebGLRenderer( parameters = {} ) {
  15867. this.isWebGLRenderer = true;
  15868. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15869. _context = parameters.context !== undefined ? parameters.context : null,
  15870. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15871. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15872. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15873. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15874. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15875. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15876. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15877. let _alpha;
  15878. if ( _context !== null ) {
  15879. _alpha = _context.getContextAttributes().alpha;
  15880. } else {
  15881. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15882. }
  15883. let currentRenderList = null;
  15884. let currentRenderState = null;
  15885. // render() can be called from within a callback triggered by another render.
  15886. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15887. const renderListStack = [];
  15888. const renderStateStack = [];
  15889. // public properties
  15890. this.domElement = _canvas;
  15891. // Debug configuration container
  15892. this.debug = {
  15893. /**
  15894. * Enables error checking and reporting when shader programs are being compiled
  15895. * @type {boolean}
  15896. */
  15897. checkShaderErrors: true
  15898. };
  15899. // clearing
  15900. this.autoClear = true;
  15901. this.autoClearColor = true;
  15902. this.autoClearDepth = true;
  15903. this.autoClearStencil = true;
  15904. // scene graph
  15905. this.sortObjects = true;
  15906. // user-defined clipping
  15907. this.clippingPlanes = [];
  15908. this.localClippingEnabled = false;
  15909. // physically based shading
  15910. this.outputEncoding = LinearEncoding;
  15911. // physical lights
  15912. this.physicallyCorrectLights = false;
  15913. // tone mapping
  15914. this.toneMapping = NoToneMapping;
  15915. this.toneMappingExposure = 1.0;
  15916. //
  15917. Object.defineProperties( this, {
  15918. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  15919. gammaFactor: {
  15920. get: function () {
  15921. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  15922. return 2;
  15923. },
  15924. set: function () {
  15925. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  15926. }
  15927. }
  15928. } );
  15929. // internal properties
  15930. const _this = this;
  15931. let _isContextLost = false;
  15932. // internal state cache
  15933. let _currentActiveCubeFace = 0;
  15934. let _currentActiveMipmapLevel = 0;
  15935. let _currentRenderTarget = null;
  15936. let _currentMaterialId = - 1;
  15937. let _currentCamera = null;
  15938. const _currentViewport = new Vector4();
  15939. const _currentScissor = new Vector4();
  15940. let _currentScissorTest = null;
  15941. //
  15942. let _width = _canvas.width;
  15943. let _height = _canvas.height;
  15944. let _pixelRatio = 1;
  15945. let _opaqueSort = null;
  15946. let _transparentSort = null;
  15947. const _viewport = new Vector4( 0, 0, _width, _height );
  15948. const _scissor = new Vector4( 0, 0, _width, _height );
  15949. let _scissorTest = false;
  15950. // frustum
  15951. const _frustum = new Frustum();
  15952. // clipping
  15953. let _clippingEnabled = false;
  15954. let _localClippingEnabled = false;
  15955. // transmission
  15956. let _transmissionRenderTarget = null;
  15957. // camera matrices cache
  15958. const _projScreenMatrix = new Matrix4();
  15959. const _vector2 = new Vector2();
  15960. const _vector3 = new Vector3();
  15961. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15962. function getTargetPixelRatio() {
  15963. return _currentRenderTarget === null ? _pixelRatio : 1;
  15964. }
  15965. // initialize
  15966. let _gl = _context;
  15967. function getContext( contextNames, contextAttributes ) {
  15968. for ( let i = 0; i < contextNames.length; i ++ ) {
  15969. const contextName = contextNames[ i ];
  15970. const context = _canvas.getContext( contextName, contextAttributes );
  15971. if ( context !== null ) return context;
  15972. }
  15973. return null;
  15974. }
  15975. try {
  15976. const contextAttributes = {
  15977. alpha: true,
  15978. depth: _depth,
  15979. stencil: _stencil,
  15980. antialias: _antialias,
  15981. premultipliedAlpha: _premultipliedAlpha,
  15982. preserveDrawingBuffer: _preserveDrawingBuffer,
  15983. powerPreference: _powerPreference,
  15984. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15985. };
  15986. // OffscreenCanvas does not have setAttribute, see #22811
  15987. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  15988. // event listeners must be registered before WebGL context is created, see #12753
  15989. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15990. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15991. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  15992. if ( _gl === null ) {
  15993. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15994. if ( _this.isWebGL1Renderer === true ) {
  15995. contextNames.shift();
  15996. }
  15997. _gl = getContext( contextNames, contextAttributes );
  15998. if ( _gl === null ) {
  15999. if ( getContext( contextNames ) ) {
  16000. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16001. } else {
  16002. throw new Error( 'Error creating WebGL context.' );
  16003. }
  16004. }
  16005. }
  16006. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16007. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16008. _gl.getShaderPrecisionFormat = function () {
  16009. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16010. };
  16011. }
  16012. } catch ( error ) {
  16013. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16014. throw error;
  16015. }
  16016. let extensions, capabilities, state, info;
  16017. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16018. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16019. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16020. let utils, bindingStates, uniformsGroups;
  16021. function initGLContext() {
  16022. extensions = new WebGLExtensions( _gl );
  16023. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16024. extensions.init( capabilities );
  16025. utils = new WebGLUtils( _gl, extensions, capabilities );
  16026. state = new WebGLState( _gl, extensions, capabilities );
  16027. info = new WebGLInfo();
  16028. properties = new WebGLProperties();
  16029. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16030. cubemaps = new WebGLCubeMaps( _this );
  16031. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16032. attributes = new WebGLAttributes( _gl, capabilities );
  16033. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16034. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16035. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16036. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16037. clipping = new WebGLClipping( properties );
  16038. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16039. materials = new WebGLMaterials( _this, properties );
  16040. renderLists = new WebGLRenderLists();
  16041. renderStates = new WebGLRenderStates( extensions, capabilities );
  16042. background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
  16043. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16044. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16045. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16046. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16047. info.programs = programCache.programs;
  16048. _this.capabilities = capabilities;
  16049. _this.extensions = extensions;
  16050. _this.properties = properties;
  16051. _this.renderLists = renderLists;
  16052. _this.shadowMap = shadowMap;
  16053. _this.state = state;
  16054. _this.info = info;
  16055. }
  16056. initGLContext();
  16057. // xr
  16058. const xr = new WebXRManager( _this, _gl );
  16059. this.xr = xr;
  16060. // API
  16061. this.getContext = function () {
  16062. return _gl;
  16063. };
  16064. this.getContextAttributes = function () {
  16065. return _gl.getContextAttributes();
  16066. };
  16067. this.forceContextLoss = function () {
  16068. const extension = extensions.get( 'WEBGL_lose_context' );
  16069. if ( extension ) extension.loseContext();
  16070. };
  16071. this.forceContextRestore = function () {
  16072. const extension = extensions.get( 'WEBGL_lose_context' );
  16073. if ( extension ) extension.restoreContext();
  16074. };
  16075. this.getPixelRatio = function () {
  16076. return _pixelRatio;
  16077. };
  16078. this.setPixelRatio = function ( value ) {
  16079. if ( value === undefined ) return;
  16080. _pixelRatio = value;
  16081. this.setSize( _width, _height, false );
  16082. };
  16083. this.getSize = function ( target ) {
  16084. return target.set( _width, _height );
  16085. };
  16086. this.setSize = function ( width, height, updateStyle ) {
  16087. if ( xr.isPresenting ) {
  16088. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16089. return;
  16090. }
  16091. _width = width;
  16092. _height = height;
  16093. _canvas.width = Math.floor( width * _pixelRatio );
  16094. _canvas.height = Math.floor( height * _pixelRatio );
  16095. if ( updateStyle !== false ) {
  16096. _canvas.style.width = width + 'px';
  16097. _canvas.style.height = height + 'px';
  16098. }
  16099. this.setViewport( 0, 0, width, height );
  16100. };
  16101. this.getDrawingBufferSize = function ( target ) {
  16102. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16103. };
  16104. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16105. _width = width;
  16106. _height = height;
  16107. _pixelRatio = pixelRatio;
  16108. _canvas.width = Math.floor( width * pixelRatio );
  16109. _canvas.height = Math.floor( height * pixelRatio );
  16110. this.setViewport( 0, 0, width, height );
  16111. };
  16112. this.getCurrentViewport = function ( target ) {
  16113. return target.copy( _currentViewport );
  16114. };
  16115. this.getViewport = function ( target ) {
  16116. return target.copy( _viewport );
  16117. };
  16118. this.setViewport = function ( x, y, width, height ) {
  16119. if ( x.isVector4 ) {
  16120. _viewport.set( x.x, x.y, x.z, x.w );
  16121. } else {
  16122. _viewport.set( x, y, width, height );
  16123. }
  16124. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16125. };
  16126. this.getScissor = function ( target ) {
  16127. return target.copy( _scissor );
  16128. };
  16129. this.setScissor = function ( x, y, width, height ) {
  16130. if ( x.isVector4 ) {
  16131. _scissor.set( x.x, x.y, x.z, x.w );
  16132. } else {
  16133. _scissor.set( x, y, width, height );
  16134. }
  16135. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16136. };
  16137. this.getScissorTest = function () {
  16138. return _scissorTest;
  16139. };
  16140. this.setScissorTest = function ( boolean ) {
  16141. state.setScissorTest( _scissorTest = boolean );
  16142. };
  16143. this.setOpaqueSort = function ( method ) {
  16144. _opaqueSort = method;
  16145. };
  16146. this.setTransparentSort = function ( method ) {
  16147. _transparentSort = method;
  16148. };
  16149. // Clearing
  16150. this.getClearColor = function ( target ) {
  16151. return target.copy( background.getClearColor() );
  16152. };
  16153. this.setClearColor = function () {
  16154. background.setClearColor.apply( background, arguments );
  16155. };
  16156. this.getClearAlpha = function () {
  16157. return background.getClearAlpha();
  16158. };
  16159. this.setClearAlpha = function () {
  16160. background.setClearAlpha.apply( background, arguments );
  16161. };
  16162. this.clear = function ( color = true, depth = true, stencil = true ) {
  16163. let bits = 0;
  16164. if ( color ) bits |= 16384;
  16165. if ( depth ) bits |= 256;
  16166. if ( stencil ) bits |= 1024;
  16167. _gl.clear( bits );
  16168. };
  16169. this.clearColor = function () {
  16170. this.clear( true, false, false );
  16171. };
  16172. this.clearDepth = function () {
  16173. this.clear( false, true, false );
  16174. };
  16175. this.clearStencil = function () {
  16176. this.clear( false, false, true );
  16177. };
  16178. //
  16179. this.dispose = function () {
  16180. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16181. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16182. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16183. renderLists.dispose();
  16184. renderStates.dispose();
  16185. properties.dispose();
  16186. cubemaps.dispose();
  16187. cubeuvmaps.dispose();
  16188. objects.dispose();
  16189. bindingStates.dispose();
  16190. uniformsGroups.dispose();
  16191. programCache.dispose();
  16192. xr.dispose();
  16193. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16194. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16195. if ( _transmissionRenderTarget ) {
  16196. _transmissionRenderTarget.dispose();
  16197. _transmissionRenderTarget = null;
  16198. }
  16199. animation.stop();
  16200. };
  16201. // Events
  16202. function onContextLost( event ) {
  16203. event.preventDefault();
  16204. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16205. _isContextLost = true;
  16206. }
  16207. function onContextRestore( /* event */ ) {
  16208. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16209. _isContextLost = false;
  16210. const infoAutoReset = info.autoReset;
  16211. const shadowMapEnabled = shadowMap.enabled;
  16212. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16213. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16214. const shadowMapType = shadowMap.type;
  16215. initGLContext();
  16216. info.autoReset = infoAutoReset;
  16217. shadowMap.enabled = shadowMapEnabled;
  16218. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16219. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16220. shadowMap.type = shadowMapType;
  16221. }
  16222. function onContextCreationError( event ) {
  16223. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16224. }
  16225. function onMaterialDispose( event ) {
  16226. const material = event.target;
  16227. material.removeEventListener( 'dispose', onMaterialDispose );
  16228. deallocateMaterial( material );
  16229. }
  16230. // Buffer deallocation
  16231. function deallocateMaterial( material ) {
  16232. releaseMaterialProgramReferences( material );
  16233. properties.remove( material );
  16234. }
  16235. function releaseMaterialProgramReferences( material ) {
  16236. const programs = properties.get( material ).programs;
  16237. if ( programs !== undefined ) {
  16238. programs.forEach( function ( program ) {
  16239. programCache.releaseProgram( program );
  16240. } );
  16241. if ( material.isShaderMaterial ) {
  16242. programCache.releaseShaderCache( material );
  16243. }
  16244. }
  16245. }
  16246. // Buffer rendering
  16247. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16248. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16249. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16250. const program = setProgram( camera, scene, geometry, material, object );
  16251. state.setMaterial( material, frontFaceCW );
  16252. //
  16253. let index = geometry.index;
  16254. const position = geometry.attributes.position;
  16255. //
  16256. if ( index === null ) {
  16257. if ( position === undefined || position.count === 0 ) return;
  16258. } else if ( index.count === 0 ) {
  16259. return;
  16260. }
  16261. //
  16262. let rangeFactor = 1;
  16263. if ( material.wireframe === true ) {
  16264. index = geometries.getWireframeAttribute( geometry );
  16265. rangeFactor = 2;
  16266. }
  16267. bindingStates.setup( object, material, program, geometry, index );
  16268. let attribute;
  16269. let renderer = bufferRenderer;
  16270. if ( index !== null ) {
  16271. attribute = attributes.get( index );
  16272. renderer = indexedBufferRenderer;
  16273. renderer.setIndex( attribute );
  16274. }
  16275. //
  16276. const dataCount = ( index !== null ) ? index.count : position.count;
  16277. const rangeStart = geometry.drawRange.start * rangeFactor;
  16278. const rangeCount = geometry.drawRange.count * rangeFactor;
  16279. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16280. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16281. const drawStart = Math.max( rangeStart, groupStart );
  16282. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16283. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16284. if ( drawCount === 0 ) return;
  16285. //
  16286. if ( object.isMesh ) {
  16287. if ( material.wireframe === true ) {
  16288. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16289. renderer.setMode( 1 );
  16290. } else {
  16291. renderer.setMode( 4 );
  16292. }
  16293. } else if ( object.isLine ) {
  16294. let lineWidth = material.linewidth;
  16295. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16296. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16297. if ( object.isLineSegments ) {
  16298. renderer.setMode( 1 );
  16299. } else if ( object.isLineLoop ) {
  16300. renderer.setMode( 2 );
  16301. } else {
  16302. renderer.setMode( 3 );
  16303. }
  16304. } else if ( object.isPoints ) {
  16305. renderer.setMode( 0 );
  16306. } else if ( object.isSprite ) {
  16307. renderer.setMode( 4 );
  16308. }
  16309. if ( object.isInstancedMesh ) {
  16310. renderer.renderInstances( drawStart, drawCount, object.count );
  16311. } else if ( geometry.isInstancedBufferGeometry ) {
  16312. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  16313. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16314. } else {
  16315. renderer.render( drawStart, drawCount );
  16316. }
  16317. };
  16318. // Compile
  16319. this.compile = function ( scene, camera ) {
  16320. function prepare( material, scene, object ) {
  16321. if ( material.transparent === true && material.side === DoubleSide ) {
  16322. material.side = BackSide;
  16323. material.needsUpdate = true;
  16324. getProgram( material, scene, object );
  16325. material.side = FrontSide;
  16326. material.needsUpdate = true;
  16327. getProgram( material, scene, object );
  16328. material.side = DoubleSide;
  16329. } else {
  16330. getProgram( material, scene, object );
  16331. }
  16332. }
  16333. currentRenderState = renderStates.get( scene );
  16334. currentRenderState.init();
  16335. renderStateStack.push( currentRenderState );
  16336. scene.traverseVisible( function ( object ) {
  16337. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16338. currentRenderState.pushLight( object );
  16339. if ( object.castShadow ) {
  16340. currentRenderState.pushShadow( object );
  16341. }
  16342. }
  16343. } );
  16344. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16345. scene.traverse( function ( object ) {
  16346. const material = object.material;
  16347. if ( material ) {
  16348. if ( Array.isArray( material ) ) {
  16349. for ( let i = 0; i < material.length; i ++ ) {
  16350. const material2 = material[ i ];
  16351. prepare( material2, scene, object );
  16352. }
  16353. } else {
  16354. prepare( material, scene, object );
  16355. }
  16356. }
  16357. } );
  16358. renderStateStack.pop();
  16359. currentRenderState = null;
  16360. };
  16361. // Animation Loop
  16362. let onAnimationFrameCallback = null;
  16363. function onAnimationFrame( time ) {
  16364. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16365. }
  16366. function onXRSessionStart() {
  16367. animation.stop();
  16368. }
  16369. function onXRSessionEnd() {
  16370. animation.start();
  16371. }
  16372. const animation = new WebGLAnimation();
  16373. animation.setAnimationLoop( onAnimationFrame );
  16374. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16375. this.setAnimationLoop = function ( callback ) {
  16376. onAnimationFrameCallback = callback;
  16377. xr.setAnimationLoop( callback );
  16378. ( callback === null ) ? animation.stop() : animation.start();
  16379. };
  16380. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16381. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16382. // Rendering
  16383. this.render = function ( scene, camera ) {
  16384. if ( camera !== undefined && camera.isCamera !== true ) {
  16385. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16386. return;
  16387. }
  16388. if ( _isContextLost === true ) return;
  16389. // update scene graph
  16390. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16391. // update camera matrices and frustum
  16392. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16393. if ( xr.enabled === true && xr.isPresenting === true ) {
  16394. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16395. camera = xr.getCamera(); // use XR camera for rendering
  16396. }
  16397. //
  16398. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16399. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16400. currentRenderState.init();
  16401. renderStateStack.push( currentRenderState );
  16402. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16403. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16404. _localClippingEnabled = this.localClippingEnabled;
  16405. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16406. currentRenderList = renderLists.get( scene, renderListStack.length );
  16407. currentRenderList.init();
  16408. renderListStack.push( currentRenderList );
  16409. projectObject( scene, camera, 0, _this.sortObjects );
  16410. currentRenderList.finish();
  16411. if ( _this.sortObjects === true ) {
  16412. currentRenderList.sort( _opaqueSort, _transparentSort );
  16413. }
  16414. //
  16415. if ( _clippingEnabled === true ) clipping.beginShadows();
  16416. const shadowsArray = currentRenderState.state.shadowsArray;
  16417. shadowMap.render( shadowsArray, scene, camera );
  16418. if ( _clippingEnabled === true ) clipping.endShadows();
  16419. //
  16420. if ( this.info.autoReset === true ) this.info.reset();
  16421. //
  16422. background.render( currentRenderList, scene );
  16423. // render scene
  16424. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16425. if ( camera.isArrayCamera ) {
  16426. const cameras = camera.cameras;
  16427. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16428. const camera2 = cameras[ i ];
  16429. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16430. }
  16431. } else {
  16432. renderScene( currentRenderList, scene, camera );
  16433. }
  16434. //
  16435. if ( _currentRenderTarget !== null ) {
  16436. // resolve multisample renderbuffers to a single-sample texture if necessary
  16437. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16438. // Generate mipmap if we're using any kind of mipmap filtering
  16439. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16440. }
  16441. //
  16442. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16443. // _gl.finish();
  16444. bindingStates.resetDefaultState();
  16445. _currentMaterialId = - 1;
  16446. _currentCamera = null;
  16447. renderStateStack.pop();
  16448. if ( renderStateStack.length > 0 ) {
  16449. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16450. } else {
  16451. currentRenderState = null;
  16452. }
  16453. renderListStack.pop();
  16454. if ( renderListStack.length > 0 ) {
  16455. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16456. } else {
  16457. currentRenderList = null;
  16458. }
  16459. };
  16460. function projectObject( object, camera, groupOrder, sortObjects ) {
  16461. if ( object.visible === false ) return;
  16462. const visible = object.layers.test( camera.layers );
  16463. if ( visible ) {
  16464. if ( object.isGroup ) {
  16465. groupOrder = object.renderOrder;
  16466. } else if ( object.isLOD ) {
  16467. if ( object.autoUpdate === true ) object.update( camera );
  16468. } else if ( object.isLight ) {
  16469. currentRenderState.pushLight( object );
  16470. if ( object.castShadow ) {
  16471. currentRenderState.pushShadow( object );
  16472. }
  16473. } else if ( object.isSprite ) {
  16474. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16475. if ( sortObjects ) {
  16476. _vector3.setFromMatrixPosition( object.matrixWorld )
  16477. .applyMatrix4( _projScreenMatrix );
  16478. }
  16479. const geometry = objects.update( object );
  16480. const material = object.material;
  16481. if ( material.visible ) {
  16482. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16483. }
  16484. }
  16485. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16486. if ( object.isSkinnedMesh ) {
  16487. // update skeleton only once in a frame
  16488. if ( object.skeleton.frame !== info.render.frame ) {
  16489. object.skeleton.update();
  16490. object.skeleton.frame = info.render.frame;
  16491. }
  16492. }
  16493. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16494. if ( sortObjects ) {
  16495. _vector3.setFromMatrixPosition( object.matrixWorld )
  16496. .applyMatrix4( _projScreenMatrix );
  16497. }
  16498. const geometry = objects.update( object );
  16499. const material = object.material;
  16500. if ( Array.isArray( material ) ) {
  16501. const groups = geometry.groups;
  16502. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16503. const group = groups[ i ];
  16504. const groupMaterial = material[ group.materialIndex ];
  16505. if ( groupMaterial && groupMaterial.visible ) {
  16506. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16507. }
  16508. }
  16509. } else if ( material.visible ) {
  16510. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16511. }
  16512. }
  16513. }
  16514. }
  16515. const children = object.children;
  16516. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16517. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16518. }
  16519. }
  16520. function renderScene( currentRenderList, scene, camera, viewport ) {
  16521. const opaqueObjects = currentRenderList.opaque;
  16522. const transmissiveObjects = currentRenderList.transmissive;
  16523. const transparentObjects = currentRenderList.transparent;
  16524. currentRenderState.setupLightsView( camera );
  16525. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16526. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16527. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16528. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16529. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16530. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16531. state.buffers.depth.setTest( true );
  16532. state.buffers.depth.setMask( true );
  16533. state.buffers.color.setMask( true );
  16534. state.setPolygonOffset( false );
  16535. }
  16536. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16537. const isWebGL2 = capabilities.isWebGL2;
  16538. if ( _transmissionRenderTarget === null ) {
  16539. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16540. generateMipmaps: true,
  16541. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16542. minFilter: LinearMipmapLinearFilter,
  16543. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16544. } );
  16545. }
  16546. _this.getDrawingBufferSize( _vector2 );
  16547. if ( isWebGL2 ) {
  16548. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16549. } else {
  16550. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16551. }
  16552. //
  16553. const currentRenderTarget = _this.getRenderTarget();
  16554. _this.setRenderTarget( _transmissionRenderTarget );
  16555. _this.clear();
  16556. // Turn off the features which can affect the frag color for opaque objects pass.
  16557. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16558. const currentToneMapping = _this.toneMapping;
  16559. _this.toneMapping = NoToneMapping;
  16560. renderObjects( opaqueObjects, scene, camera );
  16561. _this.toneMapping = currentToneMapping;
  16562. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16563. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16564. _this.setRenderTarget( currentRenderTarget );
  16565. }
  16566. function renderObjects( renderList, scene, camera ) {
  16567. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16568. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16569. const renderItem = renderList[ i ];
  16570. const object = renderItem.object;
  16571. const geometry = renderItem.geometry;
  16572. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16573. const group = renderItem.group;
  16574. if ( object.layers.test( camera.layers ) ) {
  16575. renderObject( object, scene, camera, geometry, material, group );
  16576. }
  16577. }
  16578. }
  16579. function renderObject( object, scene, camera, geometry, material, group ) {
  16580. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16581. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16582. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16583. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16584. if ( material.transparent === true && material.side === DoubleSide ) {
  16585. material.side = BackSide;
  16586. material.needsUpdate = true;
  16587. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16588. material.side = FrontSide;
  16589. material.needsUpdate = true;
  16590. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16591. material.side = DoubleSide;
  16592. } else {
  16593. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16594. }
  16595. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16596. }
  16597. function getProgram( material, scene, object ) {
  16598. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16599. const materialProperties = properties.get( material );
  16600. const lights = currentRenderState.state.lights;
  16601. const shadowsArray = currentRenderState.state.shadowsArray;
  16602. const lightsStateVersion = lights.state.version;
  16603. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16604. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16605. let programs = materialProperties.programs;
  16606. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16607. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16608. materialProperties.fog = scene.fog;
  16609. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16610. if ( programs === undefined ) {
  16611. // new material
  16612. material.addEventListener( 'dispose', onMaterialDispose );
  16613. programs = new Map();
  16614. materialProperties.programs = programs;
  16615. }
  16616. let program = programs.get( programCacheKey );
  16617. if ( program !== undefined ) {
  16618. // early out if program and light state is identical
  16619. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16620. updateCommonMaterialProperties( material, parameters );
  16621. return program;
  16622. }
  16623. } else {
  16624. parameters.uniforms = programCache.getUniforms( material );
  16625. material.onBuild( object, parameters, _this );
  16626. material.onBeforeCompile( parameters, _this );
  16627. program = programCache.acquireProgram( parameters, programCacheKey );
  16628. programs.set( programCacheKey, program );
  16629. materialProperties.uniforms = parameters.uniforms;
  16630. }
  16631. const uniforms = materialProperties.uniforms;
  16632. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16633. uniforms.clippingPlanes = clipping.uniform;
  16634. }
  16635. updateCommonMaterialProperties( material, parameters );
  16636. // store the light setup it was created for
  16637. materialProperties.needsLights = materialNeedsLights( material );
  16638. materialProperties.lightsStateVersion = lightsStateVersion;
  16639. if ( materialProperties.needsLights ) {
  16640. // wire up the material to this renderer's lighting state
  16641. uniforms.ambientLightColor.value = lights.state.ambient;
  16642. uniforms.lightProbe.value = lights.state.probe;
  16643. uniforms.directionalLights.value = lights.state.directional;
  16644. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16645. uniforms.spotLights.value = lights.state.spot;
  16646. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16647. uniforms.rectAreaLights.value = lights.state.rectArea;
  16648. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16649. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16650. uniforms.pointLights.value = lights.state.point;
  16651. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16652. uniforms.hemisphereLights.value = lights.state.hemi;
  16653. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16654. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16655. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16656. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16657. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16658. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16659. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16660. // TODO (abelnation): add area lights shadow info to uniforms
  16661. }
  16662. const progUniforms = program.getUniforms();
  16663. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16664. materialProperties.currentProgram = program;
  16665. materialProperties.uniformsList = uniformsList;
  16666. return program;
  16667. }
  16668. function updateCommonMaterialProperties( material, parameters ) {
  16669. const materialProperties = properties.get( material );
  16670. materialProperties.outputEncoding = parameters.outputEncoding;
  16671. materialProperties.instancing = parameters.instancing;
  16672. materialProperties.skinning = parameters.skinning;
  16673. materialProperties.morphTargets = parameters.morphTargets;
  16674. materialProperties.morphNormals = parameters.morphNormals;
  16675. materialProperties.morphColors = parameters.morphColors;
  16676. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16677. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16678. materialProperties.numIntersection = parameters.numClipIntersection;
  16679. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16680. materialProperties.vertexTangents = parameters.vertexTangents;
  16681. materialProperties.toneMapping = parameters.toneMapping;
  16682. }
  16683. function setProgram( camera, scene, geometry, material, object ) {
  16684. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16685. textures.resetTextureUnits();
  16686. const fog = scene.fog;
  16687. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16688. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16689. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16690. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16691. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16692. const morphTargets = !! geometry.morphAttributes.position;
  16693. const morphNormals = !! geometry.morphAttributes.normal;
  16694. const morphColors = !! geometry.morphAttributes.color;
  16695. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16696. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16697. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16698. const materialProperties = properties.get( material );
  16699. const lights = currentRenderState.state.lights;
  16700. if ( _clippingEnabled === true ) {
  16701. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16702. const useCache =
  16703. camera === _currentCamera &&
  16704. material.id === _currentMaterialId;
  16705. // we might want to call this function with some ClippingGroup
  16706. // object instead of the material, once it becomes feasible
  16707. // (#8465, #8379)
  16708. clipping.setState( material, camera, useCache );
  16709. }
  16710. }
  16711. //
  16712. let needsProgramChange = false;
  16713. if ( material.version === materialProperties.__version ) {
  16714. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16715. needsProgramChange = true;
  16716. } else if ( materialProperties.outputEncoding !== encoding ) {
  16717. needsProgramChange = true;
  16718. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16719. needsProgramChange = true;
  16720. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16721. needsProgramChange = true;
  16722. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16723. needsProgramChange = true;
  16724. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16725. needsProgramChange = true;
  16726. } else if ( materialProperties.envMap !== envMap ) {
  16727. needsProgramChange = true;
  16728. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16729. needsProgramChange = true;
  16730. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16731. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16732. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16733. needsProgramChange = true;
  16734. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16735. needsProgramChange = true;
  16736. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16737. needsProgramChange = true;
  16738. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16739. needsProgramChange = true;
  16740. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16741. needsProgramChange = true;
  16742. } else if ( materialProperties.morphColors !== morphColors ) {
  16743. needsProgramChange = true;
  16744. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16745. needsProgramChange = true;
  16746. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16747. needsProgramChange = true;
  16748. }
  16749. } else {
  16750. needsProgramChange = true;
  16751. materialProperties.__version = material.version;
  16752. }
  16753. //
  16754. let program = materialProperties.currentProgram;
  16755. if ( needsProgramChange === true ) {
  16756. program = getProgram( material, scene, object );
  16757. }
  16758. let refreshProgram = false;
  16759. let refreshMaterial = false;
  16760. let refreshLights = false;
  16761. const p_uniforms = program.getUniforms(),
  16762. m_uniforms = materialProperties.uniforms;
  16763. if ( state.useProgram( program.program ) ) {
  16764. refreshProgram = true;
  16765. refreshMaterial = true;
  16766. refreshLights = true;
  16767. }
  16768. if ( material.id !== _currentMaterialId ) {
  16769. _currentMaterialId = material.id;
  16770. refreshMaterial = true;
  16771. }
  16772. if ( refreshProgram || _currentCamera !== camera ) {
  16773. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16774. if ( capabilities.logarithmicDepthBuffer ) {
  16775. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16776. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16777. }
  16778. if ( _currentCamera !== camera ) {
  16779. _currentCamera = camera;
  16780. // lighting uniforms depend on the camera so enforce an update
  16781. // now, in case this material supports lights - or later, when
  16782. // the next material that does gets activated:
  16783. refreshMaterial = true; // set to true on material change
  16784. refreshLights = true; // remains set until update done
  16785. }
  16786. // load material specific uniforms
  16787. // (shader material also gets them for the sake of genericity)
  16788. if ( material.isShaderMaterial ||
  16789. material.isMeshPhongMaterial ||
  16790. material.isMeshToonMaterial ||
  16791. material.isMeshStandardMaterial ||
  16792. material.envMap ) {
  16793. const uCamPos = p_uniforms.map.cameraPosition;
  16794. if ( uCamPos !== undefined ) {
  16795. uCamPos.setValue( _gl,
  16796. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16797. }
  16798. }
  16799. if ( material.isMeshPhongMaterial ||
  16800. material.isMeshToonMaterial ||
  16801. material.isMeshLambertMaterial ||
  16802. material.isMeshBasicMaterial ||
  16803. material.isMeshStandardMaterial ||
  16804. material.isShaderMaterial ) {
  16805. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  16806. }
  16807. if ( material.isMeshPhongMaterial ||
  16808. material.isMeshToonMaterial ||
  16809. material.isMeshLambertMaterial ||
  16810. material.isMeshBasicMaterial ||
  16811. material.isMeshStandardMaterial ||
  16812. material.isShaderMaterial ||
  16813. material.isShadowMaterial ||
  16814. object.isSkinnedMesh ) {
  16815. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16816. }
  16817. }
  16818. // skinning and morph target uniforms must be set even if material didn't change
  16819. // auto-setting of texture unit for bone and morph texture must go before other textures
  16820. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16821. if ( object.isSkinnedMesh ) {
  16822. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16823. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16824. const skeleton = object.skeleton;
  16825. if ( skeleton ) {
  16826. if ( capabilities.floatVertexTextures ) {
  16827. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  16828. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  16829. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  16830. } else {
  16831. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  16832. }
  16833. }
  16834. }
  16835. const morphAttributes = geometry.morphAttributes;
  16836. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  16837. morphtargets.update( object, geometry, material, program );
  16838. }
  16839. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  16840. materialProperties.receiveShadow = object.receiveShadow;
  16841. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  16842. }
  16843. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  16844. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  16845. m_uniforms.envMap.value = envMap;
  16846. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16847. }
  16848. if ( refreshMaterial ) {
  16849. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  16850. if ( materialProperties.needsLights ) {
  16851. // the current material requires lighting info
  16852. // note: all lighting uniforms are always set correctly
  16853. // they simply reference the renderer's state for their
  16854. // values
  16855. //
  16856. // use the current material's .needsUpdate flags to set
  16857. // the GL state when required
  16858. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16859. }
  16860. // refresh uniforms common to several materials
  16861. if ( fog && material.fog === true ) {
  16862. materials.refreshFogUniforms( m_uniforms, fog );
  16863. }
  16864. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  16865. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16866. }
  16867. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  16868. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16869. material.uniformsNeedUpdate = false;
  16870. }
  16871. if ( material.isSpriteMaterial ) {
  16872. p_uniforms.setValue( _gl, 'center', object.center );
  16873. }
  16874. // common matrices
  16875. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  16876. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  16877. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16878. // UBOs
  16879. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  16880. const groups = material.uniformsGroups;
  16881. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16882. if ( capabilities.isWebGL2 ) {
  16883. const group = groups[ i ];
  16884. uniformsGroups.update( group, program );
  16885. uniformsGroups.bind( group, program );
  16886. } else {
  16887. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  16888. }
  16889. }
  16890. }
  16891. return program;
  16892. }
  16893. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16894. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  16895. uniforms.ambientLightColor.needsUpdate = value;
  16896. uniforms.lightProbe.needsUpdate = value;
  16897. uniforms.directionalLights.needsUpdate = value;
  16898. uniforms.directionalLightShadows.needsUpdate = value;
  16899. uniforms.pointLights.needsUpdate = value;
  16900. uniforms.pointLightShadows.needsUpdate = value;
  16901. uniforms.spotLights.needsUpdate = value;
  16902. uniforms.spotLightShadows.needsUpdate = value;
  16903. uniforms.rectAreaLights.needsUpdate = value;
  16904. uniforms.hemisphereLights.needsUpdate = value;
  16905. }
  16906. function materialNeedsLights( material ) {
  16907. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  16908. material.isMeshStandardMaterial || material.isShadowMaterial ||
  16909. ( material.isShaderMaterial && material.lights === true );
  16910. }
  16911. this.getActiveCubeFace = function () {
  16912. return _currentActiveCubeFace;
  16913. };
  16914. this.getActiveMipmapLevel = function () {
  16915. return _currentActiveMipmapLevel;
  16916. };
  16917. this.getRenderTarget = function () {
  16918. return _currentRenderTarget;
  16919. };
  16920. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  16921. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  16922. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  16923. const renderTargetProperties = properties.get( renderTarget );
  16924. renderTargetProperties.__hasExternalTextures = true;
  16925. if ( renderTargetProperties.__hasExternalTextures ) {
  16926. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16927. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  16928. // The multisample_render_to_texture extension doesn't work properly if there
  16929. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16930. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  16931. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  16932. renderTargetProperties.__useRenderToTexture = false;
  16933. }
  16934. }
  16935. }
  16936. };
  16937. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  16938. const renderTargetProperties = properties.get( renderTarget );
  16939. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16940. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16941. };
  16942. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16943. _currentRenderTarget = renderTarget;
  16944. _currentActiveCubeFace = activeCubeFace;
  16945. _currentActiveMipmapLevel = activeMipmapLevel;
  16946. let useDefaultFramebuffer = true;
  16947. if ( renderTarget ) {
  16948. const renderTargetProperties = properties.get( renderTarget );
  16949. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  16950. // We need to make sure to rebind the framebuffer.
  16951. state.bindFramebuffer( 36160, null );
  16952. useDefaultFramebuffer = false;
  16953. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  16954. textures.setupRenderTarget( renderTarget );
  16955. } else if ( renderTargetProperties.__hasExternalTextures ) {
  16956. // Color and depth texture must be rebound in order for the swapchain to update.
  16957. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  16958. }
  16959. }
  16960. let framebuffer = null;
  16961. let isCube = false;
  16962. let isRenderTarget3D = false;
  16963. if ( renderTarget ) {
  16964. const texture = renderTarget.texture;
  16965. if ( texture.isData3DTexture || texture.isDataArrayTexture ) {
  16966. isRenderTarget3D = true;
  16967. }
  16968. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16969. if ( renderTarget.isWebGLCubeRenderTarget ) {
  16970. framebuffer = __webglFramebuffer[ activeCubeFace ];
  16971. isCube = true;
  16972. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  16973. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  16974. } else {
  16975. framebuffer = __webglFramebuffer;
  16976. }
  16977. _currentViewport.copy( renderTarget.viewport );
  16978. _currentScissor.copy( renderTarget.scissor );
  16979. _currentScissorTest = renderTarget.scissorTest;
  16980. } else {
  16981. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16982. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16983. _currentScissorTest = _scissorTest;
  16984. }
  16985. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16986. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  16987. state.drawBuffers( renderTarget, framebuffer );
  16988. }
  16989. state.viewport( _currentViewport );
  16990. state.scissor( _currentScissor );
  16991. state.setScissorTest( _currentScissorTest );
  16992. if ( isCube ) {
  16993. const textureProperties = properties.get( renderTarget.texture );
  16994. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16995. } else if ( isRenderTarget3D ) {
  16996. const textureProperties = properties.get( renderTarget.texture );
  16997. const layer = activeCubeFace || 0;
  16998. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16999. }
  17000. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17001. };
  17002. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17003. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17004. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17005. return;
  17006. }
  17007. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17008. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17009. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17010. }
  17011. if ( framebuffer ) {
  17012. state.bindFramebuffer( 36160, framebuffer );
  17013. try {
  17014. const texture = renderTarget.texture;
  17015. const textureFormat = texture.format;
  17016. const textureType = texture.type;
  17017. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17018. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17019. return;
  17020. }
  17021. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17022. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17023. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17024. ! halfFloatSupportedByExt ) {
  17025. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17026. return;
  17027. }
  17028. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17029. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17030. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17031. }
  17032. } finally {
  17033. // restore framebuffer of current render target if necessary
  17034. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17035. state.bindFramebuffer( 36160, framebuffer );
  17036. }
  17037. }
  17038. };
  17039. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17040. const levelScale = Math.pow( 2, - level );
  17041. const width = Math.floor( texture.image.width * levelScale );
  17042. const height = Math.floor( texture.image.height * levelScale );
  17043. textures.setTexture2D( texture, 0 );
  17044. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17045. state.unbindTexture();
  17046. };
  17047. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17048. const width = srcTexture.image.width;
  17049. const height = srcTexture.image.height;
  17050. const glFormat = utils.convert( dstTexture.format );
  17051. const glType = utils.convert( dstTexture.type );
  17052. textures.setTexture2D( dstTexture, 0 );
  17053. // As another texture upload may have changed pixelStorei
  17054. // parameters, make sure they are correct for the dstTexture
  17055. _gl.pixelStorei( 37440, dstTexture.flipY );
  17056. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17057. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17058. if ( srcTexture.isDataTexture ) {
  17059. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17060. } else {
  17061. if ( srcTexture.isCompressedTexture ) {
  17062. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17063. } else {
  17064. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17065. }
  17066. }
  17067. // Generate mipmaps only when copying level 0
  17068. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17069. state.unbindTexture();
  17070. };
  17071. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17072. if ( _this.isWebGL1Renderer ) {
  17073. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17074. return;
  17075. }
  17076. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17077. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17078. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17079. const glFormat = utils.convert( dstTexture.format );
  17080. const glType = utils.convert( dstTexture.type );
  17081. let glTarget;
  17082. if ( dstTexture.isData3DTexture ) {
  17083. textures.setTexture3D( dstTexture, 0 );
  17084. glTarget = 32879;
  17085. } else if ( dstTexture.isDataArrayTexture ) {
  17086. textures.setTexture2DArray( dstTexture, 0 );
  17087. glTarget = 35866;
  17088. } else {
  17089. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17090. return;
  17091. }
  17092. _gl.pixelStorei( 37440, dstTexture.flipY );
  17093. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17094. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17095. const unpackRowLen = _gl.getParameter( 3314 );
  17096. const unpackImageHeight = _gl.getParameter( 32878 );
  17097. const unpackSkipPixels = _gl.getParameter( 3316 );
  17098. const unpackSkipRows = _gl.getParameter( 3315 );
  17099. const unpackSkipImages = _gl.getParameter( 32877 );
  17100. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17101. _gl.pixelStorei( 3314, image.width );
  17102. _gl.pixelStorei( 32878, image.height );
  17103. _gl.pixelStorei( 3316, sourceBox.min.x );
  17104. _gl.pixelStorei( 3315, sourceBox.min.y );
  17105. _gl.pixelStorei( 32877, sourceBox.min.z );
  17106. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17107. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17108. } else {
  17109. if ( srcTexture.isCompressedTexture ) {
  17110. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17111. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17112. } else {
  17113. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17114. }
  17115. }
  17116. _gl.pixelStorei( 3314, unpackRowLen );
  17117. _gl.pixelStorei( 32878, unpackImageHeight );
  17118. _gl.pixelStorei( 3316, unpackSkipPixels );
  17119. _gl.pixelStorei( 3315, unpackSkipRows );
  17120. _gl.pixelStorei( 32877, unpackSkipImages );
  17121. // Generate mipmaps only when copying level 0
  17122. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17123. state.unbindTexture();
  17124. };
  17125. this.initTexture = function ( texture ) {
  17126. if ( texture.isCubeTexture ) {
  17127. textures.setTextureCube( texture, 0 );
  17128. } else if ( texture.isData3DTexture ) {
  17129. textures.setTexture3D( texture, 0 );
  17130. } else if ( texture.isDataArrayTexture ) {
  17131. textures.setTexture2DArray( texture, 0 );
  17132. } else {
  17133. textures.setTexture2D( texture, 0 );
  17134. }
  17135. state.unbindTexture();
  17136. };
  17137. this.resetState = function () {
  17138. _currentActiveCubeFace = 0;
  17139. _currentActiveMipmapLevel = 0;
  17140. _currentRenderTarget = null;
  17141. state.reset();
  17142. bindingStates.reset();
  17143. };
  17144. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17145. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17146. }
  17147. }
  17148. class WebGL1Renderer extends WebGLRenderer {}
  17149. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17150. class FogExp2 {
  17151. constructor( color, density = 0.00025 ) {
  17152. this.isFogExp2 = true;
  17153. this.name = '';
  17154. this.color = new Color( color );
  17155. this.density = density;
  17156. }
  17157. clone() {
  17158. return new FogExp2( this.color, this.density );
  17159. }
  17160. toJSON( /* meta */ ) {
  17161. return {
  17162. type: 'FogExp2',
  17163. color: this.color.getHex(),
  17164. density: this.density
  17165. };
  17166. }
  17167. }
  17168. class Fog {
  17169. constructor( color, near = 1, far = 1000 ) {
  17170. this.isFog = true;
  17171. this.name = '';
  17172. this.color = new Color( color );
  17173. this.near = near;
  17174. this.far = far;
  17175. }
  17176. clone() {
  17177. return new Fog( this.color, this.near, this.far );
  17178. }
  17179. toJSON( /* meta */ ) {
  17180. return {
  17181. type: 'Fog',
  17182. color: this.color.getHex(),
  17183. near: this.near,
  17184. far: this.far
  17185. };
  17186. }
  17187. }
  17188. class Scene extends Object3D {
  17189. constructor() {
  17190. super();
  17191. this.isScene = true;
  17192. this.type = 'Scene';
  17193. this.background = null;
  17194. this.environment = null;
  17195. this.fog = null;
  17196. this.overrideMaterial = null;
  17197. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17198. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17199. }
  17200. }
  17201. copy( source, recursive ) {
  17202. super.copy( source, recursive );
  17203. if ( source.background !== null ) this.background = source.background.clone();
  17204. if ( source.environment !== null ) this.environment = source.environment.clone();
  17205. if ( source.fog !== null ) this.fog = source.fog.clone();
  17206. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17207. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17208. return this;
  17209. }
  17210. toJSON( meta ) {
  17211. const data = super.toJSON( meta );
  17212. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17213. return data;
  17214. }
  17215. // @deprecated
  17216. get autoUpdate() {
  17217. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17218. return this.matrixWorldAutoUpdate;
  17219. }
  17220. set autoUpdate( value ) {
  17221. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17222. this.matrixWorldAutoUpdate = value;
  17223. }
  17224. }
  17225. class InterleavedBuffer {
  17226. constructor( array, stride ) {
  17227. this.isInterleavedBuffer = true;
  17228. this.array = array;
  17229. this.stride = stride;
  17230. this.count = array !== undefined ? array.length / stride : 0;
  17231. this.usage = StaticDrawUsage;
  17232. this.updateRange = { offset: 0, count: - 1 };
  17233. this.version = 0;
  17234. this.uuid = generateUUID();
  17235. }
  17236. onUploadCallback() {}
  17237. set needsUpdate( value ) {
  17238. if ( value === true ) this.version ++;
  17239. }
  17240. setUsage( value ) {
  17241. this.usage = value;
  17242. return this;
  17243. }
  17244. copy( source ) {
  17245. this.array = new source.array.constructor( source.array );
  17246. this.count = source.count;
  17247. this.stride = source.stride;
  17248. this.usage = source.usage;
  17249. return this;
  17250. }
  17251. copyAt( index1, attribute, index2 ) {
  17252. index1 *= this.stride;
  17253. index2 *= attribute.stride;
  17254. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17255. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17256. }
  17257. return this;
  17258. }
  17259. set( value, offset = 0 ) {
  17260. this.array.set( value, offset );
  17261. return this;
  17262. }
  17263. clone( data ) {
  17264. if ( data.arrayBuffers === undefined ) {
  17265. data.arrayBuffers = {};
  17266. }
  17267. if ( this.array.buffer._uuid === undefined ) {
  17268. this.array.buffer._uuid = generateUUID();
  17269. }
  17270. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17271. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17272. }
  17273. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17274. const ib = new this.constructor( array, this.stride );
  17275. ib.setUsage( this.usage );
  17276. return ib;
  17277. }
  17278. onUpload( callback ) {
  17279. this.onUploadCallback = callback;
  17280. return this;
  17281. }
  17282. toJSON( data ) {
  17283. if ( data.arrayBuffers === undefined ) {
  17284. data.arrayBuffers = {};
  17285. }
  17286. // generate UUID for array buffer if necessary
  17287. if ( this.array.buffer._uuid === undefined ) {
  17288. this.array.buffer._uuid = generateUUID();
  17289. }
  17290. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17291. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17292. }
  17293. //
  17294. return {
  17295. uuid: this.uuid,
  17296. buffer: this.array.buffer._uuid,
  17297. type: this.array.constructor.name,
  17298. stride: this.stride
  17299. };
  17300. }
  17301. }
  17302. const _vector$6 = /*@__PURE__*/ new Vector3();
  17303. class InterleavedBufferAttribute {
  17304. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17305. this.isInterleavedBufferAttribute = true;
  17306. this.name = '';
  17307. this.data = interleavedBuffer;
  17308. this.itemSize = itemSize;
  17309. this.offset = offset;
  17310. this.normalized = normalized === true;
  17311. }
  17312. get count() {
  17313. return this.data.count;
  17314. }
  17315. get array() {
  17316. return this.data.array;
  17317. }
  17318. set needsUpdate( value ) {
  17319. this.data.needsUpdate = value;
  17320. }
  17321. applyMatrix4( m ) {
  17322. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17323. _vector$6.fromBufferAttribute( this, i );
  17324. _vector$6.applyMatrix4( m );
  17325. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17326. }
  17327. return this;
  17328. }
  17329. applyNormalMatrix( m ) {
  17330. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17331. _vector$6.fromBufferAttribute( this, i );
  17332. _vector$6.applyNormalMatrix( m );
  17333. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17334. }
  17335. return this;
  17336. }
  17337. transformDirection( m ) {
  17338. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17339. _vector$6.fromBufferAttribute( this, i );
  17340. _vector$6.transformDirection( m );
  17341. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17342. }
  17343. return this;
  17344. }
  17345. setX( index, x ) {
  17346. if ( this.normalized ) x = normalize( x, this.array );
  17347. this.data.array[ index * this.data.stride + this.offset ] = x;
  17348. return this;
  17349. }
  17350. setY( index, y ) {
  17351. if ( this.normalized ) y = normalize( y, this.array );
  17352. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17353. return this;
  17354. }
  17355. setZ( index, z ) {
  17356. if ( this.normalized ) z = normalize( z, this.array );
  17357. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17358. return this;
  17359. }
  17360. setW( index, w ) {
  17361. if ( this.normalized ) w = normalize( w, this.array );
  17362. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17363. return this;
  17364. }
  17365. getX( index ) {
  17366. let x = this.data.array[ index * this.data.stride + this.offset ];
  17367. if ( this.normalized ) x = denormalize( x, this.array );
  17368. return x;
  17369. }
  17370. getY( index ) {
  17371. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17372. if ( this.normalized ) y = denormalize( y, this.array );
  17373. return y;
  17374. }
  17375. getZ( index ) {
  17376. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17377. if ( this.normalized ) z = denormalize( z, this.array );
  17378. return z;
  17379. }
  17380. getW( index ) {
  17381. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17382. if ( this.normalized ) w = denormalize( w, this.array );
  17383. return w;
  17384. }
  17385. setXY( index, x, y ) {
  17386. index = index * this.data.stride + this.offset;
  17387. if ( this.normalized ) {
  17388. x = normalize( x, this.array );
  17389. y = normalize( y, this.array );
  17390. }
  17391. this.data.array[ index + 0 ] = x;
  17392. this.data.array[ index + 1 ] = y;
  17393. return this;
  17394. }
  17395. setXYZ( index, x, y, z ) {
  17396. index = index * this.data.stride + this.offset;
  17397. if ( this.normalized ) {
  17398. x = normalize( x, this.array );
  17399. y = normalize( y, this.array );
  17400. z = normalize( z, this.array );
  17401. }
  17402. this.data.array[ index + 0 ] = x;
  17403. this.data.array[ index + 1 ] = y;
  17404. this.data.array[ index + 2 ] = z;
  17405. return this;
  17406. }
  17407. setXYZW( index, x, y, z, w ) {
  17408. index = index * this.data.stride + this.offset;
  17409. if ( this.normalized ) {
  17410. x = normalize( x, this.array );
  17411. y = normalize( y, this.array );
  17412. z = normalize( z, this.array );
  17413. w = normalize( w, this.array );
  17414. }
  17415. this.data.array[ index + 0 ] = x;
  17416. this.data.array[ index + 1 ] = y;
  17417. this.data.array[ index + 2 ] = z;
  17418. this.data.array[ index + 3 ] = w;
  17419. return this;
  17420. }
  17421. clone( data ) {
  17422. if ( data === undefined ) {
  17423. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' );
  17424. const array = [];
  17425. for ( let i = 0; i < this.count; i ++ ) {
  17426. const index = i * this.data.stride + this.offset;
  17427. for ( let j = 0; j < this.itemSize; j ++ ) {
  17428. array.push( this.data.array[ index + j ] );
  17429. }
  17430. }
  17431. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17432. } else {
  17433. if ( data.interleavedBuffers === undefined ) {
  17434. data.interleavedBuffers = {};
  17435. }
  17436. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17437. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17438. }
  17439. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17440. }
  17441. }
  17442. toJSON( data ) {
  17443. if ( data === undefined ) {
  17444. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' );
  17445. const array = [];
  17446. for ( let i = 0; i < this.count; i ++ ) {
  17447. const index = i * this.data.stride + this.offset;
  17448. for ( let j = 0; j < this.itemSize; j ++ ) {
  17449. array.push( this.data.array[ index + j ] );
  17450. }
  17451. }
  17452. // deinterleave data and save it as an ordinary buffer attribute for now
  17453. return {
  17454. itemSize: this.itemSize,
  17455. type: this.array.constructor.name,
  17456. array: array,
  17457. normalized: this.normalized
  17458. };
  17459. } else {
  17460. // save as true interleaved attribtue
  17461. if ( data.interleavedBuffers === undefined ) {
  17462. data.interleavedBuffers = {};
  17463. }
  17464. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17465. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17466. }
  17467. return {
  17468. isInterleavedBufferAttribute: true,
  17469. itemSize: this.itemSize,
  17470. data: this.data.uuid,
  17471. offset: this.offset,
  17472. normalized: this.normalized
  17473. };
  17474. }
  17475. }
  17476. }
  17477. class SpriteMaterial extends Material {
  17478. constructor( parameters ) {
  17479. super();
  17480. this.isSpriteMaterial = true;
  17481. this.type = 'SpriteMaterial';
  17482. this.color = new Color( 0xffffff );
  17483. this.map = null;
  17484. this.alphaMap = null;
  17485. this.rotation = 0;
  17486. this.sizeAttenuation = true;
  17487. this.transparent = true;
  17488. this.fog = true;
  17489. this.setValues( parameters );
  17490. }
  17491. copy( source ) {
  17492. super.copy( source );
  17493. this.color.copy( source.color );
  17494. this.map = source.map;
  17495. this.alphaMap = source.alphaMap;
  17496. this.rotation = source.rotation;
  17497. this.sizeAttenuation = source.sizeAttenuation;
  17498. this.fog = source.fog;
  17499. return this;
  17500. }
  17501. }
  17502. let _geometry;
  17503. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17504. const _worldScale = /*@__PURE__*/ new Vector3();
  17505. const _mvPosition = /*@__PURE__*/ new Vector3();
  17506. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17507. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17508. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17509. const _vA = /*@__PURE__*/ new Vector3();
  17510. const _vB = /*@__PURE__*/ new Vector3();
  17511. const _vC = /*@__PURE__*/ new Vector3();
  17512. const _uvA = /*@__PURE__*/ new Vector2();
  17513. const _uvB = /*@__PURE__*/ new Vector2();
  17514. const _uvC = /*@__PURE__*/ new Vector2();
  17515. class Sprite extends Object3D {
  17516. constructor( material ) {
  17517. super();
  17518. this.isSprite = true;
  17519. this.type = 'Sprite';
  17520. if ( _geometry === undefined ) {
  17521. _geometry = new BufferGeometry();
  17522. const float32Array = new Float32Array( [
  17523. - 0.5, - 0.5, 0, 0, 0,
  17524. 0.5, - 0.5, 0, 1, 0,
  17525. 0.5, 0.5, 0, 1, 1,
  17526. - 0.5, 0.5, 0, 0, 1
  17527. ] );
  17528. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17529. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17530. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17531. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17532. }
  17533. this.geometry = _geometry;
  17534. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17535. this.center = new Vector2( 0.5, 0.5 );
  17536. }
  17537. raycast( raycaster, intersects ) {
  17538. if ( raycaster.camera === null ) {
  17539. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17540. }
  17541. _worldScale.setFromMatrixScale( this.matrixWorld );
  17542. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17543. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17544. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17545. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17546. _worldScale.multiplyScalar( - _mvPosition.z );
  17547. }
  17548. const rotation = this.material.rotation;
  17549. let sin, cos;
  17550. if ( rotation !== 0 ) {
  17551. cos = Math.cos( rotation );
  17552. sin = Math.sin( rotation );
  17553. }
  17554. const center = this.center;
  17555. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17556. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17557. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17558. _uvA.set( 0, 0 );
  17559. _uvB.set( 1, 0 );
  17560. _uvC.set( 1, 1 );
  17561. // check first triangle
  17562. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17563. if ( intersect === null ) {
  17564. // check second triangle
  17565. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17566. _uvB.set( 0, 1 );
  17567. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17568. if ( intersect === null ) {
  17569. return;
  17570. }
  17571. }
  17572. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17573. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17574. intersects.push( {
  17575. distance: distance,
  17576. point: _intersectPoint.clone(),
  17577. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17578. face: null,
  17579. object: this
  17580. } );
  17581. }
  17582. copy( source, recursive ) {
  17583. super.copy( source, recursive );
  17584. if ( source.center !== undefined ) this.center.copy( source.center );
  17585. this.material = source.material;
  17586. return this;
  17587. }
  17588. }
  17589. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17590. // compute position in camera space
  17591. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17592. // to check if rotation is not zero
  17593. if ( sin !== undefined ) {
  17594. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17595. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17596. } else {
  17597. _rotatedPosition.copy( _alignedPosition );
  17598. }
  17599. vertexPosition.copy( mvPosition );
  17600. vertexPosition.x += _rotatedPosition.x;
  17601. vertexPosition.y += _rotatedPosition.y;
  17602. // transform to world space
  17603. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17604. }
  17605. const _v1$2 = /*@__PURE__*/ new Vector3();
  17606. const _v2$1 = /*@__PURE__*/ new Vector3();
  17607. class LOD extends Object3D {
  17608. constructor() {
  17609. super();
  17610. this._currentLevel = 0;
  17611. this.type = 'LOD';
  17612. Object.defineProperties( this, {
  17613. levels: {
  17614. enumerable: true,
  17615. value: []
  17616. },
  17617. isLOD: {
  17618. value: true,
  17619. }
  17620. } );
  17621. this.autoUpdate = true;
  17622. }
  17623. copy( source ) {
  17624. super.copy( source, false );
  17625. const levels = source.levels;
  17626. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17627. const level = levels[ i ];
  17628. this.addLevel( level.object.clone(), level.distance );
  17629. }
  17630. this.autoUpdate = source.autoUpdate;
  17631. return this;
  17632. }
  17633. addLevel( object, distance = 0 ) {
  17634. distance = Math.abs( distance );
  17635. const levels = this.levels;
  17636. let l;
  17637. for ( l = 0; l < levels.length; l ++ ) {
  17638. if ( distance < levels[ l ].distance ) {
  17639. break;
  17640. }
  17641. }
  17642. levels.splice( l, 0, { distance: distance, object: object } );
  17643. this.add( object );
  17644. return this;
  17645. }
  17646. getCurrentLevel() {
  17647. return this._currentLevel;
  17648. }
  17649. getObjectForDistance( distance ) {
  17650. const levels = this.levels;
  17651. if ( levels.length > 0 ) {
  17652. let i, l;
  17653. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17654. if ( distance < levels[ i ].distance ) {
  17655. break;
  17656. }
  17657. }
  17658. return levels[ i - 1 ].object;
  17659. }
  17660. return null;
  17661. }
  17662. raycast( raycaster, intersects ) {
  17663. const levels = this.levels;
  17664. if ( levels.length > 0 ) {
  17665. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17666. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17667. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17668. }
  17669. }
  17670. update( camera ) {
  17671. const levels = this.levels;
  17672. if ( levels.length > 1 ) {
  17673. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17674. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17675. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17676. levels[ 0 ].object.visible = true;
  17677. let i, l;
  17678. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17679. if ( distance >= levels[ i ].distance ) {
  17680. levels[ i - 1 ].object.visible = false;
  17681. levels[ i ].object.visible = true;
  17682. } else {
  17683. break;
  17684. }
  17685. }
  17686. this._currentLevel = i - 1;
  17687. for ( ; i < l; i ++ ) {
  17688. levels[ i ].object.visible = false;
  17689. }
  17690. }
  17691. }
  17692. toJSON( meta ) {
  17693. const data = super.toJSON( meta );
  17694. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17695. data.object.levels = [];
  17696. const levels = this.levels;
  17697. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17698. const level = levels[ i ];
  17699. data.object.levels.push( {
  17700. object: level.object.uuid,
  17701. distance: level.distance
  17702. } );
  17703. }
  17704. return data;
  17705. }
  17706. }
  17707. const _basePosition = /*@__PURE__*/ new Vector3();
  17708. const _skinIndex = /*@__PURE__*/ new Vector4();
  17709. const _skinWeight = /*@__PURE__*/ new Vector4();
  17710. const _vector$5 = /*@__PURE__*/ new Vector3();
  17711. const _matrix = /*@__PURE__*/ new Matrix4();
  17712. class SkinnedMesh extends Mesh {
  17713. constructor( geometry, material ) {
  17714. super( geometry, material );
  17715. this.isSkinnedMesh = true;
  17716. this.type = 'SkinnedMesh';
  17717. this.bindMode = 'attached';
  17718. this.bindMatrix = new Matrix4();
  17719. this.bindMatrixInverse = new Matrix4();
  17720. }
  17721. copy( source, recursive ) {
  17722. super.copy( source, recursive );
  17723. this.bindMode = source.bindMode;
  17724. this.bindMatrix.copy( source.bindMatrix );
  17725. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17726. this.skeleton = source.skeleton;
  17727. return this;
  17728. }
  17729. bind( skeleton, bindMatrix ) {
  17730. this.skeleton = skeleton;
  17731. if ( bindMatrix === undefined ) {
  17732. this.updateMatrixWorld( true );
  17733. this.skeleton.calculateInverses();
  17734. bindMatrix = this.matrixWorld;
  17735. }
  17736. this.bindMatrix.copy( bindMatrix );
  17737. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17738. }
  17739. pose() {
  17740. this.skeleton.pose();
  17741. }
  17742. normalizeSkinWeights() {
  17743. const vector = new Vector4();
  17744. const skinWeight = this.geometry.attributes.skinWeight;
  17745. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17746. vector.fromBufferAttribute( skinWeight, i );
  17747. const scale = 1.0 / vector.manhattanLength();
  17748. if ( scale !== Infinity ) {
  17749. vector.multiplyScalar( scale );
  17750. } else {
  17751. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17752. }
  17753. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17754. }
  17755. }
  17756. updateMatrixWorld( force ) {
  17757. super.updateMatrixWorld( force );
  17758. if ( this.bindMode === 'attached' ) {
  17759. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17760. } else if ( this.bindMode === 'detached' ) {
  17761. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17762. } else {
  17763. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17764. }
  17765. }
  17766. boneTransform( index, target ) {
  17767. const skeleton = this.skeleton;
  17768. const geometry = this.geometry;
  17769. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17770. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17771. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17772. target.set( 0, 0, 0 );
  17773. for ( let i = 0; i < 4; i ++ ) {
  17774. const weight = _skinWeight.getComponent( i );
  17775. if ( weight !== 0 ) {
  17776. const boneIndex = _skinIndex.getComponent( i );
  17777. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17778. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  17779. }
  17780. }
  17781. return target.applyMatrix4( this.bindMatrixInverse );
  17782. }
  17783. }
  17784. class Bone extends Object3D {
  17785. constructor() {
  17786. super();
  17787. this.isBone = true;
  17788. this.type = 'Bone';
  17789. }
  17790. }
  17791. class DataTexture extends Texture {
  17792. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  17793. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17794. this.isDataTexture = true;
  17795. this.image = { data: data, width: width, height: height };
  17796. this.generateMipmaps = false;
  17797. this.flipY = false;
  17798. this.unpackAlignment = 1;
  17799. }
  17800. }
  17801. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17802. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17803. class Skeleton {
  17804. constructor( bones = [], boneInverses = [] ) {
  17805. this.uuid = generateUUID();
  17806. this.bones = bones.slice( 0 );
  17807. this.boneInverses = boneInverses;
  17808. this.boneMatrices = null;
  17809. this.boneTexture = null;
  17810. this.boneTextureSize = 0;
  17811. this.frame = - 1;
  17812. this.init();
  17813. }
  17814. init() {
  17815. const bones = this.bones;
  17816. const boneInverses = this.boneInverses;
  17817. this.boneMatrices = new Float32Array( bones.length * 16 );
  17818. // calculate inverse bone matrices if necessary
  17819. if ( boneInverses.length === 0 ) {
  17820. this.calculateInverses();
  17821. } else {
  17822. // handle special case
  17823. if ( bones.length !== boneInverses.length ) {
  17824. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17825. this.boneInverses = [];
  17826. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17827. this.boneInverses.push( new Matrix4() );
  17828. }
  17829. }
  17830. }
  17831. }
  17832. calculateInverses() {
  17833. this.boneInverses.length = 0;
  17834. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17835. const inverse = new Matrix4();
  17836. if ( this.bones[ i ] ) {
  17837. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17838. }
  17839. this.boneInverses.push( inverse );
  17840. }
  17841. }
  17842. pose() {
  17843. // recover the bind-time world matrices
  17844. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17845. const bone = this.bones[ i ];
  17846. if ( bone ) {
  17847. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17848. }
  17849. }
  17850. // compute the local matrices, positions, rotations and scales
  17851. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17852. const bone = this.bones[ i ];
  17853. if ( bone ) {
  17854. if ( bone.parent && bone.parent.isBone ) {
  17855. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17856. bone.matrix.multiply( bone.matrixWorld );
  17857. } else {
  17858. bone.matrix.copy( bone.matrixWorld );
  17859. }
  17860. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17861. }
  17862. }
  17863. }
  17864. update() {
  17865. const bones = this.bones;
  17866. const boneInverses = this.boneInverses;
  17867. const boneMatrices = this.boneMatrices;
  17868. const boneTexture = this.boneTexture;
  17869. // flatten bone matrices to array
  17870. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17871. // compute the offset between the current and the original transform
  17872. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17873. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17874. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17875. }
  17876. if ( boneTexture !== null ) {
  17877. boneTexture.needsUpdate = true;
  17878. }
  17879. }
  17880. clone() {
  17881. return new Skeleton( this.bones, this.boneInverses );
  17882. }
  17883. computeBoneTexture() {
  17884. // layout (1 matrix = 4 pixels)
  17885. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17886. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17887. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17888. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17889. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17890. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17891. size = ceilPowerOfTwo( size );
  17892. size = Math.max( size, 4 );
  17893. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17894. boneMatrices.set( this.boneMatrices ); // copy current values
  17895. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17896. boneTexture.needsUpdate = true;
  17897. this.boneMatrices = boneMatrices;
  17898. this.boneTexture = boneTexture;
  17899. this.boneTextureSize = size;
  17900. return this;
  17901. }
  17902. getBoneByName( name ) {
  17903. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17904. const bone = this.bones[ i ];
  17905. if ( bone.name === name ) {
  17906. return bone;
  17907. }
  17908. }
  17909. return undefined;
  17910. }
  17911. dispose( ) {
  17912. if ( this.boneTexture !== null ) {
  17913. this.boneTexture.dispose();
  17914. this.boneTexture = null;
  17915. }
  17916. }
  17917. fromJSON( json, bones ) {
  17918. this.uuid = json.uuid;
  17919. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17920. const uuid = json.bones[ i ];
  17921. let bone = bones[ uuid ];
  17922. if ( bone === undefined ) {
  17923. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  17924. bone = new Bone();
  17925. }
  17926. this.bones.push( bone );
  17927. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17928. }
  17929. this.init();
  17930. return this;
  17931. }
  17932. toJSON() {
  17933. const data = {
  17934. metadata: {
  17935. version: 4.5,
  17936. type: 'Skeleton',
  17937. generator: 'Skeleton.toJSON'
  17938. },
  17939. bones: [],
  17940. boneInverses: []
  17941. };
  17942. data.uuid = this.uuid;
  17943. const bones = this.bones;
  17944. const boneInverses = this.boneInverses;
  17945. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17946. const bone = bones[ i ];
  17947. data.bones.push( bone.uuid );
  17948. const boneInverse = boneInverses[ i ];
  17949. data.boneInverses.push( boneInverse.toArray() );
  17950. }
  17951. return data;
  17952. }
  17953. }
  17954. class InstancedBufferAttribute extends BufferAttribute {
  17955. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17956. super( array, itemSize, normalized );
  17957. this.isInstancedBufferAttribute = true;
  17958. this.meshPerAttribute = meshPerAttribute;
  17959. }
  17960. copy( source ) {
  17961. super.copy( source );
  17962. this.meshPerAttribute = source.meshPerAttribute;
  17963. return this;
  17964. }
  17965. toJSON() {
  17966. const data = super.toJSON();
  17967. data.meshPerAttribute = this.meshPerAttribute;
  17968. data.isInstancedBufferAttribute = true;
  17969. return data;
  17970. }
  17971. }
  17972. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17973. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17974. const _instanceIntersects = [];
  17975. const _mesh = /*@__PURE__*/ new Mesh();
  17976. class InstancedMesh extends Mesh {
  17977. constructor( geometry, material, count ) {
  17978. super( geometry, material );
  17979. this.isInstancedMesh = true;
  17980. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17981. this.instanceColor = null;
  17982. this.count = count;
  17983. this.frustumCulled = false;
  17984. }
  17985. copy( source, recursive ) {
  17986. super.copy( source, recursive );
  17987. this.instanceMatrix.copy( source.instanceMatrix );
  17988. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17989. this.count = source.count;
  17990. return this;
  17991. }
  17992. getColorAt( index, color ) {
  17993. color.fromArray( this.instanceColor.array, index * 3 );
  17994. }
  17995. getMatrixAt( index, matrix ) {
  17996. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17997. }
  17998. raycast( raycaster, intersects ) {
  17999. const matrixWorld = this.matrixWorld;
  18000. const raycastTimes = this.count;
  18001. _mesh.geometry = this.geometry;
  18002. _mesh.material = this.material;
  18003. if ( _mesh.material === undefined ) return;
  18004. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18005. // calculate the world matrix for each instance
  18006. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18007. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18008. // the mesh represents this single instance
  18009. _mesh.matrixWorld = _instanceWorldMatrix;
  18010. _mesh.raycast( raycaster, _instanceIntersects );
  18011. // process the result of raycast
  18012. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18013. const intersect = _instanceIntersects[ i ];
  18014. intersect.instanceId = instanceId;
  18015. intersect.object = this;
  18016. intersects.push( intersect );
  18017. }
  18018. _instanceIntersects.length = 0;
  18019. }
  18020. }
  18021. setColorAt( index, color ) {
  18022. if ( this.instanceColor === null ) {
  18023. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18024. }
  18025. color.toArray( this.instanceColor.array, index * 3 );
  18026. }
  18027. setMatrixAt( index, matrix ) {
  18028. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18029. }
  18030. updateMorphTargets() {
  18031. }
  18032. dispose() {
  18033. this.dispatchEvent( { type: 'dispose' } );
  18034. }
  18035. }
  18036. class LineBasicMaterial extends Material {
  18037. constructor( parameters ) {
  18038. super();
  18039. this.isLineBasicMaterial = true;
  18040. this.type = 'LineBasicMaterial';
  18041. this.color = new Color( 0xffffff );
  18042. this.linewidth = 1;
  18043. this.linecap = 'round';
  18044. this.linejoin = 'round';
  18045. this.fog = true;
  18046. this.setValues( parameters );
  18047. }
  18048. copy( source ) {
  18049. super.copy( source );
  18050. this.color.copy( source.color );
  18051. this.linewidth = source.linewidth;
  18052. this.linecap = source.linecap;
  18053. this.linejoin = source.linejoin;
  18054. this.fog = source.fog;
  18055. return this;
  18056. }
  18057. }
  18058. const _start$1 = /*@__PURE__*/ new Vector3();
  18059. const _end$1 = /*@__PURE__*/ new Vector3();
  18060. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18061. const _ray$1 = /*@__PURE__*/ new Ray();
  18062. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18063. class Line extends Object3D {
  18064. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18065. super();
  18066. this.isLine = true;
  18067. this.type = 'Line';
  18068. this.geometry = geometry;
  18069. this.material = material;
  18070. this.updateMorphTargets();
  18071. }
  18072. copy( source, recursive ) {
  18073. super.copy( source, recursive );
  18074. this.material = source.material;
  18075. this.geometry = source.geometry;
  18076. return this;
  18077. }
  18078. computeLineDistances() {
  18079. const geometry = this.geometry;
  18080. // we assume non-indexed geometry
  18081. if ( geometry.index === null ) {
  18082. const positionAttribute = geometry.attributes.position;
  18083. const lineDistances = [ 0 ];
  18084. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18085. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18086. _end$1.fromBufferAttribute( positionAttribute, i );
  18087. lineDistances[ i ] = lineDistances[ i - 1 ];
  18088. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18089. }
  18090. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18091. } else {
  18092. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18093. }
  18094. return this;
  18095. }
  18096. raycast( raycaster, intersects ) {
  18097. const geometry = this.geometry;
  18098. const matrixWorld = this.matrixWorld;
  18099. const threshold = raycaster.params.Line.threshold;
  18100. const drawRange = geometry.drawRange;
  18101. // Checking boundingSphere distance to ray
  18102. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18103. _sphere$1.copy( geometry.boundingSphere );
  18104. _sphere$1.applyMatrix4( matrixWorld );
  18105. _sphere$1.radius += threshold;
  18106. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18107. //
  18108. _inverseMatrix$1.copy( matrixWorld ).invert();
  18109. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18110. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18111. const localThresholdSq = localThreshold * localThreshold;
  18112. const vStart = new Vector3();
  18113. const vEnd = new Vector3();
  18114. const interSegment = new Vector3();
  18115. const interRay = new Vector3();
  18116. const step = this.isLineSegments ? 2 : 1;
  18117. const index = geometry.index;
  18118. const attributes = geometry.attributes;
  18119. const positionAttribute = attributes.position;
  18120. if ( index !== null ) {
  18121. const start = Math.max( 0, drawRange.start );
  18122. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18123. for ( let i = start, l = end - 1; i < l; i += step ) {
  18124. const a = index.getX( i );
  18125. const b = index.getX( i + 1 );
  18126. vStart.fromBufferAttribute( positionAttribute, a );
  18127. vEnd.fromBufferAttribute( positionAttribute, b );
  18128. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18129. if ( distSq > localThresholdSq ) continue;
  18130. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18131. const distance = raycaster.ray.origin.distanceTo( interRay );
  18132. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18133. intersects.push( {
  18134. distance: distance,
  18135. // What do we want? intersection point on the ray or on the segment??
  18136. // point: raycaster.ray.at( distance ),
  18137. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18138. index: i,
  18139. face: null,
  18140. faceIndex: null,
  18141. object: this
  18142. } );
  18143. }
  18144. } else {
  18145. const start = Math.max( 0, drawRange.start );
  18146. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18147. for ( let i = start, l = end - 1; i < l; i += step ) {
  18148. vStart.fromBufferAttribute( positionAttribute, i );
  18149. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18150. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18151. if ( distSq > localThresholdSq ) continue;
  18152. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18153. const distance = raycaster.ray.origin.distanceTo( interRay );
  18154. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18155. intersects.push( {
  18156. distance: distance,
  18157. // What do we want? intersection point on the ray or on the segment??
  18158. // point: raycaster.ray.at( distance ),
  18159. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18160. index: i,
  18161. face: null,
  18162. faceIndex: null,
  18163. object: this
  18164. } );
  18165. }
  18166. }
  18167. }
  18168. updateMorphTargets() {
  18169. const geometry = this.geometry;
  18170. const morphAttributes = geometry.morphAttributes;
  18171. const keys = Object.keys( morphAttributes );
  18172. if ( keys.length > 0 ) {
  18173. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18174. if ( morphAttribute !== undefined ) {
  18175. this.morphTargetInfluences = [];
  18176. this.morphTargetDictionary = {};
  18177. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18178. const name = morphAttribute[ m ].name || String( m );
  18179. this.morphTargetInfluences.push( 0 );
  18180. this.morphTargetDictionary[ name ] = m;
  18181. }
  18182. }
  18183. }
  18184. }
  18185. }
  18186. const _start = /*@__PURE__*/ new Vector3();
  18187. const _end = /*@__PURE__*/ new Vector3();
  18188. class LineSegments extends Line {
  18189. constructor( geometry, material ) {
  18190. super( geometry, material );
  18191. this.isLineSegments = true;
  18192. this.type = 'LineSegments';
  18193. }
  18194. computeLineDistances() {
  18195. const geometry = this.geometry;
  18196. // we assume non-indexed geometry
  18197. if ( geometry.index === null ) {
  18198. const positionAttribute = geometry.attributes.position;
  18199. const lineDistances = [];
  18200. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18201. _start.fromBufferAttribute( positionAttribute, i );
  18202. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18203. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18204. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18205. }
  18206. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18207. } else {
  18208. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18209. }
  18210. return this;
  18211. }
  18212. }
  18213. class LineLoop extends Line {
  18214. constructor( geometry, material ) {
  18215. super( geometry, material );
  18216. this.isLineLoop = true;
  18217. this.type = 'LineLoop';
  18218. }
  18219. }
  18220. class PointsMaterial extends Material {
  18221. constructor( parameters ) {
  18222. super();
  18223. this.isPointsMaterial = true;
  18224. this.type = 'PointsMaterial';
  18225. this.color = new Color( 0xffffff );
  18226. this.map = null;
  18227. this.alphaMap = null;
  18228. this.size = 1;
  18229. this.sizeAttenuation = true;
  18230. this.fog = true;
  18231. this.setValues( parameters );
  18232. }
  18233. copy( source ) {
  18234. super.copy( source );
  18235. this.color.copy( source.color );
  18236. this.map = source.map;
  18237. this.alphaMap = source.alphaMap;
  18238. this.size = source.size;
  18239. this.sizeAttenuation = source.sizeAttenuation;
  18240. this.fog = source.fog;
  18241. return this;
  18242. }
  18243. }
  18244. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18245. const _ray = /*@__PURE__*/ new Ray();
  18246. const _sphere = /*@__PURE__*/ new Sphere();
  18247. const _position$2 = /*@__PURE__*/ new Vector3();
  18248. class Points extends Object3D {
  18249. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18250. super();
  18251. this.isPoints = true;
  18252. this.type = 'Points';
  18253. this.geometry = geometry;
  18254. this.material = material;
  18255. this.updateMorphTargets();
  18256. }
  18257. copy( source, recursive ) {
  18258. super.copy( source, recursive );
  18259. this.material = source.material;
  18260. this.geometry = source.geometry;
  18261. return this;
  18262. }
  18263. raycast( raycaster, intersects ) {
  18264. const geometry = this.geometry;
  18265. const matrixWorld = this.matrixWorld;
  18266. const threshold = raycaster.params.Points.threshold;
  18267. const drawRange = geometry.drawRange;
  18268. // Checking boundingSphere distance to ray
  18269. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18270. _sphere.copy( geometry.boundingSphere );
  18271. _sphere.applyMatrix4( matrixWorld );
  18272. _sphere.radius += threshold;
  18273. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18274. //
  18275. _inverseMatrix.copy( matrixWorld ).invert();
  18276. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18277. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18278. const localThresholdSq = localThreshold * localThreshold;
  18279. const index = geometry.index;
  18280. const attributes = geometry.attributes;
  18281. const positionAttribute = attributes.position;
  18282. if ( index !== null ) {
  18283. const start = Math.max( 0, drawRange.start );
  18284. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18285. for ( let i = start, il = end; i < il; i ++ ) {
  18286. const a = index.getX( i );
  18287. _position$2.fromBufferAttribute( positionAttribute, a );
  18288. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18289. }
  18290. } else {
  18291. const start = Math.max( 0, drawRange.start );
  18292. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18293. for ( let i = start, l = end; i < l; i ++ ) {
  18294. _position$2.fromBufferAttribute( positionAttribute, i );
  18295. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18296. }
  18297. }
  18298. }
  18299. updateMorphTargets() {
  18300. const geometry = this.geometry;
  18301. const morphAttributes = geometry.morphAttributes;
  18302. const keys = Object.keys( morphAttributes );
  18303. if ( keys.length > 0 ) {
  18304. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18305. if ( morphAttribute !== undefined ) {
  18306. this.morphTargetInfluences = [];
  18307. this.morphTargetDictionary = {};
  18308. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18309. const name = morphAttribute[ m ].name || String( m );
  18310. this.morphTargetInfluences.push( 0 );
  18311. this.morphTargetDictionary[ name ] = m;
  18312. }
  18313. }
  18314. }
  18315. }
  18316. }
  18317. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18318. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18319. if ( rayPointDistanceSq < localThresholdSq ) {
  18320. const intersectPoint = new Vector3();
  18321. _ray.closestPointToPoint( point, intersectPoint );
  18322. intersectPoint.applyMatrix4( matrixWorld );
  18323. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18324. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18325. intersects.push( {
  18326. distance: distance,
  18327. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18328. point: intersectPoint,
  18329. index: index,
  18330. face: null,
  18331. object: object
  18332. } );
  18333. }
  18334. }
  18335. class VideoTexture extends Texture {
  18336. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18337. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18338. this.isVideoTexture = true;
  18339. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18340. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18341. this.generateMipmaps = false;
  18342. const scope = this;
  18343. function updateVideo() {
  18344. scope.needsUpdate = true;
  18345. video.requestVideoFrameCallback( updateVideo );
  18346. }
  18347. if ( 'requestVideoFrameCallback' in video ) {
  18348. video.requestVideoFrameCallback( updateVideo );
  18349. }
  18350. }
  18351. clone() {
  18352. return new this.constructor( this.image ).copy( this );
  18353. }
  18354. update() {
  18355. const video = this.image;
  18356. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18357. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18358. this.needsUpdate = true;
  18359. }
  18360. }
  18361. }
  18362. class FramebufferTexture extends Texture {
  18363. constructor( width, height, format ) {
  18364. super( { width, height } );
  18365. this.isFramebufferTexture = true;
  18366. this.format = format;
  18367. this.magFilter = NearestFilter;
  18368. this.minFilter = NearestFilter;
  18369. this.generateMipmaps = false;
  18370. this.needsUpdate = true;
  18371. }
  18372. }
  18373. class CompressedTexture extends Texture {
  18374. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18375. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18376. this.isCompressedTexture = true;
  18377. this.image = { width: width, height: height };
  18378. this.mipmaps = mipmaps;
  18379. // no flipping for cube textures
  18380. // (also flipping doesn't work for compressed textures )
  18381. this.flipY = false;
  18382. // can't generate mipmaps for compressed textures
  18383. // mips must be embedded in DDS files
  18384. this.generateMipmaps = false;
  18385. }
  18386. }
  18387. class CanvasTexture extends Texture {
  18388. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18389. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18390. this.isCanvasTexture = true;
  18391. this.needsUpdate = true;
  18392. }
  18393. }
  18394. /**
  18395. * Extensible curve object.
  18396. *
  18397. * Some common of curve methods:
  18398. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18399. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18400. * .getPoints(), .getSpacedPoints()
  18401. * .getLength()
  18402. * .updateArcLengths()
  18403. *
  18404. * This following curves inherit from THREE.Curve:
  18405. *
  18406. * -- 2D curves --
  18407. * THREE.ArcCurve
  18408. * THREE.CubicBezierCurve
  18409. * THREE.EllipseCurve
  18410. * THREE.LineCurve
  18411. * THREE.QuadraticBezierCurve
  18412. * THREE.SplineCurve
  18413. *
  18414. * -- 3D curves --
  18415. * THREE.CatmullRomCurve3
  18416. * THREE.CubicBezierCurve3
  18417. * THREE.LineCurve3
  18418. * THREE.QuadraticBezierCurve3
  18419. *
  18420. * A series of curves can be represented as a THREE.CurvePath.
  18421. *
  18422. **/
  18423. class Curve {
  18424. constructor() {
  18425. this.type = 'Curve';
  18426. this.arcLengthDivisions = 200;
  18427. }
  18428. // Virtual base class method to overwrite and implement in subclasses
  18429. // - t [0 .. 1]
  18430. getPoint( /* t, optionalTarget */ ) {
  18431. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18432. return null;
  18433. }
  18434. // Get point at relative position in curve according to arc length
  18435. // - u [0 .. 1]
  18436. getPointAt( u, optionalTarget ) {
  18437. const t = this.getUtoTmapping( u );
  18438. return this.getPoint( t, optionalTarget );
  18439. }
  18440. // Get sequence of points using getPoint( t )
  18441. getPoints( divisions = 5 ) {
  18442. const points = [];
  18443. for ( let d = 0; d <= divisions; d ++ ) {
  18444. points.push( this.getPoint( d / divisions ) );
  18445. }
  18446. return points;
  18447. }
  18448. // Get sequence of points using getPointAt( u )
  18449. getSpacedPoints( divisions = 5 ) {
  18450. const points = [];
  18451. for ( let d = 0; d <= divisions; d ++ ) {
  18452. points.push( this.getPointAt( d / divisions ) );
  18453. }
  18454. return points;
  18455. }
  18456. // Get total curve arc length
  18457. getLength() {
  18458. const lengths = this.getLengths();
  18459. return lengths[ lengths.length - 1 ];
  18460. }
  18461. // Get list of cumulative segment lengths
  18462. getLengths( divisions = this.arcLengthDivisions ) {
  18463. if ( this.cacheArcLengths &&
  18464. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18465. ! this.needsUpdate ) {
  18466. return this.cacheArcLengths;
  18467. }
  18468. this.needsUpdate = false;
  18469. const cache = [];
  18470. let current, last = this.getPoint( 0 );
  18471. let sum = 0;
  18472. cache.push( 0 );
  18473. for ( let p = 1; p <= divisions; p ++ ) {
  18474. current = this.getPoint( p / divisions );
  18475. sum += current.distanceTo( last );
  18476. cache.push( sum );
  18477. last = current;
  18478. }
  18479. this.cacheArcLengths = cache;
  18480. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18481. }
  18482. updateArcLengths() {
  18483. this.needsUpdate = true;
  18484. this.getLengths();
  18485. }
  18486. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18487. getUtoTmapping( u, distance ) {
  18488. const arcLengths = this.getLengths();
  18489. let i = 0;
  18490. const il = arcLengths.length;
  18491. let targetArcLength; // The targeted u distance value to get
  18492. if ( distance ) {
  18493. targetArcLength = distance;
  18494. } else {
  18495. targetArcLength = u * arcLengths[ il - 1 ];
  18496. }
  18497. // binary search for the index with largest value smaller than target u distance
  18498. let low = 0, high = il - 1, comparison;
  18499. while ( low <= high ) {
  18500. 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
  18501. comparison = arcLengths[ i ] - targetArcLength;
  18502. if ( comparison < 0 ) {
  18503. low = i + 1;
  18504. } else if ( comparison > 0 ) {
  18505. high = i - 1;
  18506. } else {
  18507. high = i;
  18508. break;
  18509. // DONE
  18510. }
  18511. }
  18512. i = high;
  18513. if ( arcLengths[ i ] === targetArcLength ) {
  18514. return i / ( il - 1 );
  18515. }
  18516. // we could get finer grain at lengths, or use simple interpolation between two points
  18517. const lengthBefore = arcLengths[ i ];
  18518. const lengthAfter = arcLengths[ i + 1 ];
  18519. const segmentLength = lengthAfter - lengthBefore;
  18520. // determine where we are between the 'before' and 'after' points
  18521. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18522. // add that fractional amount to t
  18523. const t = ( i + segmentFraction ) / ( il - 1 );
  18524. return t;
  18525. }
  18526. // Returns a unit vector tangent at t
  18527. // In case any sub curve does not implement its tangent derivation,
  18528. // 2 points a small delta apart will be used to find its gradient
  18529. // which seems to give a reasonable approximation
  18530. getTangent( t, optionalTarget ) {
  18531. const delta = 0.0001;
  18532. let t1 = t - delta;
  18533. let t2 = t + delta;
  18534. // Capping in case of danger
  18535. if ( t1 < 0 ) t1 = 0;
  18536. if ( t2 > 1 ) t2 = 1;
  18537. const pt1 = this.getPoint( t1 );
  18538. const pt2 = this.getPoint( t2 );
  18539. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18540. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18541. return tangent;
  18542. }
  18543. getTangentAt( u, optionalTarget ) {
  18544. const t = this.getUtoTmapping( u );
  18545. return this.getTangent( t, optionalTarget );
  18546. }
  18547. computeFrenetFrames( segments, closed ) {
  18548. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18549. const normal = new Vector3();
  18550. const tangents = [];
  18551. const normals = [];
  18552. const binormals = [];
  18553. const vec = new Vector3();
  18554. const mat = new Matrix4();
  18555. // compute the tangent vectors for each segment on the curve
  18556. for ( let i = 0; i <= segments; i ++ ) {
  18557. const u = i / segments;
  18558. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18559. }
  18560. // select an initial normal vector perpendicular to the first tangent vector,
  18561. // and in the direction of the minimum tangent xyz component
  18562. normals[ 0 ] = new Vector3();
  18563. binormals[ 0 ] = new Vector3();
  18564. let min = Number.MAX_VALUE;
  18565. const tx = Math.abs( tangents[ 0 ].x );
  18566. const ty = Math.abs( tangents[ 0 ].y );
  18567. const tz = Math.abs( tangents[ 0 ].z );
  18568. if ( tx <= min ) {
  18569. min = tx;
  18570. normal.set( 1, 0, 0 );
  18571. }
  18572. if ( ty <= min ) {
  18573. min = ty;
  18574. normal.set( 0, 1, 0 );
  18575. }
  18576. if ( tz <= min ) {
  18577. normal.set( 0, 0, 1 );
  18578. }
  18579. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18580. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18581. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18582. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18583. for ( let i = 1; i <= segments; i ++ ) {
  18584. normals[ i ] = normals[ i - 1 ].clone();
  18585. binormals[ i ] = binormals[ i - 1 ].clone();
  18586. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18587. if ( vec.length() > Number.EPSILON ) {
  18588. vec.normalize();
  18589. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18590. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18591. }
  18592. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18593. }
  18594. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18595. if ( closed === true ) {
  18596. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18597. theta /= segments;
  18598. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18599. theta = - theta;
  18600. }
  18601. for ( let i = 1; i <= segments; i ++ ) {
  18602. // twist a little...
  18603. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18604. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18605. }
  18606. }
  18607. return {
  18608. tangents: tangents,
  18609. normals: normals,
  18610. binormals: binormals
  18611. };
  18612. }
  18613. clone() {
  18614. return new this.constructor().copy( this );
  18615. }
  18616. copy( source ) {
  18617. this.arcLengthDivisions = source.arcLengthDivisions;
  18618. return this;
  18619. }
  18620. toJSON() {
  18621. const data = {
  18622. metadata: {
  18623. version: 4.5,
  18624. type: 'Curve',
  18625. generator: 'Curve.toJSON'
  18626. }
  18627. };
  18628. data.arcLengthDivisions = this.arcLengthDivisions;
  18629. data.type = this.type;
  18630. return data;
  18631. }
  18632. fromJSON( json ) {
  18633. this.arcLengthDivisions = json.arcLengthDivisions;
  18634. return this;
  18635. }
  18636. }
  18637. class EllipseCurve extends Curve {
  18638. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18639. super();
  18640. this.isEllipseCurve = true;
  18641. this.type = 'EllipseCurve';
  18642. this.aX = aX;
  18643. this.aY = aY;
  18644. this.xRadius = xRadius;
  18645. this.yRadius = yRadius;
  18646. this.aStartAngle = aStartAngle;
  18647. this.aEndAngle = aEndAngle;
  18648. this.aClockwise = aClockwise;
  18649. this.aRotation = aRotation;
  18650. }
  18651. getPoint( t, optionalTarget ) {
  18652. const point = optionalTarget || new Vector2();
  18653. const twoPi = Math.PI * 2;
  18654. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18655. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18656. // ensures that deltaAngle is 0 .. 2 PI
  18657. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18658. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18659. if ( deltaAngle < Number.EPSILON ) {
  18660. if ( samePoints ) {
  18661. deltaAngle = 0;
  18662. } else {
  18663. deltaAngle = twoPi;
  18664. }
  18665. }
  18666. if ( this.aClockwise === true && ! samePoints ) {
  18667. if ( deltaAngle === twoPi ) {
  18668. deltaAngle = - twoPi;
  18669. } else {
  18670. deltaAngle = deltaAngle - twoPi;
  18671. }
  18672. }
  18673. const angle = this.aStartAngle + t * deltaAngle;
  18674. let x = this.aX + this.xRadius * Math.cos( angle );
  18675. let y = this.aY + this.yRadius * Math.sin( angle );
  18676. if ( this.aRotation !== 0 ) {
  18677. const cos = Math.cos( this.aRotation );
  18678. const sin = Math.sin( this.aRotation );
  18679. const tx = x - this.aX;
  18680. const ty = y - this.aY;
  18681. // Rotate the point about the center of the ellipse.
  18682. x = tx * cos - ty * sin + this.aX;
  18683. y = tx * sin + ty * cos + this.aY;
  18684. }
  18685. return point.set( x, y );
  18686. }
  18687. copy( source ) {
  18688. super.copy( source );
  18689. this.aX = source.aX;
  18690. this.aY = source.aY;
  18691. this.xRadius = source.xRadius;
  18692. this.yRadius = source.yRadius;
  18693. this.aStartAngle = source.aStartAngle;
  18694. this.aEndAngle = source.aEndAngle;
  18695. this.aClockwise = source.aClockwise;
  18696. this.aRotation = source.aRotation;
  18697. return this;
  18698. }
  18699. toJSON() {
  18700. const data = super.toJSON();
  18701. data.aX = this.aX;
  18702. data.aY = this.aY;
  18703. data.xRadius = this.xRadius;
  18704. data.yRadius = this.yRadius;
  18705. data.aStartAngle = this.aStartAngle;
  18706. data.aEndAngle = this.aEndAngle;
  18707. data.aClockwise = this.aClockwise;
  18708. data.aRotation = this.aRotation;
  18709. return data;
  18710. }
  18711. fromJSON( json ) {
  18712. super.fromJSON( json );
  18713. this.aX = json.aX;
  18714. this.aY = json.aY;
  18715. this.xRadius = json.xRadius;
  18716. this.yRadius = json.yRadius;
  18717. this.aStartAngle = json.aStartAngle;
  18718. this.aEndAngle = json.aEndAngle;
  18719. this.aClockwise = json.aClockwise;
  18720. this.aRotation = json.aRotation;
  18721. return this;
  18722. }
  18723. }
  18724. class ArcCurve extends EllipseCurve {
  18725. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18726. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18727. this.isArcCurve = true;
  18728. this.type = 'ArcCurve';
  18729. }
  18730. }
  18731. /**
  18732. * Centripetal CatmullRom Curve - which is useful for avoiding
  18733. * cusps and self-intersections in non-uniform catmull rom curves.
  18734. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18735. *
  18736. * curve.type accepts centripetal(default), chordal and catmullrom
  18737. * curve.tension is used for catmullrom which defaults to 0.5
  18738. */
  18739. /*
  18740. Based on an optimized c++ solution in
  18741. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18742. - http://ideone.com/NoEbVM
  18743. This CubicPoly class could be used for reusing some variables and calculations,
  18744. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18745. which can be placed in CurveUtils.
  18746. */
  18747. function CubicPoly() {
  18748. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18749. /*
  18750. * Compute coefficients for a cubic polynomial
  18751. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18752. * such that
  18753. * p(0) = x0, p(1) = x1
  18754. * and
  18755. * p'(0) = t0, p'(1) = t1.
  18756. */
  18757. function init( x0, x1, t0, t1 ) {
  18758. c0 = x0;
  18759. c1 = t0;
  18760. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18761. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18762. }
  18763. return {
  18764. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18765. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18766. },
  18767. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18768. // compute tangents when parameterized in [t1,t2]
  18769. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18770. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18771. // rescale tangents for parametrization in [0,1]
  18772. t1 *= dt1;
  18773. t2 *= dt1;
  18774. init( x1, x2, t1, t2 );
  18775. },
  18776. calc: function ( t ) {
  18777. const t2 = t * t;
  18778. const t3 = t2 * t;
  18779. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18780. }
  18781. };
  18782. }
  18783. //
  18784. const tmp = /*@__PURE__*/ new Vector3();
  18785. const px = /*@__PURE__*/ new CubicPoly();
  18786. const py = /*@__PURE__*/ new CubicPoly();
  18787. const pz = /*@__PURE__*/ new CubicPoly();
  18788. class CatmullRomCurve3 extends Curve {
  18789. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18790. super();
  18791. this.isCatmullRomCurve3 = true;
  18792. this.type = 'CatmullRomCurve3';
  18793. this.points = points;
  18794. this.closed = closed;
  18795. this.curveType = curveType;
  18796. this.tension = tension;
  18797. }
  18798. getPoint( t, optionalTarget = new Vector3() ) {
  18799. const point = optionalTarget;
  18800. const points = this.points;
  18801. const l = points.length;
  18802. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18803. let intPoint = Math.floor( p );
  18804. let weight = p - intPoint;
  18805. if ( this.closed ) {
  18806. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18807. } else if ( weight === 0 && intPoint === l - 1 ) {
  18808. intPoint = l - 2;
  18809. weight = 1;
  18810. }
  18811. let p0, p3; // 4 points (p1 & p2 defined below)
  18812. if ( this.closed || intPoint > 0 ) {
  18813. p0 = points[ ( intPoint - 1 ) % l ];
  18814. } else {
  18815. // extrapolate first point
  18816. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18817. p0 = tmp;
  18818. }
  18819. const p1 = points[ intPoint % l ];
  18820. const p2 = points[ ( intPoint + 1 ) % l ];
  18821. if ( this.closed || intPoint + 2 < l ) {
  18822. p3 = points[ ( intPoint + 2 ) % l ];
  18823. } else {
  18824. // extrapolate last point
  18825. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18826. p3 = tmp;
  18827. }
  18828. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18829. // init Centripetal / Chordal Catmull-Rom
  18830. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18831. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18832. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18833. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18834. // safety check for repeated points
  18835. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18836. if ( dt0 < 1e-4 ) dt0 = dt1;
  18837. if ( dt2 < 1e-4 ) dt2 = dt1;
  18838. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18839. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18840. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18841. } else if ( this.curveType === 'catmullrom' ) {
  18842. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18843. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18844. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18845. }
  18846. point.set(
  18847. px.calc( weight ),
  18848. py.calc( weight ),
  18849. pz.calc( weight )
  18850. );
  18851. return point;
  18852. }
  18853. copy( source ) {
  18854. super.copy( source );
  18855. this.points = [];
  18856. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18857. const point = source.points[ i ];
  18858. this.points.push( point.clone() );
  18859. }
  18860. this.closed = source.closed;
  18861. this.curveType = source.curveType;
  18862. this.tension = source.tension;
  18863. return this;
  18864. }
  18865. toJSON() {
  18866. const data = super.toJSON();
  18867. data.points = [];
  18868. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18869. const point = this.points[ i ];
  18870. data.points.push( point.toArray() );
  18871. }
  18872. data.closed = this.closed;
  18873. data.curveType = this.curveType;
  18874. data.tension = this.tension;
  18875. return data;
  18876. }
  18877. fromJSON( json ) {
  18878. super.fromJSON( json );
  18879. this.points = [];
  18880. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18881. const point = json.points[ i ];
  18882. this.points.push( new Vector3().fromArray( point ) );
  18883. }
  18884. this.closed = json.closed;
  18885. this.curveType = json.curveType;
  18886. this.tension = json.tension;
  18887. return this;
  18888. }
  18889. }
  18890. /**
  18891. * Bezier Curves formulas obtained from
  18892. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18893. */
  18894. function CatmullRom( t, p0, p1, p2, p3 ) {
  18895. const v0 = ( p2 - p0 ) * 0.5;
  18896. const v1 = ( p3 - p1 ) * 0.5;
  18897. const t2 = t * t;
  18898. const t3 = t * t2;
  18899. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18900. }
  18901. //
  18902. function QuadraticBezierP0( t, p ) {
  18903. const k = 1 - t;
  18904. return k * k * p;
  18905. }
  18906. function QuadraticBezierP1( t, p ) {
  18907. return 2 * ( 1 - t ) * t * p;
  18908. }
  18909. function QuadraticBezierP2( t, p ) {
  18910. return t * t * p;
  18911. }
  18912. function QuadraticBezier( t, p0, p1, p2 ) {
  18913. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18914. QuadraticBezierP2( t, p2 );
  18915. }
  18916. //
  18917. function CubicBezierP0( t, p ) {
  18918. const k = 1 - t;
  18919. return k * k * k * p;
  18920. }
  18921. function CubicBezierP1( t, p ) {
  18922. const k = 1 - t;
  18923. return 3 * k * k * t * p;
  18924. }
  18925. function CubicBezierP2( t, p ) {
  18926. return 3 * ( 1 - t ) * t * t * p;
  18927. }
  18928. function CubicBezierP3( t, p ) {
  18929. return t * t * t * p;
  18930. }
  18931. function CubicBezier( t, p0, p1, p2, p3 ) {
  18932. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18933. CubicBezierP3( t, p3 );
  18934. }
  18935. class CubicBezierCurve extends Curve {
  18936. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18937. super();
  18938. this.isCubicBezierCurve = true;
  18939. this.type = 'CubicBezierCurve';
  18940. this.v0 = v0;
  18941. this.v1 = v1;
  18942. this.v2 = v2;
  18943. this.v3 = v3;
  18944. }
  18945. getPoint( t, optionalTarget = new Vector2() ) {
  18946. const point = optionalTarget;
  18947. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18948. point.set(
  18949. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18950. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18951. );
  18952. return point;
  18953. }
  18954. copy( source ) {
  18955. super.copy( source );
  18956. this.v0.copy( source.v0 );
  18957. this.v1.copy( source.v1 );
  18958. this.v2.copy( source.v2 );
  18959. this.v3.copy( source.v3 );
  18960. return this;
  18961. }
  18962. toJSON() {
  18963. const data = super.toJSON();
  18964. data.v0 = this.v0.toArray();
  18965. data.v1 = this.v1.toArray();
  18966. data.v2 = this.v2.toArray();
  18967. data.v3 = this.v3.toArray();
  18968. return data;
  18969. }
  18970. fromJSON( json ) {
  18971. super.fromJSON( json );
  18972. this.v0.fromArray( json.v0 );
  18973. this.v1.fromArray( json.v1 );
  18974. this.v2.fromArray( json.v2 );
  18975. this.v3.fromArray( json.v3 );
  18976. return this;
  18977. }
  18978. }
  18979. class CubicBezierCurve3 extends Curve {
  18980. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18981. super();
  18982. this.isCubicBezierCurve3 = true;
  18983. this.type = 'CubicBezierCurve3';
  18984. this.v0 = v0;
  18985. this.v1 = v1;
  18986. this.v2 = v2;
  18987. this.v3 = v3;
  18988. }
  18989. getPoint( t, optionalTarget = new Vector3() ) {
  18990. const point = optionalTarget;
  18991. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18992. point.set(
  18993. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18994. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18995. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18996. );
  18997. return point;
  18998. }
  18999. copy( source ) {
  19000. super.copy( source );
  19001. this.v0.copy( source.v0 );
  19002. this.v1.copy( source.v1 );
  19003. this.v2.copy( source.v2 );
  19004. this.v3.copy( source.v3 );
  19005. return this;
  19006. }
  19007. toJSON() {
  19008. const data = super.toJSON();
  19009. data.v0 = this.v0.toArray();
  19010. data.v1 = this.v1.toArray();
  19011. data.v2 = this.v2.toArray();
  19012. data.v3 = this.v3.toArray();
  19013. return data;
  19014. }
  19015. fromJSON( json ) {
  19016. super.fromJSON( json );
  19017. this.v0.fromArray( json.v0 );
  19018. this.v1.fromArray( json.v1 );
  19019. this.v2.fromArray( json.v2 );
  19020. this.v3.fromArray( json.v3 );
  19021. return this;
  19022. }
  19023. }
  19024. class LineCurve extends Curve {
  19025. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19026. super();
  19027. this.isLineCurve = true;
  19028. this.type = 'LineCurve';
  19029. this.v1 = v1;
  19030. this.v2 = v2;
  19031. }
  19032. getPoint( t, optionalTarget = new Vector2() ) {
  19033. const point = optionalTarget;
  19034. if ( t === 1 ) {
  19035. point.copy( this.v2 );
  19036. } else {
  19037. point.copy( this.v2 ).sub( this.v1 );
  19038. point.multiplyScalar( t ).add( this.v1 );
  19039. }
  19040. return point;
  19041. }
  19042. // Line curve is linear, so we can overwrite default getPointAt
  19043. getPointAt( u, optionalTarget ) {
  19044. return this.getPoint( u, optionalTarget );
  19045. }
  19046. getTangent( t, optionalTarget ) {
  19047. const tangent = optionalTarget || new Vector2();
  19048. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19049. return tangent;
  19050. }
  19051. copy( source ) {
  19052. super.copy( source );
  19053. this.v1.copy( source.v1 );
  19054. this.v2.copy( source.v2 );
  19055. return this;
  19056. }
  19057. toJSON() {
  19058. const data = super.toJSON();
  19059. data.v1 = this.v1.toArray();
  19060. data.v2 = this.v2.toArray();
  19061. return data;
  19062. }
  19063. fromJSON( json ) {
  19064. super.fromJSON( json );
  19065. this.v1.fromArray( json.v1 );
  19066. this.v2.fromArray( json.v2 );
  19067. return this;
  19068. }
  19069. }
  19070. class LineCurve3 extends Curve {
  19071. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19072. super();
  19073. this.isLineCurve3 = true;
  19074. this.type = 'LineCurve3';
  19075. this.v1 = v1;
  19076. this.v2 = v2;
  19077. }
  19078. getPoint( t, optionalTarget = new Vector3() ) {
  19079. const point = optionalTarget;
  19080. if ( t === 1 ) {
  19081. point.copy( this.v2 );
  19082. } else {
  19083. point.copy( this.v2 ).sub( this.v1 );
  19084. point.multiplyScalar( t ).add( this.v1 );
  19085. }
  19086. return point;
  19087. }
  19088. // Line curve is linear, so we can overwrite default getPointAt
  19089. getPointAt( u, optionalTarget ) {
  19090. return this.getPoint( u, optionalTarget );
  19091. }
  19092. copy( source ) {
  19093. super.copy( source );
  19094. this.v1.copy( source.v1 );
  19095. this.v2.copy( source.v2 );
  19096. return this;
  19097. }
  19098. toJSON() {
  19099. const data = super.toJSON();
  19100. data.v1 = this.v1.toArray();
  19101. data.v2 = this.v2.toArray();
  19102. return data;
  19103. }
  19104. fromJSON( json ) {
  19105. super.fromJSON( json );
  19106. this.v1.fromArray( json.v1 );
  19107. this.v2.fromArray( json.v2 );
  19108. return this;
  19109. }
  19110. }
  19111. class QuadraticBezierCurve extends Curve {
  19112. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19113. super();
  19114. this.isQuadraticBezierCurve = true;
  19115. this.type = 'QuadraticBezierCurve';
  19116. this.v0 = v0;
  19117. this.v1 = v1;
  19118. this.v2 = v2;
  19119. }
  19120. getPoint( t, optionalTarget = new Vector2() ) {
  19121. const point = optionalTarget;
  19122. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19123. point.set(
  19124. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19125. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19126. );
  19127. return point;
  19128. }
  19129. copy( source ) {
  19130. super.copy( source );
  19131. this.v0.copy( source.v0 );
  19132. this.v1.copy( source.v1 );
  19133. this.v2.copy( source.v2 );
  19134. return this;
  19135. }
  19136. toJSON() {
  19137. const data = super.toJSON();
  19138. data.v0 = this.v0.toArray();
  19139. data.v1 = this.v1.toArray();
  19140. data.v2 = this.v2.toArray();
  19141. return data;
  19142. }
  19143. fromJSON( json ) {
  19144. super.fromJSON( json );
  19145. this.v0.fromArray( json.v0 );
  19146. this.v1.fromArray( json.v1 );
  19147. this.v2.fromArray( json.v2 );
  19148. return this;
  19149. }
  19150. }
  19151. class QuadraticBezierCurve3 extends Curve {
  19152. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19153. super();
  19154. this.isQuadraticBezierCurve3 = true;
  19155. this.type = 'QuadraticBezierCurve3';
  19156. this.v0 = v0;
  19157. this.v1 = v1;
  19158. this.v2 = v2;
  19159. }
  19160. getPoint( t, optionalTarget = new Vector3() ) {
  19161. const point = optionalTarget;
  19162. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19163. point.set(
  19164. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19165. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19166. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19167. );
  19168. return point;
  19169. }
  19170. copy( source ) {
  19171. super.copy( source );
  19172. this.v0.copy( source.v0 );
  19173. this.v1.copy( source.v1 );
  19174. this.v2.copy( source.v2 );
  19175. return this;
  19176. }
  19177. toJSON() {
  19178. const data = super.toJSON();
  19179. data.v0 = this.v0.toArray();
  19180. data.v1 = this.v1.toArray();
  19181. data.v2 = this.v2.toArray();
  19182. return data;
  19183. }
  19184. fromJSON( json ) {
  19185. super.fromJSON( json );
  19186. this.v0.fromArray( json.v0 );
  19187. this.v1.fromArray( json.v1 );
  19188. this.v2.fromArray( json.v2 );
  19189. return this;
  19190. }
  19191. }
  19192. class SplineCurve extends Curve {
  19193. constructor( points = [] ) {
  19194. super();
  19195. this.isSplineCurve = true;
  19196. this.type = 'SplineCurve';
  19197. this.points = points;
  19198. }
  19199. getPoint( t, optionalTarget = new Vector2() ) {
  19200. const point = optionalTarget;
  19201. const points = this.points;
  19202. const p = ( points.length - 1 ) * t;
  19203. const intPoint = Math.floor( p );
  19204. const weight = p - intPoint;
  19205. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19206. const p1 = points[ intPoint ];
  19207. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19208. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19209. point.set(
  19210. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19211. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19212. );
  19213. return point;
  19214. }
  19215. copy( source ) {
  19216. super.copy( source );
  19217. this.points = [];
  19218. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19219. const point = source.points[ i ];
  19220. this.points.push( point.clone() );
  19221. }
  19222. return this;
  19223. }
  19224. toJSON() {
  19225. const data = super.toJSON();
  19226. data.points = [];
  19227. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19228. const point = this.points[ i ];
  19229. data.points.push( point.toArray() );
  19230. }
  19231. return data;
  19232. }
  19233. fromJSON( json ) {
  19234. super.fromJSON( json );
  19235. this.points = [];
  19236. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19237. const point = json.points[ i ];
  19238. this.points.push( new Vector2().fromArray( point ) );
  19239. }
  19240. return this;
  19241. }
  19242. }
  19243. var Curves = /*#__PURE__*/Object.freeze({
  19244. __proto__: null,
  19245. ArcCurve: ArcCurve,
  19246. CatmullRomCurve3: CatmullRomCurve3,
  19247. CubicBezierCurve: CubicBezierCurve,
  19248. CubicBezierCurve3: CubicBezierCurve3,
  19249. EllipseCurve: EllipseCurve,
  19250. LineCurve: LineCurve,
  19251. LineCurve3: LineCurve3,
  19252. QuadraticBezierCurve: QuadraticBezierCurve,
  19253. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19254. SplineCurve: SplineCurve
  19255. });
  19256. /**************************************************************
  19257. * Curved Path - a curve path is simply a array of connected
  19258. * curves, but retains the api of a curve
  19259. **************************************************************/
  19260. class CurvePath extends Curve {
  19261. constructor() {
  19262. super();
  19263. this.type = 'CurvePath';
  19264. this.curves = [];
  19265. this.autoClose = false; // Automatically closes the path
  19266. }
  19267. add( curve ) {
  19268. this.curves.push( curve );
  19269. }
  19270. closePath() {
  19271. // Add a line curve if start and end of lines are not connected
  19272. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19273. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19274. if ( ! startPoint.equals( endPoint ) ) {
  19275. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19276. }
  19277. }
  19278. // To get accurate point with reference to
  19279. // entire path distance at time t,
  19280. // following has to be done:
  19281. // 1. Length of each sub path have to be known
  19282. // 2. Locate and identify type of curve
  19283. // 3. Get t for the curve
  19284. // 4. Return curve.getPointAt(t')
  19285. getPoint( t, optionalTarget ) {
  19286. const d = t * this.getLength();
  19287. const curveLengths = this.getCurveLengths();
  19288. let i = 0;
  19289. // To think about boundaries points.
  19290. while ( i < curveLengths.length ) {
  19291. if ( curveLengths[ i ] >= d ) {
  19292. const diff = curveLengths[ i ] - d;
  19293. const curve = this.curves[ i ];
  19294. const segmentLength = curve.getLength();
  19295. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19296. return curve.getPointAt( u, optionalTarget );
  19297. }
  19298. i ++;
  19299. }
  19300. return null;
  19301. // loop where sum != 0, sum > d , sum+1 <d
  19302. }
  19303. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19304. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19305. // getPoint() depends on getLength
  19306. getLength() {
  19307. const lens = this.getCurveLengths();
  19308. return lens[ lens.length - 1 ];
  19309. }
  19310. // cacheLengths must be recalculated.
  19311. updateArcLengths() {
  19312. this.needsUpdate = true;
  19313. this.cacheLengths = null;
  19314. this.getCurveLengths();
  19315. }
  19316. // Compute lengths and cache them
  19317. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19318. getCurveLengths() {
  19319. // We use cache values if curves and cache array are same length
  19320. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19321. return this.cacheLengths;
  19322. }
  19323. // Get length of sub-curve
  19324. // Push sums into cached array
  19325. const lengths = [];
  19326. let sums = 0;
  19327. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19328. sums += this.curves[ i ].getLength();
  19329. lengths.push( sums );
  19330. }
  19331. this.cacheLengths = lengths;
  19332. return lengths;
  19333. }
  19334. getSpacedPoints( divisions = 40 ) {
  19335. const points = [];
  19336. for ( let i = 0; i <= divisions; i ++ ) {
  19337. points.push( this.getPoint( i / divisions ) );
  19338. }
  19339. if ( this.autoClose ) {
  19340. points.push( points[ 0 ] );
  19341. }
  19342. return points;
  19343. }
  19344. getPoints( divisions = 12 ) {
  19345. const points = [];
  19346. let last;
  19347. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19348. const curve = curves[ i ];
  19349. const resolution = curve.isEllipseCurve ? divisions * 2
  19350. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19351. : curve.isSplineCurve ? divisions * curve.points.length
  19352. : divisions;
  19353. const pts = curve.getPoints( resolution );
  19354. for ( let j = 0; j < pts.length; j ++ ) {
  19355. const point = pts[ j ];
  19356. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19357. points.push( point );
  19358. last = point;
  19359. }
  19360. }
  19361. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19362. points.push( points[ 0 ] );
  19363. }
  19364. return points;
  19365. }
  19366. copy( source ) {
  19367. super.copy( source );
  19368. this.curves = [];
  19369. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19370. const curve = source.curves[ i ];
  19371. this.curves.push( curve.clone() );
  19372. }
  19373. this.autoClose = source.autoClose;
  19374. return this;
  19375. }
  19376. toJSON() {
  19377. const data = super.toJSON();
  19378. data.autoClose = this.autoClose;
  19379. data.curves = [];
  19380. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19381. const curve = this.curves[ i ];
  19382. data.curves.push( curve.toJSON() );
  19383. }
  19384. return data;
  19385. }
  19386. fromJSON( json ) {
  19387. super.fromJSON( json );
  19388. this.autoClose = json.autoClose;
  19389. this.curves = [];
  19390. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19391. const curve = json.curves[ i ];
  19392. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19393. }
  19394. return this;
  19395. }
  19396. }
  19397. class Path extends CurvePath {
  19398. constructor( points ) {
  19399. super();
  19400. this.type = 'Path';
  19401. this.currentPoint = new Vector2();
  19402. if ( points ) {
  19403. this.setFromPoints( points );
  19404. }
  19405. }
  19406. setFromPoints( points ) {
  19407. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19408. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19409. this.lineTo( points[ i ].x, points[ i ].y );
  19410. }
  19411. return this;
  19412. }
  19413. moveTo( x, y ) {
  19414. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19415. return this;
  19416. }
  19417. lineTo( x, y ) {
  19418. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19419. this.curves.push( curve );
  19420. this.currentPoint.set( x, y );
  19421. return this;
  19422. }
  19423. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19424. const curve = new QuadraticBezierCurve(
  19425. this.currentPoint.clone(),
  19426. new Vector2( aCPx, aCPy ),
  19427. new Vector2( aX, aY )
  19428. );
  19429. this.curves.push( curve );
  19430. this.currentPoint.set( aX, aY );
  19431. return this;
  19432. }
  19433. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19434. const curve = new CubicBezierCurve(
  19435. this.currentPoint.clone(),
  19436. new Vector2( aCP1x, aCP1y ),
  19437. new Vector2( aCP2x, aCP2y ),
  19438. new Vector2( aX, aY )
  19439. );
  19440. this.curves.push( curve );
  19441. this.currentPoint.set( aX, aY );
  19442. return this;
  19443. }
  19444. splineThru( pts /*Array of Vector*/ ) {
  19445. const npts = [ this.currentPoint.clone() ].concat( pts );
  19446. const curve = new SplineCurve( npts );
  19447. this.curves.push( curve );
  19448. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19449. return this;
  19450. }
  19451. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19452. const x0 = this.currentPoint.x;
  19453. const y0 = this.currentPoint.y;
  19454. this.absarc( aX + x0, aY + y0, aRadius,
  19455. aStartAngle, aEndAngle, aClockwise );
  19456. return this;
  19457. }
  19458. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19459. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19460. return this;
  19461. }
  19462. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19463. const x0 = this.currentPoint.x;
  19464. const y0 = this.currentPoint.y;
  19465. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19466. return this;
  19467. }
  19468. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19469. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19470. if ( this.curves.length > 0 ) {
  19471. // if a previous curve is present, attempt to join
  19472. const firstPoint = curve.getPoint( 0 );
  19473. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19474. this.lineTo( firstPoint.x, firstPoint.y );
  19475. }
  19476. }
  19477. this.curves.push( curve );
  19478. const lastPoint = curve.getPoint( 1 );
  19479. this.currentPoint.copy( lastPoint );
  19480. return this;
  19481. }
  19482. copy( source ) {
  19483. super.copy( source );
  19484. this.currentPoint.copy( source.currentPoint );
  19485. return this;
  19486. }
  19487. toJSON() {
  19488. const data = super.toJSON();
  19489. data.currentPoint = this.currentPoint.toArray();
  19490. return data;
  19491. }
  19492. fromJSON( json ) {
  19493. super.fromJSON( json );
  19494. this.currentPoint.fromArray( json.currentPoint );
  19495. return this;
  19496. }
  19497. }
  19498. class LatheGeometry extends BufferGeometry {
  19499. 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 ) {
  19500. super();
  19501. this.type = 'LatheGeometry';
  19502. this.parameters = {
  19503. points: points,
  19504. segments: segments,
  19505. phiStart: phiStart,
  19506. phiLength: phiLength
  19507. };
  19508. segments = Math.floor( segments );
  19509. // clamp phiLength so it's in range of [ 0, 2PI ]
  19510. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19511. // buffers
  19512. const indices = [];
  19513. const vertices = [];
  19514. const uvs = [];
  19515. const initNormals = [];
  19516. const normals = [];
  19517. // helper variables
  19518. const inverseSegments = 1.0 / segments;
  19519. const vertex = new Vector3();
  19520. const uv = new Vector2();
  19521. const normal = new Vector3();
  19522. const curNormal = new Vector3();
  19523. const prevNormal = new Vector3();
  19524. let dx = 0;
  19525. let dy = 0;
  19526. // pre-compute normals for initial "meridian"
  19527. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19528. switch ( j ) {
  19529. case 0: // special handling for 1st vertex on path
  19530. dx = points[ j + 1 ].x - points[ j ].x;
  19531. dy = points[ j + 1 ].y - points[ j ].y;
  19532. normal.x = dy * 1.0;
  19533. normal.y = - dx;
  19534. normal.z = dy * 0.0;
  19535. prevNormal.copy( normal );
  19536. normal.normalize();
  19537. initNormals.push( normal.x, normal.y, normal.z );
  19538. break;
  19539. case ( points.length - 1 ): // special handling for last Vertex on path
  19540. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19541. break;
  19542. default: // default handling for all vertices in between
  19543. dx = points[ j + 1 ].x - points[ j ].x;
  19544. dy = points[ j + 1 ].y - points[ j ].y;
  19545. normal.x = dy * 1.0;
  19546. normal.y = - dx;
  19547. normal.z = dy * 0.0;
  19548. curNormal.copy( normal );
  19549. normal.x += prevNormal.x;
  19550. normal.y += prevNormal.y;
  19551. normal.z += prevNormal.z;
  19552. normal.normalize();
  19553. initNormals.push( normal.x, normal.y, normal.z );
  19554. prevNormal.copy( curNormal );
  19555. }
  19556. }
  19557. // generate vertices, uvs and normals
  19558. for ( let i = 0; i <= segments; i ++ ) {
  19559. const phi = phiStart + i * inverseSegments * phiLength;
  19560. const sin = Math.sin( phi );
  19561. const cos = Math.cos( phi );
  19562. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19563. // vertex
  19564. vertex.x = points[ j ].x * sin;
  19565. vertex.y = points[ j ].y;
  19566. vertex.z = points[ j ].x * cos;
  19567. vertices.push( vertex.x, vertex.y, vertex.z );
  19568. // uv
  19569. uv.x = i / segments;
  19570. uv.y = j / ( points.length - 1 );
  19571. uvs.push( uv.x, uv.y );
  19572. // normal
  19573. const x = initNormals[ 3 * j + 0 ] * sin;
  19574. const y = initNormals[ 3 * j + 1 ];
  19575. const z = initNormals[ 3 * j + 0 ] * cos;
  19576. normals.push( x, y, z );
  19577. }
  19578. }
  19579. // indices
  19580. for ( let i = 0; i < segments; i ++ ) {
  19581. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19582. const base = j + i * points.length;
  19583. const a = base;
  19584. const b = base + points.length;
  19585. const c = base + points.length + 1;
  19586. const d = base + 1;
  19587. // faces
  19588. indices.push( a, b, d );
  19589. indices.push( c, d, b );
  19590. }
  19591. }
  19592. // build geometry
  19593. this.setIndex( indices );
  19594. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19595. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19596. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19597. }
  19598. static fromJSON( data ) {
  19599. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19600. }
  19601. }
  19602. class CapsuleGeometry extends LatheGeometry {
  19603. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19604. const path = new Path();
  19605. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19606. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19607. super( path.getPoints( capSegments ), radialSegments );
  19608. this.type = 'CapsuleGeometry';
  19609. this.parameters = {
  19610. radius: radius,
  19611. height: length,
  19612. capSegments: capSegments,
  19613. radialSegments: radialSegments,
  19614. };
  19615. }
  19616. static fromJSON( data ) {
  19617. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19618. }
  19619. }
  19620. class CircleGeometry extends BufferGeometry {
  19621. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19622. super();
  19623. this.type = 'CircleGeometry';
  19624. this.parameters = {
  19625. radius: radius,
  19626. segments: segments,
  19627. thetaStart: thetaStart,
  19628. thetaLength: thetaLength
  19629. };
  19630. segments = Math.max( 3, segments );
  19631. // buffers
  19632. const indices = [];
  19633. const vertices = [];
  19634. const normals = [];
  19635. const uvs = [];
  19636. // helper variables
  19637. const vertex = new Vector3();
  19638. const uv = new Vector2();
  19639. // center point
  19640. vertices.push( 0, 0, 0 );
  19641. normals.push( 0, 0, 1 );
  19642. uvs.push( 0.5, 0.5 );
  19643. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19644. const segment = thetaStart + s / segments * thetaLength;
  19645. // vertex
  19646. vertex.x = radius * Math.cos( segment );
  19647. vertex.y = radius * Math.sin( segment );
  19648. vertices.push( vertex.x, vertex.y, vertex.z );
  19649. // normal
  19650. normals.push( 0, 0, 1 );
  19651. // uvs
  19652. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19653. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19654. uvs.push( uv.x, uv.y );
  19655. }
  19656. // indices
  19657. for ( let i = 1; i <= segments; i ++ ) {
  19658. indices.push( i, i + 1, 0 );
  19659. }
  19660. // build geometry
  19661. this.setIndex( indices );
  19662. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19663. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19664. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19665. }
  19666. static fromJSON( data ) {
  19667. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19668. }
  19669. }
  19670. class CylinderGeometry extends BufferGeometry {
  19671. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19672. super();
  19673. this.type = 'CylinderGeometry';
  19674. this.parameters = {
  19675. radiusTop: radiusTop,
  19676. radiusBottom: radiusBottom,
  19677. height: height,
  19678. radialSegments: radialSegments,
  19679. heightSegments: heightSegments,
  19680. openEnded: openEnded,
  19681. thetaStart: thetaStart,
  19682. thetaLength: thetaLength
  19683. };
  19684. const scope = this;
  19685. radialSegments = Math.floor( radialSegments );
  19686. heightSegments = Math.floor( heightSegments );
  19687. // buffers
  19688. const indices = [];
  19689. const vertices = [];
  19690. const normals = [];
  19691. const uvs = [];
  19692. // helper variables
  19693. let index = 0;
  19694. const indexArray = [];
  19695. const halfHeight = height / 2;
  19696. let groupStart = 0;
  19697. // generate geometry
  19698. generateTorso();
  19699. if ( openEnded === false ) {
  19700. if ( radiusTop > 0 ) generateCap( true );
  19701. if ( radiusBottom > 0 ) generateCap( false );
  19702. }
  19703. // build geometry
  19704. this.setIndex( indices );
  19705. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19706. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19707. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19708. function generateTorso() {
  19709. const normal = new Vector3();
  19710. const vertex = new Vector3();
  19711. let groupCount = 0;
  19712. // this will be used to calculate the normal
  19713. const slope = ( radiusBottom - radiusTop ) / height;
  19714. // generate vertices, normals and uvs
  19715. for ( let y = 0; y <= heightSegments; y ++ ) {
  19716. const indexRow = [];
  19717. const v = y / heightSegments;
  19718. // calculate the radius of the current row
  19719. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19720. for ( let x = 0; x <= radialSegments; x ++ ) {
  19721. const u = x / radialSegments;
  19722. const theta = u * thetaLength + thetaStart;
  19723. const sinTheta = Math.sin( theta );
  19724. const cosTheta = Math.cos( theta );
  19725. // vertex
  19726. vertex.x = radius * sinTheta;
  19727. vertex.y = - v * height + halfHeight;
  19728. vertex.z = radius * cosTheta;
  19729. vertices.push( vertex.x, vertex.y, vertex.z );
  19730. // normal
  19731. normal.set( sinTheta, slope, cosTheta ).normalize();
  19732. normals.push( normal.x, normal.y, normal.z );
  19733. // uv
  19734. uvs.push( u, 1 - v );
  19735. // save index of vertex in respective row
  19736. indexRow.push( index ++ );
  19737. }
  19738. // now save vertices of the row in our index array
  19739. indexArray.push( indexRow );
  19740. }
  19741. // generate indices
  19742. for ( let x = 0; x < radialSegments; x ++ ) {
  19743. for ( let y = 0; y < heightSegments; y ++ ) {
  19744. // we use the index array to access the correct indices
  19745. const a = indexArray[ y ][ x ];
  19746. const b = indexArray[ y + 1 ][ x ];
  19747. const c = indexArray[ y + 1 ][ x + 1 ];
  19748. const d = indexArray[ y ][ x + 1 ];
  19749. // faces
  19750. indices.push( a, b, d );
  19751. indices.push( b, c, d );
  19752. // update group counter
  19753. groupCount += 6;
  19754. }
  19755. }
  19756. // add a group to the geometry. this will ensure multi material support
  19757. scope.addGroup( groupStart, groupCount, 0 );
  19758. // calculate new start value for groups
  19759. groupStart += groupCount;
  19760. }
  19761. function generateCap( top ) {
  19762. // save the index of the first center vertex
  19763. const centerIndexStart = index;
  19764. const uv = new Vector2();
  19765. const vertex = new Vector3();
  19766. let groupCount = 0;
  19767. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19768. const sign = ( top === true ) ? 1 : - 1;
  19769. // first we generate the center vertex data of the cap.
  19770. // because the geometry needs one set of uvs per face,
  19771. // we must generate a center vertex per face/segment
  19772. for ( let x = 1; x <= radialSegments; x ++ ) {
  19773. // vertex
  19774. vertices.push( 0, halfHeight * sign, 0 );
  19775. // normal
  19776. normals.push( 0, sign, 0 );
  19777. // uv
  19778. uvs.push( 0.5, 0.5 );
  19779. // increase index
  19780. index ++;
  19781. }
  19782. // save the index of the last center vertex
  19783. const centerIndexEnd = index;
  19784. // now we generate the surrounding vertices, normals and uvs
  19785. for ( let x = 0; x <= radialSegments; x ++ ) {
  19786. const u = x / radialSegments;
  19787. const theta = u * thetaLength + thetaStart;
  19788. const cosTheta = Math.cos( theta );
  19789. const sinTheta = Math.sin( theta );
  19790. // vertex
  19791. vertex.x = radius * sinTheta;
  19792. vertex.y = halfHeight * sign;
  19793. vertex.z = radius * cosTheta;
  19794. vertices.push( vertex.x, vertex.y, vertex.z );
  19795. // normal
  19796. normals.push( 0, sign, 0 );
  19797. // uv
  19798. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19799. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19800. uvs.push( uv.x, uv.y );
  19801. // increase index
  19802. index ++;
  19803. }
  19804. // generate indices
  19805. for ( let x = 0; x < radialSegments; x ++ ) {
  19806. const c = centerIndexStart + x;
  19807. const i = centerIndexEnd + x;
  19808. if ( top === true ) {
  19809. // face top
  19810. indices.push( i, i + 1, c );
  19811. } else {
  19812. // face bottom
  19813. indices.push( i + 1, i, c );
  19814. }
  19815. groupCount += 3;
  19816. }
  19817. // add a group to the geometry. this will ensure multi material support
  19818. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19819. // calculate new start value for groups
  19820. groupStart += groupCount;
  19821. }
  19822. }
  19823. static fromJSON( data ) {
  19824. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19825. }
  19826. }
  19827. class ConeGeometry extends CylinderGeometry {
  19828. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19829. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19830. this.type = 'ConeGeometry';
  19831. this.parameters = {
  19832. radius: radius,
  19833. height: height,
  19834. radialSegments: radialSegments,
  19835. heightSegments: heightSegments,
  19836. openEnded: openEnded,
  19837. thetaStart: thetaStart,
  19838. thetaLength: thetaLength
  19839. };
  19840. }
  19841. static fromJSON( data ) {
  19842. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19843. }
  19844. }
  19845. class PolyhedronGeometry extends BufferGeometry {
  19846. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  19847. super();
  19848. this.type = 'PolyhedronGeometry';
  19849. this.parameters = {
  19850. vertices: vertices,
  19851. indices: indices,
  19852. radius: radius,
  19853. detail: detail
  19854. };
  19855. // default buffer data
  19856. const vertexBuffer = [];
  19857. const uvBuffer = [];
  19858. // the subdivision creates the vertex buffer data
  19859. subdivide( detail );
  19860. // all vertices should lie on a conceptual sphere with a given radius
  19861. applyRadius( radius );
  19862. // finally, create the uv data
  19863. generateUVs();
  19864. // build non-indexed geometry
  19865. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19866. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19867. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19868. if ( detail === 0 ) {
  19869. this.computeVertexNormals(); // flat normals
  19870. } else {
  19871. this.normalizeNormals(); // smooth normals
  19872. }
  19873. // helper functions
  19874. function subdivide( detail ) {
  19875. const a = new Vector3();
  19876. const b = new Vector3();
  19877. const c = new Vector3();
  19878. // iterate over all faces and apply a subdivison with the given detail value
  19879. for ( let i = 0; i < indices.length; i += 3 ) {
  19880. // get the vertices of the face
  19881. getVertexByIndex( indices[ i + 0 ], a );
  19882. getVertexByIndex( indices[ i + 1 ], b );
  19883. getVertexByIndex( indices[ i + 2 ], c );
  19884. // perform subdivision
  19885. subdivideFace( a, b, c, detail );
  19886. }
  19887. }
  19888. function subdivideFace( a, b, c, detail ) {
  19889. const cols = detail + 1;
  19890. // we use this multidimensional array as a data structure for creating the subdivision
  19891. const v = [];
  19892. // construct all of the vertices for this subdivision
  19893. for ( let i = 0; i <= cols; i ++ ) {
  19894. v[ i ] = [];
  19895. const aj = a.clone().lerp( c, i / cols );
  19896. const bj = b.clone().lerp( c, i / cols );
  19897. const rows = cols - i;
  19898. for ( let j = 0; j <= rows; j ++ ) {
  19899. if ( j === 0 && i === cols ) {
  19900. v[ i ][ j ] = aj;
  19901. } else {
  19902. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19903. }
  19904. }
  19905. }
  19906. // construct all of the faces
  19907. for ( let i = 0; i < cols; i ++ ) {
  19908. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19909. const k = Math.floor( j / 2 );
  19910. if ( j % 2 === 0 ) {
  19911. pushVertex( v[ i ][ k + 1 ] );
  19912. pushVertex( v[ i + 1 ][ k ] );
  19913. pushVertex( v[ i ][ k ] );
  19914. } else {
  19915. pushVertex( v[ i ][ k + 1 ] );
  19916. pushVertex( v[ i + 1 ][ k + 1 ] );
  19917. pushVertex( v[ i + 1 ][ k ] );
  19918. }
  19919. }
  19920. }
  19921. }
  19922. function applyRadius( radius ) {
  19923. const vertex = new Vector3();
  19924. // iterate over the entire buffer and apply the radius to each vertex
  19925. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19926. vertex.x = vertexBuffer[ i + 0 ];
  19927. vertex.y = vertexBuffer[ i + 1 ];
  19928. vertex.z = vertexBuffer[ i + 2 ];
  19929. vertex.normalize().multiplyScalar( radius );
  19930. vertexBuffer[ i + 0 ] = vertex.x;
  19931. vertexBuffer[ i + 1 ] = vertex.y;
  19932. vertexBuffer[ i + 2 ] = vertex.z;
  19933. }
  19934. }
  19935. function generateUVs() {
  19936. const vertex = new Vector3();
  19937. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19938. vertex.x = vertexBuffer[ i + 0 ];
  19939. vertex.y = vertexBuffer[ i + 1 ];
  19940. vertex.z = vertexBuffer[ i + 2 ];
  19941. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19942. const v = inclination( vertex ) / Math.PI + 0.5;
  19943. uvBuffer.push( u, 1 - v );
  19944. }
  19945. correctUVs();
  19946. correctSeam();
  19947. }
  19948. function correctSeam() {
  19949. // handle case when face straddles the seam, see #3269
  19950. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  19951. // uv data of a single face
  19952. const x0 = uvBuffer[ i + 0 ];
  19953. const x1 = uvBuffer[ i + 2 ];
  19954. const x2 = uvBuffer[ i + 4 ];
  19955. const max = Math.max( x0, x1, x2 );
  19956. const min = Math.min( x0, x1, x2 );
  19957. // 0.9 is somewhat arbitrary
  19958. if ( max > 0.9 && min < 0.1 ) {
  19959. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19960. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19961. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19962. }
  19963. }
  19964. }
  19965. function pushVertex( vertex ) {
  19966. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19967. }
  19968. function getVertexByIndex( index, vertex ) {
  19969. const stride = index * 3;
  19970. vertex.x = vertices[ stride + 0 ];
  19971. vertex.y = vertices[ stride + 1 ];
  19972. vertex.z = vertices[ stride + 2 ];
  19973. }
  19974. function correctUVs() {
  19975. const a = new Vector3();
  19976. const b = new Vector3();
  19977. const c = new Vector3();
  19978. const centroid = new Vector3();
  19979. const uvA = new Vector2();
  19980. const uvB = new Vector2();
  19981. const uvC = new Vector2();
  19982. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19983. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19984. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19985. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19986. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19987. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19988. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19989. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19990. const azi = azimuth( centroid );
  19991. correctUV( uvA, j + 0, a, azi );
  19992. correctUV( uvB, j + 2, b, azi );
  19993. correctUV( uvC, j + 4, c, azi );
  19994. }
  19995. }
  19996. function correctUV( uv, stride, vector, azimuth ) {
  19997. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19998. uvBuffer[ stride ] = uv.x - 1;
  19999. }
  20000. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20001. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20002. }
  20003. }
  20004. // Angle around the Y axis, counter-clockwise when looking from above.
  20005. function azimuth( vector ) {
  20006. return Math.atan2( vector.z, - vector.x );
  20007. }
  20008. // Angle above the XZ plane.
  20009. function inclination( vector ) {
  20010. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20011. }
  20012. }
  20013. static fromJSON( data ) {
  20014. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20015. }
  20016. }
  20017. class DodecahedronGeometry extends PolyhedronGeometry {
  20018. constructor( radius = 1, detail = 0 ) {
  20019. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20020. const r = 1 / t;
  20021. const vertices = [
  20022. // (±1, ±1, ±1)
  20023. - 1, - 1, - 1, - 1, - 1, 1,
  20024. - 1, 1, - 1, - 1, 1, 1,
  20025. 1, - 1, - 1, 1, - 1, 1,
  20026. 1, 1, - 1, 1, 1, 1,
  20027. // (0, ±1/φ, ±φ)
  20028. 0, - r, - t, 0, - r, t,
  20029. 0, r, - t, 0, r, t,
  20030. // (±1/φ, ±φ, 0)
  20031. - r, - t, 0, - r, t, 0,
  20032. r, - t, 0, r, t, 0,
  20033. // (±φ, 0, ±1/φ)
  20034. - t, 0, - r, t, 0, - r,
  20035. - t, 0, r, t, 0, r
  20036. ];
  20037. const indices = [
  20038. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20039. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20040. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20041. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20042. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20043. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20044. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20045. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20046. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20047. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20048. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20049. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20050. ];
  20051. super( vertices, indices, radius, detail );
  20052. this.type = 'DodecahedronGeometry';
  20053. this.parameters = {
  20054. radius: radius,
  20055. detail: detail
  20056. };
  20057. }
  20058. static fromJSON( data ) {
  20059. return new DodecahedronGeometry( data.radius, data.detail );
  20060. }
  20061. }
  20062. const _v0 = /*@__PURE__*/ new Vector3();
  20063. const _v1$1 = /*@__PURE__*/ new Vector3();
  20064. const _normal = /*@__PURE__*/ new Vector3();
  20065. const _triangle = /*@__PURE__*/ new Triangle();
  20066. class EdgesGeometry extends BufferGeometry {
  20067. constructor( geometry = null, thresholdAngle = 1 ) {
  20068. super();
  20069. this.type = 'EdgesGeometry';
  20070. this.parameters = {
  20071. geometry: geometry,
  20072. thresholdAngle: thresholdAngle
  20073. };
  20074. if ( geometry !== null ) {
  20075. const precisionPoints = 4;
  20076. const precision = Math.pow( 10, precisionPoints );
  20077. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20078. const indexAttr = geometry.getIndex();
  20079. const positionAttr = geometry.getAttribute( 'position' );
  20080. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20081. const indexArr = [ 0, 0, 0 ];
  20082. const vertKeys = [ 'a', 'b', 'c' ];
  20083. const hashes = new Array( 3 );
  20084. const edgeData = {};
  20085. const vertices = [];
  20086. for ( let i = 0; i < indexCount; i += 3 ) {
  20087. if ( indexAttr ) {
  20088. indexArr[ 0 ] = indexAttr.getX( i );
  20089. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20090. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20091. } else {
  20092. indexArr[ 0 ] = i;
  20093. indexArr[ 1 ] = i + 1;
  20094. indexArr[ 2 ] = i + 2;
  20095. }
  20096. const { a, b, c } = _triangle;
  20097. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20098. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20099. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20100. _triangle.getNormal( _normal );
  20101. // create hashes for the edge from the vertices
  20102. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20103. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20104. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20105. // skip degenerate triangles
  20106. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20107. continue;
  20108. }
  20109. // iterate over every edge
  20110. for ( let j = 0; j < 3; j ++ ) {
  20111. // get the first and next vertex making up the edge
  20112. const jNext = ( j + 1 ) % 3;
  20113. const vecHash0 = hashes[ j ];
  20114. const vecHash1 = hashes[ jNext ];
  20115. const v0 = _triangle[ vertKeys[ j ] ];
  20116. const v1 = _triangle[ vertKeys[ jNext ] ];
  20117. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20118. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20119. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20120. // if we found a sibling edge add it into the vertex array if
  20121. // it meets the angle threshold and delete the edge from the map.
  20122. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20123. vertices.push( v0.x, v0.y, v0.z );
  20124. vertices.push( v1.x, v1.y, v1.z );
  20125. }
  20126. edgeData[ reverseHash ] = null;
  20127. } else if ( ! ( hash in edgeData ) ) {
  20128. // if we've already got an edge here then skip adding a new one
  20129. edgeData[ hash ] = {
  20130. index0: indexArr[ j ],
  20131. index1: indexArr[ jNext ],
  20132. normal: _normal.clone(),
  20133. };
  20134. }
  20135. }
  20136. }
  20137. // iterate over all remaining, unmatched edges and add them to the vertex array
  20138. for ( const key in edgeData ) {
  20139. if ( edgeData[ key ] ) {
  20140. const { index0, index1 } = edgeData[ key ];
  20141. _v0.fromBufferAttribute( positionAttr, index0 );
  20142. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20143. vertices.push( _v0.x, _v0.y, _v0.z );
  20144. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20145. }
  20146. }
  20147. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20148. }
  20149. }
  20150. }
  20151. class Shape extends Path {
  20152. constructor( points ) {
  20153. super( points );
  20154. this.uuid = generateUUID();
  20155. this.type = 'Shape';
  20156. this.holes = [];
  20157. }
  20158. getPointsHoles( divisions ) {
  20159. const holesPts = [];
  20160. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20161. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20162. }
  20163. return holesPts;
  20164. }
  20165. // get points of shape and holes (keypoints based on segments parameter)
  20166. extractPoints( divisions ) {
  20167. return {
  20168. shape: this.getPoints( divisions ),
  20169. holes: this.getPointsHoles( divisions )
  20170. };
  20171. }
  20172. copy( source ) {
  20173. super.copy( source );
  20174. this.holes = [];
  20175. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20176. const hole = source.holes[ i ];
  20177. this.holes.push( hole.clone() );
  20178. }
  20179. return this;
  20180. }
  20181. toJSON() {
  20182. const data = super.toJSON();
  20183. data.uuid = this.uuid;
  20184. data.holes = [];
  20185. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20186. const hole = this.holes[ i ];
  20187. data.holes.push( hole.toJSON() );
  20188. }
  20189. return data;
  20190. }
  20191. fromJSON( json ) {
  20192. super.fromJSON( json );
  20193. this.uuid = json.uuid;
  20194. this.holes = [];
  20195. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20196. const hole = json.holes[ i ];
  20197. this.holes.push( new Path().fromJSON( hole ) );
  20198. }
  20199. return this;
  20200. }
  20201. }
  20202. /**
  20203. * Port from https://github.com/mapbox/earcut (v2.2.2)
  20204. */
  20205. const Earcut = {
  20206. triangulate: function ( data, holeIndices, dim = 2 ) {
  20207. const hasHoles = holeIndices && holeIndices.length;
  20208. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20209. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20210. const triangles = [];
  20211. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20212. let minX, minY, maxX, maxY, x, y, invSize;
  20213. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20214. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20215. if ( data.length > 80 * dim ) {
  20216. minX = maxX = data[ 0 ];
  20217. minY = maxY = data[ 1 ];
  20218. for ( let i = dim; i < outerLen; i += dim ) {
  20219. x = data[ i ];
  20220. y = data[ i + 1 ];
  20221. if ( x < minX ) minX = x;
  20222. if ( y < minY ) minY = y;
  20223. if ( x > maxX ) maxX = x;
  20224. if ( y > maxY ) maxY = y;
  20225. }
  20226. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20227. invSize = Math.max( maxX - minX, maxY - minY );
  20228. invSize = invSize !== 0 ? 1 / invSize : 0;
  20229. }
  20230. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20231. return triangles;
  20232. }
  20233. };
  20234. // create a circular doubly linked list from polygon points in the specified winding order
  20235. function linkedList( data, start, end, dim, clockwise ) {
  20236. let i, last;
  20237. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20238. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20239. } else {
  20240. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20241. }
  20242. if ( last && equals( last, last.next ) ) {
  20243. removeNode( last );
  20244. last = last.next;
  20245. }
  20246. return last;
  20247. }
  20248. // eliminate colinear or duplicate points
  20249. function filterPoints( start, end ) {
  20250. if ( ! start ) return start;
  20251. if ( ! end ) end = start;
  20252. let p = start,
  20253. again;
  20254. do {
  20255. again = false;
  20256. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20257. removeNode( p );
  20258. p = end = p.prev;
  20259. if ( p === p.next ) break;
  20260. again = true;
  20261. } else {
  20262. p = p.next;
  20263. }
  20264. } while ( again || p !== end );
  20265. return end;
  20266. }
  20267. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20268. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20269. if ( ! ear ) return;
  20270. // interlink polygon nodes in z-order
  20271. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20272. let stop = ear,
  20273. prev, next;
  20274. // iterate through ears, slicing them one by one
  20275. while ( ear.prev !== ear.next ) {
  20276. prev = ear.prev;
  20277. next = ear.next;
  20278. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20279. // cut off the triangle
  20280. triangles.push( prev.i / dim );
  20281. triangles.push( ear.i / dim );
  20282. triangles.push( next.i / dim );
  20283. removeNode( ear );
  20284. // skipping the next vertex leads to less sliver triangles
  20285. ear = next.next;
  20286. stop = next.next;
  20287. continue;
  20288. }
  20289. ear = next;
  20290. // if we looped through the whole remaining polygon and can't find any more ears
  20291. if ( ear === stop ) {
  20292. // try filtering points and slicing again
  20293. if ( ! pass ) {
  20294. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20295. // if this didn't work, try curing all small self-intersections locally
  20296. } else if ( pass === 1 ) {
  20297. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20298. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20299. // as a last resort, try splitting the remaining polygon into two
  20300. } else if ( pass === 2 ) {
  20301. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20302. }
  20303. break;
  20304. }
  20305. }
  20306. }
  20307. // check whether a polygon node forms a valid ear with adjacent nodes
  20308. function isEar( ear ) {
  20309. const a = ear.prev,
  20310. b = ear,
  20311. c = ear.next;
  20312. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20313. // now make sure we don't have other points inside the potential ear
  20314. let p = ear.next.next;
  20315. while ( p !== ear.prev ) {
  20316. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20317. area( p.prev, p, p.next ) >= 0 ) return false;
  20318. p = p.next;
  20319. }
  20320. return true;
  20321. }
  20322. function isEarHashed( ear, minX, minY, invSize ) {
  20323. const a = ear.prev,
  20324. b = ear,
  20325. c = ear.next;
  20326. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20327. // triangle bbox; min & max are calculated like this for speed
  20328. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20329. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20330. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20331. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20332. // z-order range for the current triangle bbox;
  20333. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20334. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20335. let p = ear.prevZ,
  20336. n = ear.nextZ;
  20337. // look for points inside the triangle in both directions
  20338. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20339. if ( p !== ear.prev && p !== ear.next &&
  20340. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20341. area( p.prev, p, p.next ) >= 0 ) return false;
  20342. p = p.prevZ;
  20343. if ( n !== ear.prev && n !== ear.next &&
  20344. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20345. area( n.prev, n, n.next ) >= 0 ) return false;
  20346. n = n.nextZ;
  20347. }
  20348. // look for remaining points in decreasing z-order
  20349. while ( p && p.z >= minZ ) {
  20350. if ( p !== ear.prev && p !== ear.next &&
  20351. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20352. area( p.prev, p, p.next ) >= 0 ) return false;
  20353. p = p.prevZ;
  20354. }
  20355. // look for remaining points in increasing z-order
  20356. while ( n && n.z <= maxZ ) {
  20357. if ( n !== ear.prev && n !== ear.next &&
  20358. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20359. area( n.prev, n, n.next ) >= 0 ) return false;
  20360. n = n.nextZ;
  20361. }
  20362. return true;
  20363. }
  20364. // go through all polygon nodes and cure small local self-intersections
  20365. function cureLocalIntersections( start, triangles, dim ) {
  20366. let p = start;
  20367. do {
  20368. const a = p.prev,
  20369. b = p.next.next;
  20370. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20371. triangles.push( a.i / dim );
  20372. triangles.push( p.i / dim );
  20373. triangles.push( b.i / dim );
  20374. // remove two nodes involved
  20375. removeNode( p );
  20376. removeNode( p.next );
  20377. p = start = b;
  20378. }
  20379. p = p.next;
  20380. } while ( p !== start );
  20381. return filterPoints( p );
  20382. }
  20383. // try splitting polygon into two and triangulate them independently
  20384. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20385. // look for a valid diagonal that divides the polygon into two
  20386. let a = start;
  20387. do {
  20388. let b = a.next.next;
  20389. while ( b !== a.prev ) {
  20390. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20391. // split the polygon in two by the diagonal
  20392. let c = splitPolygon( a, b );
  20393. // filter colinear points around the cuts
  20394. a = filterPoints( a, a.next );
  20395. c = filterPoints( c, c.next );
  20396. // run earcut on each half
  20397. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20398. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20399. return;
  20400. }
  20401. b = b.next;
  20402. }
  20403. a = a.next;
  20404. } while ( a !== start );
  20405. }
  20406. // link every hole into the outer loop, producing a single-ring polygon without holes
  20407. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20408. const queue = [];
  20409. let i, len, start, end, list;
  20410. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20411. start = holeIndices[ i ] * dim;
  20412. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20413. list = linkedList( data, start, end, dim, false );
  20414. if ( list === list.next ) list.steiner = true;
  20415. queue.push( getLeftmost( list ) );
  20416. }
  20417. queue.sort( compareX );
  20418. // process holes from left to right
  20419. for ( i = 0; i < queue.length; i ++ ) {
  20420. eliminateHole( queue[ i ], outerNode );
  20421. outerNode = filterPoints( outerNode, outerNode.next );
  20422. }
  20423. return outerNode;
  20424. }
  20425. function compareX( a, b ) {
  20426. return a.x - b.x;
  20427. }
  20428. // find a bridge between vertices that connects hole with an outer ring and link it
  20429. function eliminateHole( hole, outerNode ) {
  20430. outerNode = findHoleBridge( hole, outerNode );
  20431. if ( outerNode ) {
  20432. const b = splitPolygon( outerNode, hole );
  20433. // filter collinear points around the cuts
  20434. filterPoints( outerNode, outerNode.next );
  20435. filterPoints( b, b.next );
  20436. }
  20437. }
  20438. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20439. function findHoleBridge( hole, outerNode ) {
  20440. let p = outerNode;
  20441. const hx = hole.x;
  20442. const hy = hole.y;
  20443. let qx = - Infinity, m;
  20444. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20445. // segment's endpoint with lesser x will be potential connection point
  20446. do {
  20447. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20448. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20449. if ( x <= hx && x > qx ) {
  20450. qx = x;
  20451. if ( x === hx ) {
  20452. if ( hy === p.y ) return p;
  20453. if ( hy === p.next.y ) return p.next;
  20454. }
  20455. m = p.x < p.next.x ? p : p.next;
  20456. }
  20457. }
  20458. p = p.next;
  20459. } while ( p !== outerNode );
  20460. if ( ! m ) return null;
  20461. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  20462. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20463. // if there are no points found, we have a valid connection;
  20464. // otherwise choose the point of the minimum angle with the ray as connection point
  20465. const stop = m,
  20466. mx = m.x,
  20467. my = m.y;
  20468. let tanMin = Infinity, tan;
  20469. p = m;
  20470. do {
  20471. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20472. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20473. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20474. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20475. m = p;
  20476. tanMin = tan;
  20477. }
  20478. }
  20479. p = p.next;
  20480. } while ( p !== stop );
  20481. return m;
  20482. }
  20483. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20484. function sectorContainsSector( m, p ) {
  20485. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20486. }
  20487. // interlink polygon nodes in z-order
  20488. function indexCurve( start, minX, minY, invSize ) {
  20489. let p = start;
  20490. do {
  20491. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20492. p.prevZ = p.prev;
  20493. p.nextZ = p.next;
  20494. p = p.next;
  20495. } while ( p !== start );
  20496. p.prevZ.nextZ = null;
  20497. p.prevZ = null;
  20498. sortLinked( p );
  20499. }
  20500. // Simon Tatham's linked list merge sort algorithm
  20501. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20502. function sortLinked( list ) {
  20503. let i, p, q, e, tail, numMerges, pSize, qSize,
  20504. inSize = 1;
  20505. do {
  20506. p = list;
  20507. list = null;
  20508. tail = null;
  20509. numMerges = 0;
  20510. while ( p ) {
  20511. numMerges ++;
  20512. q = p;
  20513. pSize = 0;
  20514. for ( i = 0; i < inSize; i ++ ) {
  20515. pSize ++;
  20516. q = q.nextZ;
  20517. if ( ! q ) break;
  20518. }
  20519. qSize = inSize;
  20520. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20521. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20522. e = p;
  20523. p = p.nextZ;
  20524. pSize --;
  20525. } else {
  20526. e = q;
  20527. q = q.nextZ;
  20528. qSize --;
  20529. }
  20530. if ( tail ) tail.nextZ = e;
  20531. else list = e;
  20532. e.prevZ = tail;
  20533. tail = e;
  20534. }
  20535. p = q;
  20536. }
  20537. tail.nextZ = null;
  20538. inSize *= 2;
  20539. } while ( numMerges > 1 );
  20540. return list;
  20541. }
  20542. // z-order of a point given coords and inverse of the longer side of data bbox
  20543. function zOrder( x, y, minX, minY, invSize ) {
  20544. // coords are transformed into non-negative 15-bit integer range
  20545. x = 32767 * ( x - minX ) * invSize;
  20546. y = 32767 * ( y - minY ) * invSize;
  20547. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20548. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20549. x = ( x | ( x << 2 ) ) & 0x33333333;
  20550. x = ( x | ( x << 1 ) ) & 0x55555555;
  20551. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20552. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20553. y = ( y | ( y << 2 ) ) & 0x33333333;
  20554. y = ( y | ( y << 1 ) ) & 0x55555555;
  20555. return x | ( y << 1 );
  20556. }
  20557. // find the leftmost node of a polygon ring
  20558. function getLeftmost( start ) {
  20559. let p = start,
  20560. leftmost = start;
  20561. do {
  20562. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20563. p = p.next;
  20564. } while ( p !== start );
  20565. return leftmost;
  20566. }
  20567. // check if a point lies within a convex triangle
  20568. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20569. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20570. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20571. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20572. }
  20573. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20574. function isValidDiagonal( a, b ) {
  20575. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  20576. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20577. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20578. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20579. }
  20580. // signed area of a triangle
  20581. function area( p, q, r ) {
  20582. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20583. }
  20584. // check if two points are equal
  20585. function equals( p1, p2 ) {
  20586. return p1.x === p2.x && p1.y === p2.y;
  20587. }
  20588. // check if two segments intersect
  20589. function intersects( p1, q1, p2, q2 ) {
  20590. const o1 = sign( area( p1, q1, p2 ) );
  20591. const o2 = sign( area( p1, q1, q2 ) );
  20592. const o3 = sign( area( p2, q2, p1 ) );
  20593. const o4 = sign( area( p2, q2, q1 ) );
  20594. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20595. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20596. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20597. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20598. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20599. return false;
  20600. }
  20601. // for collinear points p, q, r, check if point q lies on segment pr
  20602. function onSegment( p, q, r ) {
  20603. 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 );
  20604. }
  20605. function sign( num ) {
  20606. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20607. }
  20608. // check if a polygon diagonal intersects any polygon segments
  20609. function intersectsPolygon( a, b ) {
  20610. let p = a;
  20611. do {
  20612. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20613. intersects( p, p.next, a, b ) ) return true;
  20614. p = p.next;
  20615. } while ( p !== a );
  20616. return false;
  20617. }
  20618. // check if a polygon diagonal is locally inside the polygon
  20619. function locallyInside( a, b ) {
  20620. return area( a.prev, a, a.next ) < 0 ?
  20621. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20622. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20623. }
  20624. // check if the middle point of a polygon diagonal is inside the polygon
  20625. function middleInside( a, b ) {
  20626. let p = a,
  20627. inside = false;
  20628. const px = ( a.x + b.x ) / 2,
  20629. py = ( a.y + b.y ) / 2;
  20630. do {
  20631. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20632. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20633. inside = ! inside;
  20634. p = p.next;
  20635. } while ( p !== a );
  20636. return inside;
  20637. }
  20638. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20639. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20640. function splitPolygon( a, b ) {
  20641. const a2 = new Node( a.i, a.x, a.y ),
  20642. b2 = new Node( b.i, b.x, b.y ),
  20643. an = a.next,
  20644. bp = b.prev;
  20645. a.next = b;
  20646. b.prev = a;
  20647. a2.next = an;
  20648. an.prev = a2;
  20649. b2.next = a2;
  20650. a2.prev = b2;
  20651. bp.next = b2;
  20652. b2.prev = bp;
  20653. return b2;
  20654. }
  20655. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20656. function insertNode( i, x, y, last ) {
  20657. const p = new Node( i, x, y );
  20658. if ( ! last ) {
  20659. p.prev = p;
  20660. p.next = p;
  20661. } else {
  20662. p.next = last.next;
  20663. p.prev = last;
  20664. last.next.prev = p;
  20665. last.next = p;
  20666. }
  20667. return p;
  20668. }
  20669. function removeNode( p ) {
  20670. p.next.prev = p.prev;
  20671. p.prev.next = p.next;
  20672. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20673. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20674. }
  20675. function Node( i, x, y ) {
  20676. // vertex index in coordinates array
  20677. this.i = i;
  20678. // vertex coordinates
  20679. this.x = x;
  20680. this.y = y;
  20681. // previous and next vertex nodes in a polygon ring
  20682. this.prev = null;
  20683. this.next = null;
  20684. // z-order curve value
  20685. this.z = null;
  20686. // previous and next nodes in z-order
  20687. this.prevZ = null;
  20688. this.nextZ = null;
  20689. // indicates whether this is a steiner point
  20690. this.steiner = false;
  20691. }
  20692. function signedArea( data, start, end, dim ) {
  20693. let sum = 0;
  20694. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20695. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20696. j = i;
  20697. }
  20698. return sum;
  20699. }
  20700. class ShapeUtils {
  20701. // calculate area of the contour polygon
  20702. static area( contour ) {
  20703. const n = contour.length;
  20704. let a = 0.0;
  20705. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20706. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20707. }
  20708. return a * 0.5;
  20709. }
  20710. static isClockWise( pts ) {
  20711. return ShapeUtils.area( pts ) < 0;
  20712. }
  20713. static triangulateShape( contour, holes ) {
  20714. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20715. const holeIndices = []; // array of hole indices
  20716. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20717. removeDupEndPts( contour );
  20718. addContour( vertices, contour );
  20719. //
  20720. let holeIndex = contour.length;
  20721. holes.forEach( removeDupEndPts );
  20722. for ( let i = 0; i < holes.length; i ++ ) {
  20723. holeIndices.push( holeIndex );
  20724. holeIndex += holes[ i ].length;
  20725. addContour( vertices, holes[ i ] );
  20726. }
  20727. //
  20728. const triangles = Earcut.triangulate( vertices, holeIndices );
  20729. //
  20730. for ( let i = 0; i < triangles.length; i += 3 ) {
  20731. faces.push( triangles.slice( i, i + 3 ) );
  20732. }
  20733. return faces;
  20734. }
  20735. }
  20736. function removeDupEndPts( points ) {
  20737. const l = points.length;
  20738. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20739. points.pop();
  20740. }
  20741. }
  20742. function addContour( vertices, contour ) {
  20743. for ( let i = 0; i < contour.length; i ++ ) {
  20744. vertices.push( contour[ i ].x );
  20745. vertices.push( contour[ i ].y );
  20746. }
  20747. }
  20748. /**
  20749. * Creates extruded geometry from a path shape.
  20750. *
  20751. * parameters = {
  20752. *
  20753. * curveSegments: <int>, // number of points on the curves
  20754. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20755. * depth: <float>, // Depth to extrude the shape
  20756. *
  20757. * bevelEnabled: <bool>, // turn on bevel
  20758. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20759. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20760. * bevelOffset: <float>, // how far from shape outline does bevel start
  20761. * bevelSegments: <int>, // number of bevel layers
  20762. *
  20763. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20764. *
  20765. * UVGenerator: <Object> // object that provides UV generator functions
  20766. *
  20767. * }
  20768. */
  20769. class ExtrudeGeometry extends BufferGeometry {
  20770. 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 = {} ) {
  20771. super();
  20772. this.type = 'ExtrudeGeometry';
  20773. this.parameters = {
  20774. shapes: shapes,
  20775. options: options
  20776. };
  20777. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20778. const scope = this;
  20779. const verticesArray = [];
  20780. const uvArray = [];
  20781. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20782. const shape = shapes[ i ];
  20783. addShape( shape );
  20784. }
  20785. // build geometry
  20786. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20787. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20788. this.computeVertexNormals();
  20789. // functions
  20790. function addShape( shape ) {
  20791. const placeholder = [];
  20792. // options
  20793. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20794. const steps = options.steps !== undefined ? options.steps : 1;
  20795. const depth = options.depth !== undefined ? options.depth : 1;
  20796. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20797. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20798. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20799. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20800. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20801. const extrudePath = options.extrudePath;
  20802. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20803. //
  20804. let extrudePts, extrudeByPath = false;
  20805. let splineTube, binormal, normal, position2;
  20806. if ( extrudePath ) {
  20807. extrudePts = extrudePath.getSpacedPoints( steps );
  20808. extrudeByPath = true;
  20809. bevelEnabled = false; // bevels not supported for path extrusion
  20810. // SETUP TNB variables
  20811. // TODO1 - have a .isClosed in spline?
  20812. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20813. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20814. binormal = new Vector3();
  20815. normal = new Vector3();
  20816. position2 = new Vector3();
  20817. }
  20818. // Safeguards if bevels are not enabled
  20819. if ( ! bevelEnabled ) {
  20820. bevelSegments = 0;
  20821. bevelThickness = 0;
  20822. bevelSize = 0;
  20823. bevelOffset = 0;
  20824. }
  20825. // Variables initialization
  20826. const shapePoints = shape.extractPoints( curveSegments );
  20827. let vertices = shapePoints.shape;
  20828. const holes = shapePoints.holes;
  20829. const reverse = ! ShapeUtils.isClockWise( vertices );
  20830. if ( reverse ) {
  20831. vertices = vertices.reverse();
  20832. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20833. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20834. const ahole = holes[ h ];
  20835. if ( ShapeUtils.isClockWise( ahole ) ) {
  20836. holes[ h ] = ahole.reverse();
  20837. }
  20838. }
  20839. }
  20840. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20841. /* Vertices */
  20842. const contour = vertices; // vertices has all points but contour has only points of circumference
  20843. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20844. const ahole = holes[ h ];
  20845. vertices = vertices.concat( ahole );
  20846. }
  20847. function scalePt2( pt, vec, size ) {
  20848. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20849. return vec.clone().multiplyScalar( size ).add( pt );
  20850. }
  20851. const vlen = vertices.length, flen = faces.length;
  20852. // Find directions for point movement
  20853. function getBevelVec( inPt, inPrev, inNext ) {
  20854. // computes for inPt the corresponding point inPt' on a new contour
  20855. // shifted by 1 unit (length of normalized vector) to the left
  20856. // if we walk along contour clockwise, this new contour is outside the old one
  20857. //
  20858. // inPt' is the intersection of the two lines parallel to the two
  20859. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20860. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20861. // good reading for geometry algorithms (here: line-line intersection)
  20862. // http://geomalgorithms.com/a05-_intersect-1.html
  20863. const v_prev_x = inPt.x - inPrev.x,
  20864. v_prev_y = inPt.y - inPrev.y;
  20865. const v_next_x = inNext.x - inPt.x,
  20866. v_next_y = inNext.y - inPt.y;
  20867. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20868. // check for collinear edges
  20869. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20870. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20871. // not collinear
  20872. // length of vectors for normalizing
  20873. const v_prev_len = Math.sqrt( v_prev_lensq );
  20874. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20875. // shift adjacent points by unit vectors to the left
  20876. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20877. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20878. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20879. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20880. // scaling factor for v_prev to intersection point
  20881. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20882. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20883. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20884. // vector from inPt to intersection point
  20885. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20886. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20887. // Don't normalize!, otherwise sharp corners become ugly
  20888. // but prevent crazy spikes
  20889. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20890. if ( v_trans_lensq <= 2 ) {
  20891. return new Vector2( v_trans_x, v_trans_y );
  20892. } else {
  20893. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20894. }
  20895. } else {
  20896. // handle special case of collinear edges
  20897. let direction_eq = false; // assumes: opposite
  20898. if ( v_prev_x > Number.EPSILON ) {
  20899. if ( v_next_x > Number.EPSILON ) {
  20900. direction_eq = true;
  20901. }
  20902. } else {
  20903. if ( v_prev_x < - Number.EPSILON ) {
  20904. if ( v_next_x < - Number.EPSILON ) {
  20905. direction_eq = true;
  20906. }
  20907. } else {
  20908. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20909. direction_eq = true;
  20910. }
  20911. }
  20912. }
  20913. if ( direction_eq ) {
  20914. // console.log("Warning: lines are a straight sequence");
  20915. v_trans_x = - v_prev_y;
  20916. v_trans_y = v_prev_x;
  20917. shrink_by = Math.sqrt( v_prev_lensq );
  20918. } else {
  20919. // console.log("Warning: lines are a straight spike");
  20920. v_trans_x = v_prev_x;
  20921. v_trans_y = v_prev_y;
  20922. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20923. }
  20924. }
  20925. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20926. }
  20927. const contourMovements = [];
  20928. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20929. if ( j === il ) j = 0;
  20930. if ( k === il ) k = 0;
  20931. // (j)---(i)---(k)
  20932. // console.log('i,j,k', i, j , k)
  20933. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20934. }
  20935. const holesMovements = [];
  20936. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20937. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20938. const ahole = holes[ h ];
  20939. oneHoleMovements = [];
  20940. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20941. if ( j === il ) j = 0;
  20942. if ( k === il ) k = 0;
  20943. // (j)---(i)---(k)
  20944. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20945. }
  20946. holesMovements.push( oneHoleMovements );
  20947. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20948. }
  20949. // Loop bevelSegments, 1 for the front, 1 for the back
  20950. for ( let b = 0; b < bevelSegments; b ++ ) {
  20951. //for ( b = bevelSegments; b > 0; b -- ) {
  20952. const t = b / bevelSegments;
  20953. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20954. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20955. // contract shape
  20956. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20957. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20958. v( vert.x, vert.y, - z );
  20959. }
  20960. // expand holes
  20961. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20962. const ahole = holes[ h ];
  20963. oneHoleMovements = holesMovements[ h ];
  20964. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20965. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20966. v( vert.x, vert.y, - z );
  20967. }
  20968. }
  20969. }
  20970. const bs = bevelSize + bevelOffset;
  20971. // Back facing vertices
  20972. for ( let i = 0; i < vlen; i ++ ) {
  20973. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20974. if ( ! extrudeByPath ) {
  20975. v( vert.x, vert.y, 0 );
  20976. } else {
  20977. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20978. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20979. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20980. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20981. v( position2.x, position2.y, position2.z );
  20982. }
  20983. }
  20984. // Add stepped vertices...
  20985. // Including front facing vertices
  20986. for ( let s = 1; s <= steps; s ++ ) {
  20987. for ( let i = 0; i < vlen; i ++ ) {
  20988. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20989. if ( ! extrudeByPath ) {
  20990. v( vert.x, vert.y, depth / steps * s );
  20991. } else {
  20992. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20993. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20994. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20995. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20996. v( position2.x, position2.y, position2.z );
  20997. }
  20998. }
  20999. }
  21000. // Add bevel segments planes
  21001. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21002. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21003. const t = b / bevelSegments;
  21004. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21005. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21006. // contract shape
  21007. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21008. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21009. v( vert.x, vert.y, depth + z );
  21010. }
  21011. // expand holes
  21012. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21013. const ahole = holes[ h ];
  21014. oneHoleMovements = holesMovements[ h ];
  21015. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21016. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21017. if ( ! extrudeByPath ) {
  21018. v( vert.x, vert.y, depth + z );
  21019. } else {
  21020. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21021. }
  21022. }
  21023. }
  21024. }
  21025. /* Faces */
  21026. // Top and bottom faces
  21027. buildLidFaces();
  21028. // Sides faces
  21029. buildSideFaces();
  21030. ///// Internal functions
  21031. function buildLidFaces() {
  21032. const start = verticesArray.length / 3;
  21033. if ( bevelEnabled ) {
  21034. let layer = 0; // steps + 1
  21035. let offset = vlen * layer;
  21036. // Bottom faces
  21037. for ( let i = 0; i < flen; i ++ ) {
  21038. const face = faces[ i ];
  21039. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21040. }
  21041. layer = steps + bevelSegments * 2;
  21042. offset = vlen * layer;
  21043. // Top faces
  21044. for ( let i = 0; i < flen; i ++ ) {
  21045. const face = faces[ i ];
  21046. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21047. }
  21048. } else {
  21049. // Bottom faces
  21050. for ( let i = 0; i < flen; i ++ ) {
  21051. const face = faces[ i ];
  21052. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21053. }
  21054. // Top faces
  21055. for ( let i = 0; i < flen; i ++ ) {
  21056. const face = faces[ i ];
  21057. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21058. }
  21059. }
  21060. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21061. }
  21062. // Create faces for the z-sides of the shape
  21063. function buildSideFaces() {
  21064. const start = verticesArray.length / 3;
  21065. let layeroffset = 0;
  21066. sidewalls( contour, layeroffset );
  21067. layeroffset += contour.length;
  21068. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21069. const ahole = holes[ h ];
  21070. sidewalls( ahole, layeroffset );
  21071. //, true
  21072. layeroffset += ahole.length;
  21073. }
  21074. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21075. }
  21076. function sidewalls( contour, layeroffset ) {
  21077. let i = contour.length;
  21078. while ( -- i >= 0 ) {
  21079. const j = i;
  21080. let k = i - 1;
  21081. if ( k < 0 ) k = contour.length - 1;
  21082. //console.log('b', i,j, i-1, k,vertices.length);
  21083. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21084. const slen1 = vlen * s;
  21085. const slen2 = vlen * ( s + 1 );
  21086. const a = layeroffset + j + slen1,
  21087. b = layeroffset + k + slen1,
  21088. c = layeroffset + k + slen2,
  21089. d = layeroffset + j + slen2;
  21090. f4( a, b, c, d );
  21091. }
  21092. }
  21093. }
  21094. function v( x, y, z ) {
  21095. placeholder.push( x );
  21096. placeholder.push( y );
  21097. placeholder.push( z );
  21098. }
  21099. function f3( a, b, c ) {
  21100. addVertex( a );
  21101. addVertex( b );
  21102. addVertex( c );
  21103. const nextIndex = verticesArray.length / 3;
  21104. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21105. addUV( uvs[ 0 ] );
  21106. addUV( uvs[ 1 ] );
  21107. addUV( uvs[ 2 ] );
  21108. }
  21109. function f4( a, b, c, d ) {
  21110. addVertex( a );
  21111. addVertex( b );
  21112. addVertex( d );
  21113. addVertex( b );
  21114. addVertex( c );
  21115. addVertex( d );
  21116. const nextIndex = verticesArray.length / 3;
  21117. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21118. addUV( uvs[ 0 ] );
  21119. addUV( uvs[ 1 ] );
  21120. addUV( uvs[ 3 ] );
  21121. addUV( uvs[ 1 ] );
  21122. addUV( uvs[ 2 ] );
  21123. addUV( uvs[ 3 ] );
  21124. }
  21125. function addVertex( index ) {
  21126. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21127. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21128. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21129. }
  21130. function addUV( vector2 ) {
  21131. uvArray.push( vector2.x );
  21132. uvArray.push( vector2.y );
  21133. }
  21134. }
  21135. }
  21136. toJSON() {
  21137. const data = super.toJSON();
  21138. const shapes = this.parameters.shapes;
  21139. const options = this.parameters.options;
  21140. return toJSON$1( shapes, options, data );
  21141. }
  21142. static fromJSON( data, shapes ) {
  21143. const geometryShapes = [];
  21144. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21145. const shape = shapes[ data.shapes[ j ] ];
  21146. geometryShapes.push( shape );
  21147. }
  21148. const extrudePath = data.options.extrudePath;
  21149. if ( extrudePath !== undefined ) {
  21150. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21151. }
  21152. return new ExtrudeGeometry( geometryShapes, data.options );
  21153. }
  21154. }
  21155. const WorldUVGenerator = {
  21156. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21157. const a_x = vertices[ indexA * 3 ];
  21158. const a_y = vertices[ indexA * 3 + 1 ];
  21159. const b_x = vertices[ indexB * 3 ];
  21160. const b_y = vertices[ indexB * 3 + 1 ];
  21161. const c_x = vertices[ indexC * 3 ];
  21162. const c_y = vertices[ indexC * 3 + 1 ];
  21163. return [
  21164. new Vector2( a_x, a_y ),
  21165. new Vector2( b_x, b_y ),
  21166. new Vector2( c_x, c_y )
  21167. ];
  21168. },
  21169. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21170. const a_x = vertices[ indexA * 3 ];
  21171. const a_y = vertices[ indexA * 3 + 1 ];
  21172. const a_z = vertices[ indexA * 3 + 2 ];
  21173. const b_x = vertices[ indexB * 3 ];
  21174. const b_y = vertices[ indexB * 3 + 1 ];
  21175. const b_z = vertices[ indexB * 3 + 2 ];
  21176. const c_x = vertices[ indexC * 3 ];
  21177. const c_y = vertices[ indexC * 3 + 1 ];
  21178. const c_z = vertices[ indexC * 3 + 2 ];
  21179. const d_x = vertices[ indexD * 3 ];
  21180. const d_y = vertices[ indexD * 3 + 1 ];
  21181. const d_z = vertices[ indexD * 3 + 2 ];
  21182. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21183. return [
  21184. new Vector2( a_x, 1 - a_z ),
  21185. new Vector2( b_x, 1 - b_z ),
  21186. new Vector2( c_x, 1 - c_z ),
  21187. new Vector2( d_x, 1 - d_z )
  21188. ];
  21189. } else {
  21190. return [
  21191. new Vector2( a_y, 1 - a_z ),
  21192. new Vector2( b_y, 1 - b_z ),
  21193. new Vector2( c_y, 1 - c_z ),
  21194. new Vector2( d_y, 1 - d_z )
  21195. ];
  21196. }
  21197. }
  21198. };
  21199. function toJSON$1( shapes, options, data ) {
  21200. data.shapes = [];
  21201. if ( Array.isArray( shapes ) ) {
  21202. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21203. const shape = shapes[ i ];
  21204. data.shapes.push( shape.uuid );
  21205. }
  21206. } else {
  21207. data.shapes.push( shapes.uuid );
  21208. }
  21209. data.options = Object.assign( {}, options );
  21210. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21211. return data;
  21212. }
  21213. class IcosahedronGeometry extends PolyhedronGeometry {
  21214. constructor( radius = 1, detail = 0 ) {
  21215. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21216. const vertices = [
  21217. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21218. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21219. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21220. ];
  21221. const indices = [
  21222. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21223. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21224. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21225. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21226. ];
  21227. super( vertices, indices, radius, detail );
  21228. this.type = 'IcosahedronGeometry';
  21229. this.parameters = {
  21230. radius: radius,
  21231. detail: detail
  21232. };
  21233. }
  21234. static fromJSON( data ) {
  21235. return new IcosahedronGeometry( data.radius, data.detail );
  21236. }
  21237. }
  21238. class OctahedronGeometry extends PolyhedronGeometry {
  21239. constructor( radius = 1, detail = 0 ) {
  21240. const vertices = [
  21241. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21242. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21243. ];
  21244. const indices = [
  21245. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21246. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21247. 1, 3, 4, 1, 4, 2
  21248. ];
  21249. super( vertices, indices, radius, detail );
  21250. this.type = 'OctahedronGeometry';
  21251. this.parameters = {
  21252. radius: radius,
  21253. detail: detail
  21254. };
  21255. }
  21256. static fromJSON( data ) {
  21257. return new OctahedronGeometry( data.radius, data.detail );
  21258. }
  21259. }
  21260. class RingGeometry extends BufferGeometry {
  21261. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21262. super();
  21263. this.type = 'RingGeometry';
  21264. this.parameters = {
  21265. innerRadius: innerRadius,
  21266. outerRadius: outerRadius,
  21267. thetaSegments: thetaSegments,
  21268. phiSegments: phiSegments,
  21269. thetaStart: thetaStart,
  21270. thetaLength: thetaLength
  21271. };
  21272. thetaSegments = Math.max( 3, thetaSegments );
  21273. phiSegments = Math.max( 1, phiSegments );
  21274. // buffers
  21275. const indices = [];
  21276. const vertices = [];
  21277. const normals = [];
  21278. const uvs = [];
  21279. // some helper variables
  21280. let radius = innerRadius;
  21281. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21282. const vertex = new Vector3();
  21283. const uv = new Vector2();
  21284. // generate vertices, normals and uvs
  21285. for ( let j = 0; j <= phiSegments; j ++ ) {
  21286. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21287. // values are generate from the inside of the ring to the outside
  21288. const segment = thetaStart + i / thetaSegments * thetaLength;
  21289. // vertex
  21290. vertex.x = radius * Math.cos( segment );
  21291. vertex.y = radius * Math.sin( segment );
  21292. vertices.push( vertex.x, vertex.y, vertex.z );
  21293. // normal
  21294. normals.push( 0, 0, 1 );
  21295. // uv
  21296. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21297. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21298. uvs.push( uv.x, uv.y );
  21299. }
  21300. // increase the radius for next row of vertices
  21301. radius += radiusStep;
  21302. }
  21303. // indices
  21304. for ( let j = 0; j < phiSegments; j ++ ) {
  21305. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21306. for ( let i = 0; i < thetaSegments; i ++ ) {
  21307. const segment = i + thetaSegmentLevel;
  21308. const a = segment;
  21309. const b = segment + thetaSegments + 1;
  21310. const c = segment + thetaSegments + 2;
  21311. const d = segment + 1;
  21312. // faces
  21313. indices.push( a, b, d );
  21314. indices.push( b, c, d );
  21315. }
  21316. }
  21317. // build geometry
  21318. this.setIndex( indices );
  21319. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21320. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21321. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21322. }
  21323. static fromJSON( data ) {
  21324. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21325. }
  21326. }
  21327. class ShapeGeometry extends BufferGeometry {
  21328. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21329. super();
  21330. this.type = 'ShapeGeometry';
  21331. this.parameters = {
  21332. shapes: shapes,
  21333. curveSegments: curveSegments
  21334. };
  21335. // buffers
  21336. const indices = [];
  21337. const vertices = [];
  21338. const normals = [];
  21339. const uvs = [];
  21340. // helper variables
  21341. let groupStart = 0;
  21342. let groupCount = 0;
  21343. // allow single and array values for "shapes" parameter
  21344. if ( Array.isArray( shapes ) === false ) {
  21345. addShape( shapes );
  21346. } else {
  21347. for ( let i = 0; i < shapes.length; i ++ ) {
  21348. addShape( shapes[ i ] );
  21349. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21350. groupStart += groupCount;
  21351. groupCount = 0;
  21352. }
  21353. }
  21354. // build geometry
  21355. this.setIndex( indices );
  21356. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21357. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21358. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21359. // helper functions
  21360. function addShape( shape ) {
  21361. const indexOffset = vertices.length / 3;
  21362. const points = shape.extractPoints( curveSegments );
  21363. let shapeVertices = points.shape;
  21364. const shapeHoles = points.holes;
  21365. // check direction of vertices
  21366. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21367. shapeVertices = shapeVertices.reverse();
  21368. }
  21369. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21370. const shapeHole = shapeHoles[ i ];
  21371. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21372. shapeHoles[ i ] = shapeHole.reverse();
  21373. }
  21374. }
  21375. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21376. // join vertices of inner and outer paths to a single array
  21377. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21378. const shapeHole = shapeHoles[ i ];
  21379. shapeVertices = shapeVertices.concat( shapeHole );
  21380. }
  21381. // vertices, normals, uvs
  21382. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21383. const vertex = shapeVertices[ i ];
  21384. vertices.push( vertex.x, vertex.y, 0 );
  21385. normals.push( 0, 0, 1 );
  21386. uvs.push( vertex.x, vertex.y ); // world uvs
  21387. }
  21388. // incides
  21389. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21390. const face = faces[ i ];
  21391. const a = face[ 0 ] + indexOffset;
  21392. const b = face[ 1 ] + indexOffset;
  21393. const c = face[ 2 ] + indexOffset;
  21394. indices.push( a, b, c );
  21395. groupCount += 3;
  21396. }
  21397. }
  21398. }
  21399. toJSON() {
  21400. const data = super.toJSON();
  21401. const shapes = this.parameters.shapes;
  21402. return toJSON( shapes, data );
  21403. }
  21404. static fromJSON( data, shapes ) {
  21405. const geometryShapes = [];
  21406. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21407. const shape = shapes[ data.shapes[ j ] ];
  21408. geometryShapes.push( shape );
  21409. }
  21410. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21411. }
  21412. }
  21413. function toJSON( shapes, data ) {
  21414. data.shapes = [];
  21415. if ( Array.isArray( shapes ) ) {
  21416. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21417. const shape = shapes[ i ];
  21418. data.shapes.push( shape.uuid );
  21419. }
  21420. } else {
  21421. data.shapes.push( shapes.uuid );
  21422. }
  21423. return data;
  21424. }
  21425. class SphereGeometry extends BufferGeometry {
  21426. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21427. super();
  21428. this.type = 'SphereGeometry';
  21429. this.parameters = {
  21430. radius: radius,
  21431. widthSegments: widthSegments,
  21432. heightSegments: heightSegments,
  21433. phiStart: phiStart,
  21434. phiLength: phiLength,
  21435. thetaStart: thetaStart,
  21436. thetaLength: thetaLength
  21437. };
  21438. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21439. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21440. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21441. let index = 0;
  21442. const grid = [];
  21443. const vertex = new Vector3();
  21444. const normal = new Vector3();
  21445. // buffers
  21446. const indices = [];
  21447. const vertices = [];
  21448. const normals = [];
  21449. const uvs = [];
  21450. // generate vertices, normals and uvs
  21451. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21452. const verticesRow = [];
  21453. const v = iy / heightSegments;
  21454. // special case for the poles
  21455. let uOffset = 0;
  21456. if ( iy == 0 && thetaStart == 0 ) {
  21457. uOffset = 0.5 / widthSegments;
  21458. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21459. uOffset = - 0.5 / widthSegments;
  21460. }
  21461. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21462. const u = ix / widthSegments;
  21463. // vertex
  21464. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21465. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21466. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21467. vertices.push( vertex.x, vertex.y, vertex.z );
  21468. // normal
  21469. normal.copy( vertex ).normalize();
  21470. normals.push( normal.x, normal.y, normal.z );
  21471. // uv
  21472. uvs.push( u + uOffset, 1 - v );
  21473. verticesRow.push( index ++ );
  21474. }
  21475. grid.push( verticesRow );
  21476. }
  21477. // indices
  21478. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21479. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21480. const a = grid[ iy ][ ix + 1 ];
  21481. const b = grid[ iy ][ ix ];
  21482. const c = grid[ iy + 1 ][ ix ];
  21483. const d = grid[ iy + 1 ][ ix + 1 ];
  21484. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21485. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21486. }
  21487. }
  21488. // build geometry
  21489. this.setIndex( indices );
  21490. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21491. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21492. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21493. }
  21494. static fromJSON( data ) {
  21495. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21496. }
  21497. }
  21498. class TetrahedronGeometry extends PolyhedronGeometry {
  21499. constructor( radius = 1, detail = 0 ) {
  21500. const vertices = [
  21501. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21502. ];
  21503. const indices = [
  21504. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21505. ];
  21506. super( vertices, indices, radius, detail );
  21507. this.type = 'TetrahedronGeometry';
  21508. this.parameters = {
  21509. radius: radius,
  21510. detail: detail
  21511. };
  21512. }
  21513. static fromJSON( data ) {
  21514. return new TetrahedronGeometry( data.radius, data.detail );
  21515. }
  21516. }
  21517. class TorusGeometry extends BufferGeometry {
  21518. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21519. super();
  21520. this.type = 'TorusGeometry';
  21521. this.parameters = {
  21522. radius: radius,
  21523. tube: tube,
  21524. radialSegments: radialSegments,
  21525. tubularSegments: tubularSegments,
  21526. arc: arc
  21527. };
  21528. radialSegments = Math.floor( radialSegments );
  21529. tubularSegments = Math.floor( tubularSegments );
  21530. // buffers
  21531. const indices = [];
  21532. const vertices = [];
  21533. const normals = [];
  21534. const uvs = [];
  21535. // helper variables
  21536. const center = new Vector3();
  21537. const vertex = new Vector3();
  21538. const normal = new Vector3();
  21539. // generate vertices, normals and uvs
  21540. for ( let j = 0; j <= radialSegments; j ++ ) {
  21541. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21542. const u = i / tubularSegments * arc;
  21543. const v = j / radialSegments * Math.PI * 2;
  21544. // vertex
  21545. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21546. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21547. vertex.z = tube * Math.sin( v );
  21548. vertices.push( vertex.x, vertex.y, vertex.z );
  21549. // normal
  21550. center.x = radius * Math.cos( u );
  21551. center.y = radius * Math.sin( u );
  21552. normal.subVectors( vertex, center ).normalize();
  21553. normals.push( normal.x, normal.y, normal.z );
  21554. // uv
  21555. uvs.push( i / tubularSegments );
  21556. uvs.push( j / radialSegments );
  21557. }
  21558. }
  21559. // generate indices
  21560. for ( let j = 1; j <= radialSegments; j ++ ) {
  21561. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21562. // indices
  21563. const a = ( tubularSegments + 1 ) * j + i - 1;
  21564. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21565. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21566. const d = ( tubularSegments + 1 ) * j + i;
  21567. // faces
  21568. indices.push( a, b, d );
  21569. indices.push( b, c, d );
  21570. }
  21571. }
  21572. // build geometry
  21573. this.setIndex( indices );
  21574. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21575. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21576. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21577. }
  21578. static fromJSON( data ) {
  21579. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21580. }
  21581. }
  21582. class TorusKnotGeometry extends BufferGeometry {
  21583. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21584. super();
  21585. this.type = 'TorusKnotGeometry';
  21586. this.parameters = {
  21587. radius: radius,
  21588. tube: tube,
  21589. tubularSegments: tubularSegments,
  21590. radialSegments: radialSegments,
  21591. p: p,
  21592. q: q
  21593. };
  21594. tubularSegments = Math.floor( tubularSegments );
  21595. radialSegments = Math.floor( radialSegments );
  21596. // buffers
  21597. const indices = [];
  21598. const vertices = [];
  21599. const normals = [];
  21600. const uvs = [];
  21601. // helper variables
  21602. const vertex = new Vector3();
  21603. const normal = new Vector3();
  21604. const P1 = new Vector3();
  21605. const P2 = new Vector3();
  21606. const B = new Vector3();
  21607. const T = new Vector3();
  21608. const N = new Vector3();
  21609. // generate vertices, normals and uvs
  21610. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21611. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21612. const u = i / tubularSegments * p * Math.PI * 2;
  21613. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21614. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21615. calculatePositionOnCurve( u, p, q, radius, P1 );
  21616. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21617. // calculate orthonormal basis
  21618. T.subVectors( P2, P1 );
  21619. N.addVectors( P2, P1 );
  21620. B.crossVectors( T, N );
  21621. N.crossVectors( B, T );
  21622. // normalize B, N. T can be ignored, we don't use it
  21623. B.normalize();
  21624. N.normalize();
  21625. for ( let j = 0; j <= radialSegments; ++ j ) {
  21626. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21627. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21628. const v = j / radialSegments * Math.PI * 2;
  21629. const cx = - tube * Math.cos( v );
  21630. const cy = tube * Math.sin( v );
  21631. // now calculate the final vertex position.
  21632. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21633. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21634. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21635. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21636. vertices.push( vertex.x, vertex.y, vertex.z );
  21637. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21638. normal.subVectors( vertex, P1 ).normalize();
  21639. normals.push( normal.x, normal.y, normal.z );
  21640. // uv
  21641. uvs.push( i / tubularSegments );
  21642. uvs.push( j / radialSegments );
  21643. }
  21644. }
  21645. // generate indices
  21646. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21647. for ( let i = 1; i <= radialSegments; i ++ ) {
  21648. // indices
  21649. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21650. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21651. const c = ( radialSegments + 1 ) * j + i;
  21652. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21653. // faces
  21654. indices.push( a, b, d );
  21655. indices.push( b, c, d );
  21656. }
  21657. }
  21658. // build geometry
  21659. this.setIndex( indices );
  21660. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21661. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21662. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21663. // this function calculates the current position on the torus curve
  21664. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21665. const cu = Math.cos( u );
  21666. const su = Math.sin( u );
  21667. const quOverP = q / p * u;
  21668. const cs = Math.cos( quOverP );
  21669. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21670. position.y = radius * ( 2 + cs ) * su * 0.5;
  21671. position.z = radius * Math.sin( quOverP ) * 0.5;
  21672. }
  21673. }
  21674. static fromJSON( data ) {
  21675. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21676. }
  21677. }
  21678. class TubeGeometry extends BufferGeometry {
  21679. 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 ) {
  21680. super();
  21681. this.type = 'TubeGeometry';
  21682. this.parameters = {
  21683. path: path,
  21684. tubularSegments: tubularSegments,
  21685. radius: radius,
  21686. radialSegments: radialSegments,
  21687. closed: closed
  21688. };
  21689. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21690. // expose internals
  21691. this.tangents = frames.tangents;
  21692. this.normals = frames.normals;
  21693. this.binormals = frames.binormals;
  21694. // helper variables
  21695. const vertex = new Vector3();
  21696. const normal = new Vector3();
  21697. const uv = new Vector2();
  21698. let P = new Vector3();
  21699. // buffer
  21700. const vertices = [];
  21701. const normals = [];
  21702. const uvs = [];
  21703. const indices = [];
  21704. // create buffer data
  21705. generateBufferData();
  21706. // build geometry
  21707. this.setIndex( indices );
  21708. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21709. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21710. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21711. // functions
  21712. function generateBufferData() {
  21713. for ( let i = 0; i < tubularSegments; i ++ ) {
  21714. generateSegment( i );
  21715. }
  21716. // if the geometry is not closed, generate the last row of vertices and normals
  21717. // at the regular position on the given path
  21718. //
  21719. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21720. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21721. // uvs are generated in a separate function.
  21722. // this makes it easy compute correct values for closed geometries
  21723. generateUVs();
  21724. // finally create faces
  21725. generateIndices();
  21726. }
  21727. function generateSegment( i ) {
  21728. // we use getPointAt to sample evenly distributed points from the given path
  21729. P = path.getPointAt( i / tubularSegments, P );
  21730. // retrieve corresponding normal and binormal
  21731. const N = frames.normals[ i ];
  21732. const B = frames.binormals[ i ];
  21733. // generate normals and vertices for the current segment
  21734. for ( let j = 0; j <= radialSegments; j ++ ) {
  21735. const v = j / radialSegments * Math.PI * 2;
  21736. const sin = Math.sin( v );
  21737. const cos = - Math.cos( v );
  21738. // normal
  21739. normal.x = ( cos * N.x + sin * B.x );
  21740. normal.y = ( cos * N.y + sin * B.y );
  21741. normal.z = ( cos * N.z + sin * B.z );
  21742. normal.normalize();
  21743. normals.push( normal.x, normal.y, normal.z );
  21744. // vertex
  21745. vertex.x = P.x + radius * normal.x;
  21746. vertex.y = P.y + radius * normal.y;
  21747. vertex.z = P.z + radius * normal.z;
  21748. vertices.push( vertex.x, vertex.y, vertex.z );
  21749. }
  21750. }
  21751. function generateIndices() {
  21752. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21753. for ( let i = 1; i <= radialSegments; i ++ ) {
  21754. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21755. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21756. const c = ( radialSegments + 1 ) * j + i;
  21757. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21758. // faces
  21759. indices.push( a, b, d );
  21760. indices.push( b, c, d );
  21761. }
  21762. }
  21763. }
  21764. function generateUVs() {
  21765. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21766. for ( let j = 0; j <= radialSegments; j ++ ) {
  21767. uv.x = i / tubularSegments;
  21768. uv.y = j / radialSegments;
  21769. uvs.push( uv.x, uv.y );
  21770. }
  21771. }
  21772. }
  21773. }
  21774. toJSON() {
  21775. const data = super.toJSON();
  21776. data.path = this.parameters.path.toJSON();
  21777. return data;
  21778. }
  21779. static fromJSON( data ) {
  21780. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21781. // User defined curves or instances of CurvePath will not be deserialized.
  21782. return new TubeGeometry(
  21783. new Curves[ data.path.type ]().fromJSON( data.path ),
  21784. data.tubularSegments,
  21785. data.radius,
  21786. data.radialSegments,
  21787. data.closed
  21788. );
  21789. }
  21790. }
  21791. class WireframeGeometry extends BufferGeometry {
  21792. constructor( geometry = null ) {
  21793. super();
  21794. this.type = 'WireframeGeometry';
  21795. this.parameters = {
  21796. geometry: geometry
  21797. };
  21798. if ( geometry !== null ) {
  21799. // buffer
  21800. const vertices = [];
  21801. const edges = new Set();
  21802. // helper variables
  21803. const start = new Vector3();
  21804. const end = new Vector3();
  21805. if ( geometry.index !== null ) {
  21806. // indexed BufferGeometry
  21807. const position = geometry.attributes.position;
  21808. const indices = geometry.index;
  21809. let groups = geometry.groups;
  21810. if ( groups.length === 0 ) {
  21811. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  21812. }
  21813. // create a data structure that contains all edges without duplicates
  21814. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21815. const group = groups[ o ];
  21816. const groupStart = group.start;
  21817. const groupCount = group.count;
  21818. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21819. for ( let j = 0; j < 3; j ++ ) {
  21820. const index1 = indices.getX( i + j );
  21821. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21822. start.fromBufferAttribute( position, index1 );
  21823. end.fromBufferAttribute( position, index2 );
  21824. if ( isUniqueEdge( start, end, edges ) === true ) {
  21825. vertices.push( start.x, start.y, start.z );
  21826. vertices.push( end.x, end.y, end.z );
  21827. }
  21828. }
  21829. }
  21830. }
  21831. } else {
  21832. // non-indexed BufferGeometry
  21833. const position = geometry.attributes.position;
  21834. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21835. for ( let j = 0; j < 3; j ++ ) {
  21836. // three edges per triangle, an edge is represented as (index1, index2)
  21837. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21838. const index1 = 3 * i + j;
  21839. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21840. start.fromBufferAttribute( position, index1 );
  21841. end.fromBufferAttribute( position, index2 );
  21842. if ( isUniqueEdge( start, end, edges ) === true ) {
  21843. vertices.push( start.x, start.y, start.z );
  21844. vertices.push( end.x, end.y, end.z );
  21845. }
  21846. }
  21847. }
  21848. }
  21849. // build geometry
  21850. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21851. }
  21852. }
  21853. }
  21854. function isUniqueEdge( start, end, edges ) {
  21855. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21856. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21857. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21858. return false;
  21859. } else {
  21860. edges.add( hash1 );
  21861. edges.add( hash2 );
  21862. return true;
  21863. }
  21864. }
  21865. var Geometries = /*#__PURE__*/Object.freeze({
  21866. __proto__: null,
  21867. BoxGeometry: BoxGeometry,
  21868. CapsuleGeometry: CapsuleGeometry,
  21869. CircleGeometry: CircleGeometry,
  21870. ConeGeometry: ConeGeometry,
  21871. CylinderGeometry: CylinderGeometry,
  21872. DodecahedronGeometry: DodecahedronGeometry,
  21873. EdgesGeometry: EdgesGeometry,
  21874. ExtrudeGeometry: ExtrudeGeometry,
  21875. IcosahedronGeometry: IcosahedronGeometry,
  21876. LatheGeometry: LatheGeometry,
  21877. OctahedronGeometry: OctahedronGeometry,
  21878. PlaneGeometry: PlaneGeometry,
  21879. PolyhedronGeometry: PolyhedronGeometry,
  21880. RingGeometry: RingGeometry,
  21881. ShapeGeometry: ShapeGeometry,
  21882. SphereGeometry: SphereGeometry,
  21883. TetrahedronGeometry: TetrahedronGeometry,
  21884. TorusGeometry: TorusGeometry,
  21885. TorusKnotGeometry: TorusKnotGeometry,
  21886. TubeGeometry: TubeGeometry,
  21887. WireframeGeometry: WireframeGeometry
  21888. });
  21889. class ShadowMaterial extends Material {
  21890. constructor( parameters ) {
  21891. super();
  21892. this.isShadowMaterial = true;
  21893. this.type = 'ShadowMaterial';
  21894. this.color = new Color( 0x000000 );
  21895. this.transparent = true;
  21896. this.fog = true;
  21897. this.setValues( parameters );
  21898. }
  21899. copy( source ) {
  21900. super.copy( source );
  21901. this.color.copy( source.color );
  21902. this.fog = source.fog;
  21903. return this;
  21904. }
  21905. }
  21906. class RawShaderMaterial extends ShaderMaterial {
  21907. constructor( parameters ) {
  21908. super( parameters );
  21909. this.isRawShaderMaterial = true;
  21910. this.type = 'RawShaderMaterial';
  21911. }
  21912. }
  21913. class MeshStandardMaterial extends Material {
  21914. constructor( parameters ) {
  21915. super();
  21916. this.isMeshStandardMaterial = true;
  21917. this.defines = { 'STANDARD': '' };
  21918. this.type = 'MeshStandardMaterial';
  21919. this.color = new Color( 0xffffff ); // diffuse
  21920. this.roughness = 1.0;
  21921. this.metalness = 0.0;
  21922. this.map = null;
  21923. this.lightMap = null;
  21924. this.lightMapIntensity = 1.0;
  21925. this.aoMap = null;
  21926. this.aoMapIntensity = 1.0;
  21927. this.emissive = new Color( 0x000000 );
  21928. this.emissiveIntensity = 1.0;
  21929. this.emissiveMap = null;
  21930. this.bumpMap = null;
  21931. this.bumpScale = 1;
  21932. this.normalMap = null;
  21933. this.normalMapType = TangentSpaceNormalMap;
  21934. this.normalScale = new Vector2( 1, 1 );
  21935. this.displacementMap = null;
  21936. this.displacementScale = 1;
  21937. this.displacementBias = 0;
  21938. this.roughnessMap = null;
  21939. this.metalnessMap = null;
  21940. this.alphaMap = null;
  21941. this.envMap = null;
  21942. this.envMapIntensity = 1.0;
  21943. this.wireframe = false;
  21944. this.wireframeLinewidth = 1;
  21945. this.wireframeLinecap = 'round';
  21946. this.wireframeLinejoin = 'round';
  21947. this.flatShading = false;
  21948. this.fog = true;
  21949. this.setValues( parameters );
  21950. }
  21951. copy( source ) {
  21952. super.copy( source );
  21953. this.defines = { 'STANDARD': '' };
  21954. this.color.copy( source.color );
  21955. this.roughness = source.roughness;
  21956. this.metalness = source.metalness;
  21957. this.map = source.map;
  21958. this.lightMap = source.lightMap;
  21959. this.lightMapIntensity = source.lightMapIntensity;
  21960. this.aoMap = source.aoMap;
  21961. this.aoMapIntensity = source.aoMapIntensity;
  21962. this.emissive.copy( source.emissive );
  21963. this.emissiveMap = source.emissiveMap;
  21964. this.emissiveIntensity = source.emissiveIntensity;
  21965. this.bumpMap = source.bumpMap;
  21966. this.bumpScale = source.bumpScale;
  21967. this.normalMap = source.normalMap;
  21968. this.normalMapType = source.normalMapType;
  21969. this.normalScale.copy( source.normalScale );
  21970. this.displacementMap = source.displacementMap;
  21971. this.displacementScale = source.displacementScale;
  21972. this.displacementBias = source.displacementBias;
  21973. this.roughnessMap = source.roughnessMap;
  21974. this.metalnessMap = source.metalnessMap;
  21975. this.alphaMap = source.alphaMap;
  21976. this.envMap = source.envMap;
  21977. this.envMapIntensity = source.envMapIntensity;
  21978. this.wireframe = source.wireframe;
  21979. this.wireframeLinewidth = source.wireframeLinewidth;
  21980. this.wireframeLinecap = source.wireframeLinecap;
  21981. this.wireframeLinejoin = source.wireframeLinejoin;
  21982. this.flatShading = source.flatShading;
  21983. this.fog = source.fog;
  21984. return this;
  21985. }
  21986. }
  21987. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21988. constructor( parameters ) {
  21989. super();
  21990. this.isMeshPhysicalMaterial = true;
  21991. this.defines = {
  21992. 'STANDARD': '',
  21993. 'PHYSICAL': ''
  21994. };
  21995. this.type = 'MeshPhysicalMaterial';
  21996. this.clearcoatMap = null;
  21997. this.clearcoatRoughness = 0.0;
  21998. this.clearcoatRoughnessMap = null;
  21999. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22000. this.clearcoatNormalMap = null;
  22001. this.ior = 1.5;
  22002. Object.defineProperty( this, 'reflectivity', {
  22003. get: function () {
  22004. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22005. },
  22006. set: function ( reflectivity ) {
  22007. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22008. }
  22009. } );
  22010. this.iridescenceMap = null;
  22011. this.iridescenceIOR = 1.3;
  22012. this.iridescenceThicknessRange = [ 100, 400 ];
  22013. this.iridescenceThicknessMap = null;
  22014. this.sheenColor = new Color( 0x000000 );
  22015. this.sheenColorMap = null;
  22016. this.sheenRoughness = 1.0;
  22017. this.sheenRoughnessMap = null;
  22018. this.transmissionMap = null;
  22019. this.thickness = 0;
  22020. this.thicknessMap = null;
  22021. this.attenuationDistance = Infinity;
  22022. this.attenuationColor = new Color( 1, 1, 1 );
  22023. this.specularIntensity = 1.0;
  22024. this.specularIntensityMap = null;
  22025. this.specularColor = new Color( 1, 1, 1 );
  22026. this.specularColorMap = null;
  22027. this._sheen = 0.0;
  22028. this._clearcoat = 0;
  22029. this._iridescence = 0;
  22030. this._transmission = 0;
  22031. this.setValues( parameters );
  22032. }
  22033. get sheen() {
  22034. return this._sheen;
  22035. }
  22036. set sheen( value ) {
  22037. if ( this._sheen > 0 !== value > 0 ) {
  22038. this.version ++;
  22039. }
  22040. this._sheen = value;
  22041. }
  22042. get clearcoat() {
  22043. return this._clearcoat;
  22044. }
  22045. set clearcoat( value ) {
  22046. if ( this._clearcoat > 0 !== value > 0 ) {
  22047. this.version ++;
  22048. }
  22049. this._clearcoat = value;
  22050. }
  22051. get iridescence() {
  22052. return this._iridescence;
  22053. }
  22054. set iridescence( value ) {
  22055. if ( this._iridescence > 0 !== value > 0 ) {
  22056. this.version ++;
  22057. }
  22058. this._iridescence = value;
  22059. }
  22060. get transmission() {
  22061. return this._transmission;
  22062. }
  22063. set transmission( value ) {
  22064. if ( this._transmission > 0 !== value > 0 ) {
  22065. this.version ++;
  22066. }
  22067. this._transmission = value;
  22068. }
  22069. copy( source ) {
  22070. super.copy( source );
  22071. this.defines = {
  22072. 'STANDARD': '',
  22073. 'PHYSICAL': ''
  22074. };
  22075. this.clearcoat = source.clearcoat;
  22076. this.clearcoatMap = source.clearcoatMap;
  22077. this.clearcoatRoughness = source.clearcoatRoughness;
  22078. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22079. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22080. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22081. this.ior = source.ior;
  22082. this.iridescence = source.iridescence;
  22083. this.iridescenceMap = source.iridescenceMap;
  22084. this.iridescenceIOR = source.iridescenceIOR;
  22085. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22086. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22087. this.sheen = source.sheen;
  22088. this.sheenColor.copy( source.sheenColor );
  22089. this.sheenColorMap = source.sheenColorMap;
  22090. this.sheenRoughness = source.sheenRoughness;
  22091. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22092. this.transmission = source.transmission;
  22093. this.transmissionMap = source.transmissionMap;
  22094. this.thickness = source.thickness;
  22095. this.thicknessMap = source.thicknessMap;
  22096. this.attenuationDistance = source.attenuationDistance;
  22097. this.attenuationColor.copy( source.attenuationColor );
  22098. this.specularIntensity = source.specularIntensity;
  22099. this.specularIntensityMap = source.specularIntensityMap;
  22100. this.specularColor.copy( source.specularColor );
  22101. this.specularColorMap = source.specularColorMap;
  22102. return this;
  22103. }
  22104. }
  22105. class MeshPhongMaterial extends Material {
  22106. constructor( parameters ) {
  22107. super();
  22108. this.isMeshPhongMaterial = true;
  22109. this.type = 'MeshPhongMaterial';
  22110. this.color = new Color( 0xffffff ); // diffuse
  22111. this.specular = new Color( 0x111111 );
  22112. this.shininess = 30;
  22113. this.map = null;
  22114. this.lightMap = null;
  22115. this.lightMapIntensity = 1.0;
  22116. this.aoMap = null;
  22117. this.aoMapIntensity = 1.0;
  22118. this.emissive = new Color( 0x000000 );
  22119. this.emissiveIntensity = 1.0;
  22120. this.emissiveMap = null;
  22121. this.bumpMap = null;
  22122. this.bumpScale = 1;
  22123. this.normalMap = null;
  22124. this.normalMapType = TangentSpaceNormalMap;
  22125. this.normalScale = new Vector2( 1, 1 );
  22126. this.displacementMap = null;
  22127. this.displacementScale = 1;
  22128. this.displacementBias = 0;
  22129. this.specularMap = null;
  22130. this.alphaMap = null;
  22131. this.envMap = null;
  22132. this.combine = MultiplyOperation;
  22133. this.reflectivity = 1;
  22134. this.refractionRatio = 0.98;
  22135. this.wireframe = false;
  22136. this.wireframeLinewidth = 1;
  22137. this.wireframeLinecap = 'round';
  22138. this.wireframeLinejoin = 'round';
  22139. this.flatShading = false;
  22140. this.fog = true;
  22141. this.setValues( parameters );
  22142. }
  22143. copy( source ) {
  22144. super.copy( source );
  22145. this.color.copy( source.color );
  22146. this.specular.copy( source.specular );
  22147. this.shininess = source.shininess;
  22148. this.map = source.map;
  22149. this.lightMap = source.lightMap;
  22150. this.lightMapIntensity = source.lightMapIntensity;
  22151. this.aoMap = source.aoMap;
  22152. this.aoMapIntensity = source.aoMapIntensity;
  22153. this.emissive.copy( source.emissive );
  22154. this.emissiveMap = source.emissiveMap;
  22155. this.emissiveIntensity = source.emissiveIntensity;
  22156. this.bumpMap = source.bumpMap;
  22157. this.bumpScale = source.bumpScale;
  22158. this.normalMap = source.normalMap;
  22159. this.normalMapType = source.normalMapType;
  22160. this.normalScale.copy( source.normalScale );
  22161. this.displacementMap = source.displacementMap;
  22162. this.displacementScale = source.displacementScale;
  22163. this.displacementBias = source.displacementBias;
  22164. this.specularMap = source.specularMap;
  22165. this.alphaMap = source.alphaMap;
  22166. this.envMap = source.envMap;
  22167. this.combine = source.combine;
  22168. this.reflectivity = source.reflectivity;
  22169. this.refractionRatio = source.refractionRatio;
  22170. this.wireframe = source.wireframe;
  22171. this.wireframeLinewidth = source.wireframeLinewidth;
  22172. this.wireframeLinecap = source.wireframeLinecap;
  22173. this.wireframeLinejoin = source.wireframeLinejoin;
  22174. this.flatShading = source.flatShading;
  22175. this.fog = source.fog;
  22176. return this;
  22177. }
  22178. }
  22179. class MeshToonMaterial extends Material {
  22180. constructor( parameters ) {
  22181. super();
  22182. this.isMeshToonMaterial = true;
  22183. this.defines = { 'TOON': '' };
  22184. this.type = 'MeshToonMaterial';
  22185. this.color = new Color( 0xffffff );
  22186. this.map = null;
  22187. this.gradientMap = null;
  22188. this.lightMap = null;
  22189. this.lightMapIntensity = 1.0;
  22190. this.aoMap = null;
  22191. this.aoMapIntensity = 1.0;
  22192. this.emissive = new Color( 0x000000 );
  22193. this.emissiveIntensity = 1.0;
  22194. this.emissiveMap = null;
  22195. this.bumpMap = null;
  22196. this.bumpScale = 1;
  22197. this.normalMap = null;
  22198. this.normalMapType = TangentSpaceNormalMap;
  22199. this.normalScale = new Vector2( 1, 1 );
  22200. this.displacementMap = null;
  22201. this.displacementScale = 1;
  22202. this.displacementBias = 0;
  22203. this.alphaMap = null;
  22204. this.wireframe = false;
  22205. this.wireframeLinewidth = 1;
  22206. this.wireframeLinecap = 'round';
  22207. this.wireframeLinejoin = 'round';
  22208. this.fog = true;
  22209. this.setValues( parameters );
  22210. }
  22211. copy( source ) {
  22212. super.copy( source );
  22213. this.color.copy( source.color );
  22214. this.map = source.map;
  22215. this.gradientMap = source.gradientMap;
  22216. this.lightMap = source.lightMap;
  22217. this.lightMapIntensity = source.lightMapIntensity;
  22218. this.aoMap = source.aoMap;
  22219. this.aoMapIntensity = source.aoMapIntensity;
  22220. this.emissive.copy( source.emissive );
  22221. this.emissiveMap = source.emissiveMap;
  22222. this.emissiveIntensity = source.emissiveIntensity;
  22223. this.bumpMap = source.bumpMap;
  22224. this.bumpScale = source.bumpScale;
  22225. this.normalMap = source.normalMap;
  22226. this.normalMapType = source.normalMapType;
  22227. this.normalScale.copy( source.normalScale );
  22228. this.displacementMap = source.displacementMap;
  22229. this.displacementScale = source.displacementScale;
  22230. this.displacementBias = source.displacementBias;
  22231. this.alphaMap = source.alphaMap;
  22232. this.wireframe = source.wireframe;
  22233. this.wireframeLinewidth = source.wireframeLinewidth;
  22234. this.wireframeLinecap = source.wireframeLinecap;
  22235. this.wireframeLinejoin = source.wireframeLinejoin;
  22236. this.fog = source.fog;
  22237. return this;
  22238. }
  22239. }
  22240. class MeshNormalMaterial extends Material {
  22241. constructor( parameters ) {
  22242. super();
  22243. this.isMeshNormalMaterial = true;
  22244. this.type = 'MeshNormalMaterial';
  22245. this.bumpMap = null;
  22246. this.bumpScale = 1;
  22247. this.normalMap = null;
  22248. this.normalMapType = TangentSpaceNormalMap;
  22249. this.normalScale = new Vector2( 1, 1 );
  22250. this.displacementMap = null;
  22251. this.displacementScale = 1;
  22252. this.displacementBias = 0;
  22253. this.wireframe = false;
  22254. this.wireframeLinewidth = 1;
  22255. this.flatShading = false;
  22256. this.setValues( parameters );
  22257. }
  22258. copy( source ) {
  22259. super.copy( source );
  22260. this.bumpMap = source.bumpMap;
  22261. this.bumpScale = source.bumpScale;
  22262. this.normalMap = source.normalMap;
  22263. this.normalMapType = source.normalMapType;
  22264. this.normalScale.copy( source.normalScale );
  22265. this.displacementMap = source.displacementMap;
  22266. this.displacementScale = source.displacementScale;
  22267. this.displacementBias = source.displacementBias;
  22268. this.wireframe = source.wireframe;
  22269. this.wireframeLinewidth = source.wireframeLinewidth;
  22270. this.flatShading = source.flatShading;
  22271. return this;
  22272. }
  22273. }
  22274. class MeshLambertMaterial extends Material {
  22275. constructor( parameters ) {
  22276. super();
  22277. this.isMeshLambertMaterial = true;
  22278. this.type = 'MeshLambertMaterial';
  22279. this.color = new Color( 0xffffff ); // diffuse
  22280. this.map = null;
  22281. this.lightMap = null;
  22282. this.lightMapIntensity = 1.0;
  22283. this.aoMap = null;
  22284. this.aoMapIntensity = 1.0;
  22285. this.emissive = new Color( 0x000000 );
  22286. this.emissiveIntensity = 1.0;
  22287. this.emissiveMap = null;
  22288. this.bumpMap = null;
  22289. this.bumpScale = 1;
  22290. this.normalMap = null;
  22291. this.normalMapType = TangentSpaceNormalMap;
  22292. this.normalScale = new Vector2( 1, 1 );
  22293. this.displacementMap = null;
  22294. this.displacementScale = 1;
  22295. this.displacementBias = 0;
  22296. this.specularMap = null;
  22297. this.alphaMap = null;
  22298. this.envMap = null;
  22299. this.combine = MultiplyOperation;
  22300. this.reflectivity = 1;
  22301. this.refractionRatio = 0.98;
  22302. this.wireframe = false;
  22303. this.wireframeLinewidth = 1;
  22304. this.wireframeLinecap = 'round';
  22305. this.wireframeLinejoin = 'round';
  22306. this.flatShading = false;
  22307. this.fog = true;
  22308. this.setValues( parameters );
  22309. }
  22310. copy( source ) {
  22311. super.copy( source );
  22312. this.color.copy( source.color );
  22313. this.map = source.map;
  22314. this.lightMap = source.lightMap;
  22315. this.lightMapIntensity = source.lightMapIntensity;
  22316. this.aoMap = source.aoMap;
  22317. this.aoMapIntensity = source.aoMapIntensity;
  22318. this.emissive.copy( source.emissive );
  22319. this.emissiveMap = source.emissiveMap;
  22320. this.emissiveIntensity = source.emissiveIntensity;
  22321. this.bumpMap = source.bumpMap;
  22322. this.bumpScale = source.bumpScale;
  22323. this.normalMap = source.normalMap;
  22324. this.normalMapType = source.normalMapType;
  22325. this.normalScale.copy( source.normalScale );
  22326. this.displacementMap = source.displacementMap;
  22327. this.displacementScale = source.displacementScale;
  22328. this.displacementBias = source.displacementBias;
  22329. this.specularMap = source.specularMap;
  22330. this.alphaMap = source.alphaMap;
  22331. this.envMap = source.envMap;
  22332. this.combine = source.combine;
  22333. this.reflectivity = source.reflectivity;
  22334. this.refractionRatio = source.refractionRatio;
  22335. this.wireframe = source.wireframe;
  22336. this.wireframeLinewidth = source.wireframeLinewidth;
  22337. this.wireframeLinecap = source.wireframeLinecap;
  22338. this.wireframeLinejoin = source.wireframeLinejoin;
  22339. this.flatShading = source.flatShading;
  22340. this.fog = source.fog;
  22341. return this;
  22342. }
  22343. }
  22344. class MeshMatcapMaterial extends Material {
  22345. constructor( parameters ) {
  22346. super();
  22347. this.isMeshMatcapMaterial = true;
  22348. this.defines = { 'MATCAP': '' };
  22349. this.type = 'MeshMatcapMaterial';
  22350. this.color = new Color( 0xffffff ); // diffuse
  22351. this.matcap = null;
  22352. this.map = null;
  22353. this.bumpMap = null;
  22354. this.bumpScale = 1;
  22355. this.normalMap = null;
  22356. this.normalMapType = TangentSpaceNormalMap;
  22357. this.normalScale = new Vector2( 1, 1 );
  22358. this.displacementMap = null;
  22359. this.displacementScale = 1;
  22360. this.displacementBias = 0;
  22361. this.alphaMap = null;
  22362. this.flatShading = false;
  22363. this.fog = true;
  22364. this.setValues( parameters );
  22365. }
  22366. copy( source ) {
  22367. super.copy( source );
  22368. this.defines = { 'MATCAP': '' };
  22369. this.color.copy( source.color );
  22370. this.matcap = source.matcap;
  22371. this.map = source.map;
  22372. this.bumpMap = source.bumpMap;
  22373. this.bumpScale = source.bumpScale;
  22374. this.normalMap = source.normalMap;
  22375. this.normalMapType = source.normalMapType;
  22376. this.normalScale.copy( source.normalScale );
  22377. this.displacementMap = source.displacementMap;
  22378. this.displacementScale = source.displacementScale;
  22379. this.displacementBias = source.displacementBias;
  22380. this.alphaMap = source.alphaMap;
  22381. this.flatShading = source.flatShading;
  22382. this.fog = source.fog;
  22383. return this;
  22384. }
  22385. }
  22386. class LineDashedMaterial extends LineBasicMaterial {
  22387. constructor( parameters ) {
  22388. super();
  22389. this.isLineDashedMaterial = true;
  22390. this.type = 'LineDashedMaterial';
  22391. this.scale = 1;
  22392. this.dashSize = 3;
  22393. this.gapSize = 1;
  22394. this.setValues( parameters );
  22395. }
  22396. copy( source ) {
  22397. super.copy( source );
  22398. this.scale = source.scale;
  22399. this.dashSize = source.dashSize;
  22400. this.gapSize = source.gapSize;
  22401. return this;
  22402. }
  22403. }
  22404. // same as Array.prototype.slice, but also works on typed arrays
  22405. function arraySlice( array, from, to ) {
  22406. if ( isTypedArray( array ) ) {
  22407. // in ios9 array.subarray(from, undefined) will return empty array
  22408. // but array.subarray(from) or array.subarray(from, len) is correct
  22409. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22410. }
  22411. return array.slice( from, to );
  22412. }
  22413. // converts an array to a specific type
  22414. function convertArray( array, type, forceClone ) {
  22415. if ( ! array || // let 'undefined' and 'null' pass
  22416. ! forceClone && array.constructor === type ) return array;
  22417. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22418. return new type( array ); // create typed array
  22419. }
  22420. return Array.prototype.slice.call( array ); // create Array
  22421. }
  22422. function isTypedArray( object ) {
  22423. return ArrayBuffer.isView( object ) &&
  22424. ! ( object instanceof DataView );
  22425. }
  22426. // returns an array by which times and values can be sorted
  22427. function getKeyframeOrder( times ) {
  22428. function compareTime( i, j ) {
  22429. return times[ i ] - times[ j ];
  22430. }
  22431. const n = times.length;
  22432. const result = new Array( n );
  22433. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22434. result.sort( compareTime );
  22435. return result;
  22436. }
  22437. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22438. function sortedArray( values, stride, order ) {
  22439. const nValues = values.length;
  22440. const result = new values.constructor( nValues );
  22441. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22442. const srcOffset = order[ i ] * stride;
  22443. for ( let j = 0; j !== stride; ++ j ) {
  22444. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22445. }
  22446. }
  22447. return result;
  22448. }
  22449. // function for parsing AOS keyframe formats
  22450. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22451. let i = 1, key = jsonKeys[ 0 ];
  22452. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22453. key = jsonKeys[ i ++ ];
  22454. }
  22455. if ( key === undefined ) return; // no data
  22456. let value = key[ valuePropertyName ];
  22457. if ( value === undefined ) return; // no data
  22458. if ( Array.isArray( value ) ) {
  22459. do {
  22460. value = key[ valuePropertyName ];
  22461. if ( value !== undefined ) {
  22462. times.push( key.time );
  22463. values.push.apply( values, value ); // push all elements
  22464. }
  22465. key = jsonKeys[ i ++ ];
  22466. } while ( key !== undefined );
  22467. } else if ( value.toArray !== undefined ) {
  22468. // ...assume THREE.Math-ish
  22469. do {
  22470. value = key[ valuePropertyName ];
  22471. if ( value !== undefined ) {
  22472. times.push( key.time );
  22473. value.toArray( values, values.length );
  22474. }
  22475. key = jsonKeys[ i ++ ];
  22476. } while ( key !== undefined );
  22477. } else {
  22478. // otherwise push as-is
  22479. do {
  22480. value = key[ valuePropertyName ];
  22481. if ( value !== undefined ) {
  22482. times.push( key.time );
  22483. values.push( value );
  22484. }
  22485. key = jsonKeys[ i ++ ];
  22486. } while ( key !== undefined );
  22487. }
  22488. }
  22489. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22490. const clip = sourceClip.clone();
  22491. clip.name = name;
  22492. const tracks = [];
  22493. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22494. const track = clip.tracks[ i ];
  22495. const valueSize = track.getValueSize();
  22496. const times = [];
  22497. const values = [];
  22498. for ( let j = 0; j < track.times.length; ++ j ) {
  22499. const frame = track.times[ j ] * fps;
  22500. if ( frame < startFrame || frame >= endFrame ) continue;
  22501. times.push( track.times[ j ] );
  22502. for ( let k = 0; k < valueSize; ++ k ) {
  22503. values.push( track.values[ j * valueSize + k ] );
  22504. }
  22505. }
  22506. if ( times.length === 0 ) continue;
  22507. track.times = convertArray( times, track.times.constructor );
  22508. track.values = convertArray( values, track.values.constructor );
  22509. tracks.push( track );
  22510. }
  22511. clip.tracks = tracks;
  22512. // find minimum .times value across all tracks in the trimmed clip
  22513. let minStartTime = Infinity;
  22514. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22515. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22516. minStartTime = clip.tracks[ i ].times[ 0 ];
  22517. }
  22518. }
  22519. // shift all tracks such that clip begins at t=0
  22520. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22521. clip.tracks[ i ].shift( - 1 * minStartTime );
  22522. }
  22523. clip.resetDuration();
  22524. return clip;
  22525. }
  22526. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22527. if ( fps <= 0 ) fps = 30;
  22528. const numTracks = referenceClip.tracks.length;
  22529. const referenceTime = referenceFrame / fps;
  22530. // Make each track's values relative to the values at the reference frame
  22531. for ( let i = 0; i < numTracks; ++ i ) {
  22532. const referenceTrack = referenceClip.tracks[ i ];
  22533. const referenceTrackType = referenceTrack.ValueTypeName;
  22534. // Skip this track if it's non-numeric
  22535. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22536. // Find the track in the target clip whose name and type matches the reference track
  22537. const targetTrack = targetClip.tracks.find( function ( track ) {
  22538. return track.name === referenceTrack.name
  22539. && track.ValueTypeName === referenceTrackType;
  22540. } );
  22541. if ( targetTrack === undefined ) continue;
  22542. let referenceOffset = 0;
  22543. const referenceValueSize = referenceTrack.getValueSize();
  22544. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22545. referenceOffset = referenceValueSize / 3;
  22546. }
  22547. let targetOffset = 0;
  22548. const targetValueSize = targetTrack.getValueSize();
  22549. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22550. targetOffset = targetValueSize / 3;
  22551. }
  22552. const lastIndex = referenceTrack.times.length - 1;
  22553. let referenceValue;
  22554. // Find the value to subtract out of the track
  22555. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22556. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22557. const startIndex = referenceOffset;
  22558. const endIndex = referenceValueSize - referenceOffset;
  22559. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22560. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22561. // Reference frame is after the last keyframe, so just use the last keyframe
  22562. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22563. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22564. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22565. } else {
  22566. // Interpolate to the reference value
  22567. const interpolant = referenceTrack.createInterpolant();
  22568. const startIndex = referenceOffset;
  22569. const endIndex = referenceValueSize - referenceOffset;
  22570. interpolant.evaluate( referenceTime );
  22571. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22572. }
  22573. // Conjugate the quaternion
  22574. if ( referenceTrackType === 'quaternion' ) {
  22575. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22576. referenceQuat.toArray( referenceValue );
  22577. }
  22578. // Subtract the reference value from all of the track values
  22579. const numTimes = targetTrack.times.length;
  22580. for ( let j = 0; j < numTimes; ++ j ) {
  22581. const valueStart = j * targetValueSize + targetOffset;
  22582. if ( referenceTrackType === 'quaternion' ) {
  22583. // Multiply the conjugate for quaternion track types
  22584. Quaternion.multiplyQuaternionsFlat(
  22585. targetTrack.values,
  22586. valueStart,
  22587. referenceValue,
  22588. 0,
  22589. targetTrack.values,
  22590. valueStart
  22591. );
  22592. } else {
  22593. const valueEnd = targetValueSize - targetOffset * 2;
  22594. // Subtract each value for all other numeric track types
  22595. for ( let k = 0; k < valueEnd; ++ k ) {
  22596. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22597. }
  22598. }
  22599. }
  22600. }
  22601. targetClip.blendMode = AdditiveAnimationBlendMode;
  22602. return targetClip;
  22603. }
  22604. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22605. __proto__: null,
  22606. arraySlice: arraySlice,
  22607. convertArray: convertArray,
  22608. isTypedArray: isTypedArray,
  22609. getKeyframeOrder: getKeyframeOrder,
  22610. sortedArray: sortedArray,
  22611. flattenJSON: flattenJSON,
  22612. subclip: subclip,
  22613. makeClipAdditive: makeClipAdditive
  22614. });
  22615. /**
  22616. * Abstract base class of interpolants over parametric samples.
  22617. *
  22618. * The parameter domain is one dimensional, typically the time or a path
  22619. * along a curve defined by the data.
  22620. *
  22621. * The sample values can have any dimensionality and derived classes may
  22622. * apply special interpretations to the data.
  22623. *
  22624. * This class provides the interval seek in a Template Method, deferring
  22625. * the actual interpolation to derived classes.
  22626. *
  22627. * Time complexity is O(1) for linear access crossing at most two points
  22628. * and O(log N) for random access, where N is the number of positions.
  22629. *
  22630. * References:
  22631. *
  22632. * http://www.oodesign.com/template-method-pattern.html
  22633. *
  22634. */
  22635. class Interpolant {
  22636. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22637. this.parameterPositions = parameterPositions;
  22638. this._cachedIndex = 0;
  22639. this.resultBuffer = resultBuffer !== undefined ?
  22640. resultBuffer : new sampleValues.constructor( sampleSize );
  22641. this.sampleValues = sampleValues;
  22642. this.valueSize = sampleSize;
  22643. this.settings = null;
  22644. this.DefaultSettings_ = {};
  22645. }
  22646. evaluate( t ) {
  22647. const pp = this.parameterPositions;
  22648. let i1 = this._cachedIndex,
  22649. t1 = pp[ i1 ],
  22650. t0 = pp[ i1 - 1 ];
  22651. validate_interval: {
  22652. seek: {
  22653. let right;
  22654. linear_scan: {
  22655. //- See http://jsperf.com/comparison-to-undefined/3
  22656. //- slower code:
  22657. //-
  22658. //- if ( t >= t1 || t1 === undefined ) {
  22659. forward_scan: if ( ! ( t < t1 ) ) {
  22660. for ( let giveUpAt = i1 + 2; ; ) {
  22661. if ( t1 === undefined ) {
  22662. if ( t < t0 ) break forward_scan;
  22663. // after end
  22664. i1 = pp.length;
  22665. this._cachedIndex = i1;
  22666. return this.copySampleValue_( i1 - 1 );
  22667. }
  22668. if ( i1 === giveUpAt ) break; // this loop
  22669. t0 = t1;
  22670. t1 = pp[ ++ i1 ];
  22671. if ( t < t1 ) {
  22672. // we have arrived at the sought interval
  22673. break seek;
  22674. }
  22675. }
  22676. // prepare binary search on the right side of the index
  22677. right = pp.length;
  22678. break linear_scan;
  22679. }
  22680. //- slower code:
  22681. //- if ( t < t0 || t0 === undefined ) {
  22682. if ( ! ( t >= t0 ) ) {
  22683. // looping?
  22684. const t1global = pp[ 1 ];
  22685. if ( t < t1global ) {
  22686. i1 = 2; // + 1, using the scan for the details
  22687. t0 = t1global;
  22688. }
  22689. // linear reverse scan
  22690. for ( let giveUpAt = i1 - 2; ; ) {
  22691. if ( t0 === undefined ) {
  22692. // before start
  22693. this._cachedIndex = 0;
  22694. return this.copySampleValue_( 0 );
  22695. }
  22696. if ( i1 === giveUpAt ) break; // this loop
  22697. t1 = t0;
  22698. t0 = pp[ -- i1 - 1 ];
  22699. if ( t >= t0 ) {
  22700. // we have arrived at the sought interval
  22701. break seek;
  22702. }
  22703. }
  22704. // prepare binary search on the left side of the index
  22705. right = i1;
  22706. i1 = 0;
  22707. break linear_scan;
  22708. }
  22709. // the interval is valid
  22710. break validate_interval;
  22711. } // linear scan
  22712. // binary search
  22713. while ( i1 < right ) {
  22714. const mid = ( i1 + right ) >>> 1;
  22715. if ( t < pp[ mid ] ) {
  22716. right = mid;
  22717. } else {
  22718. i1 = mid + 1;
  22719. }
  22720. }
  22721. t1 = pp[ i1 ];
  22722. t0 = pp[ i1 - 1 ];
  22723. // check boundary cases, again
  22724. if ( t0 === undefined ) {
  22725. this._cachedIndex = 0;
  22726. return this.copySampleValue_( 0 );
  22727. }
  22728. if ( t1 === undefined ) {
  22729. i1 = pp.length;
  22730. this._cachedIndex = i1;
  22731. return this.copySampleValue_( i1 - 1 );
  22732. }
  22733. } // seek
  22734. this._cachedIndex = i1;
  22735. this.intervalChanged_( i1, t0, t1 );
  22736. } // validate_interval
  22737. return this.interpolate_( i1, t0, t, t1 );
  22738. }
  22739. getSettings_() {
  22740. return this.settings || this.DefaultSettings_;
  22741. }
  22742. copySampleValue_( index ) {
  22743. // copies a sample value to the result buffer
  22744. const result = this.resultBuffer,
  22745. values = this.sampleValues,
  22746. stride = this.valueSize,
  22747. offset = index * stride;
  22748. for ( let i = 0; i !== stride; ++ i ) {
  22749. result[ i ] = values[ offset + i ];
  22750. }
  22751. return result;
  22752. }
  22753. // Template methods for derived classes:
  22754. interpolate_( /* i1, t0, t, t1 */ ) {
  22755. throw new Error( 'call to abstract method' );
  22756. // implementations shall return this.resultBuffer
  22757. }
  22758. intervalChanged_( /* i1, t0, t1 */ ) {
  22759. // empty
  22760. }
  22761. }
  22762. /**
  22763. * Fast and simple cubic spline interpolant.
  22764. *
  22765. * It was derived from a Hermitian construction setting the first derivative
  22766. * at each sample position to the linear slope between neighboring positions
  22767. * over their parameter interval.
  22768. */
  22769. class CubicInterpolant extends Interpolant {
  22770. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22771. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22772. this._weightPrev = - 0;
  22773. this._offsetPrev = - 0;
  22774. this._weightNext = - 0;
  22775. this._offsetNext = - 0;
  22776. this.DefaultSettings_ = {
  22777. endingStart: ZeroCurvatureEnding,
  22778. endingEnd: ZeroCurvatureEnding
  22779. };
  22780. }
  22781. intervalChanged_( i1, t0, t1 ) {
  22782. const pp = this.parameterPositions;
  22783. let iPrev = i1 - 2,
  22784. iNext = i1 + 1,
  22785. tPrev = pp[ iPrev ],
  22786. tNext = pp[ iNext ];
  22787. if ( tPrev === undefined ) {
  22788. switch ( this.getSettings_().endingStart ) {
  22789. case ZeroSlopeEnding:
  22790. // f'(t0) = 0
  22791. iPrev = i1;
  22792. tPrev = 2 * t0 - t1;
  22793. break;
  22794. case WrapAroundEnding:
  22795. // use the other end of the curve
  22796. iPrev = pp.length - 2;
  22797. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22798. break;
  22799. default: // ZeroCurvatureEnding
  22800. // f''(t0) = 0 a.k.a. Natural Spline
  22801. iPrev = i1;
  22802. tPrev = t1;
  22803. }
  22804. }
  22805. if ( tNext === undefined ) {
  22806. switch ( this.getSettings_().endingEnd ) {
  22807. case ZeroSlopeEnding:
  22808. // f'(tN) = 0
  22809. iNext = i1;
  22810. tNext = 2 * t1 - t0;
  22811. break;
  22812. case WrapAroundEnding:
  22813. // use the other end of the curve
  22814. iNext = 1;
  22815. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22816. break;
  22817. default: // ZeroCurvatureEnding
  22818. // f''(tN) = 0, a.k.a. Natural Spline
  22819. iNext = i1 - 1;
  22820. tNext = t0;
  22821. }
  22822. }
  22823. const halfDt = ( t1 - t0 ) * 0.5,
  22824. stride = this.valueSize;
  22825. this._weightPrev = halfDt / ( t0 - tPrev );
  22826. this._weightNext = halfDt / ( tNext - t1 );
  22827. this._offsetPrev = iPrev * stride;
  22828. this._offsetNext = iNext * stride;
  22829. }
  22830. interpolate_( i1, t0, t, t1 ) {
  22831. const result = this.resultBuffer,
  22832. values = this.sampleValues,
  22833. stride = this.valueSize,
  22834. o1 = i1 * stride, o0 = o1 - stride,
  22835. oP = this._offsetPrev, oN = this._offsetNext,
  22836. wP = this._weightPrev, wN = this._weightNext,
  22837. p = ( t - t0 ) / ( t1 - t0 ),
  22838. pp = p * p,
  22839. ppp = pp * p;
  22840. // evaluate polynomials
  22841. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  22842. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  22843. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22844. const sN = wN * ppp - wN * pp;
  22845. // combine data linearly
  22846. for ( let i = 0; i !== stride; ++ i ) {
  22847. result[ i ] =
  22848. sP * values[ oP + i ] +
  22849. s0 * values[ o0 + i ] +
  22850. s1 * values[ o1 + i ] +
  22851. sN * values[ oN + i ];
  22852. }
  22853. return result;
  22854. }
  22855. }
  22856. class LinearInterpolant extends Interpolant {
  22857. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22858. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22859. }
  22860. interpolate_( i1, t0, t, t1 ) {
  22861. const result = this.resultBuffer,
  22862. values = this.sampleValues,
  22863. stride = this.valueSize,
  22864. offset1 = i1 * stride,
  22865. offset0 = offset1 - stride,
  22866. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22867. weight0 = 1 - weight1;
  22868. for ( let i = 0; i !== stride; ++ i ) {
  22869. result[ i ] =
  22870. values[ offset0 + i ] * weight0 +
  22871. values[ offset1 + i ] * weight1;
  22872. }
  22873. return result;
  22874. }
  22875. }
  22876. /**
  22877. *
  22878. * Interpolant that evaluates to the sample value at the position preceding
  22879. * the parameter.
  22880. */
  22881. class DiscreteInterpolant extends Interpolant {
  22882. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22883. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22884. }
  22885. interpolate_( i1 /*, t0, t, t1 */ ) {
  22886. return this.copySampleValue_( i1 - 1 );
  22887. }
  22888. }
  22889. class KeyframeTrack {
  22890. constructor( name, times, values, interpolation ) {
  22891. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22892. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22893. this.name = name;
  22894. this.times = convertArray( times, this.TimeBufferType );
  22895. this.values = convertArray( values, this.ValueBufferType );
  22896. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22897. }
  22898. // Serialization (in static context, because of constructor invocation
  22899. // and automatic invocation of .toJSON):
  22900. static toJSON( track ) {
  22901. const trackType = track.constructor;
  22902. let json;
  22903. // derived classes can define a static toJSON method
  22904. if ( trackType.toJSON !== this.toJSON ) {
  22905. json = trackType.toJSON( track );
  22906. } else {
  22907. // by default, we assume the data can be serialized as-is
  22908. json = {
  22909. 'name': track.name,
  22910. 'times': convertArray( track.times, Array ),
  22911. 'values': convertArray( track.values, Array )
  22912. };
  22913. const interpolation = track.getInterpolation();
  22914. if ( interpolation !== track.DefaultInterpolation ) {
  22915. json.interpolation = interpolation;
  22916. }
  22917. }
  22918. json.type = track.ValueTypeName; // mandatory
  22919. return json;
  22920. }
  22921. InterpolantFactoryMethodDiscrete( result ) {
  22922. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22923. }
  22924. InterpolantFactoryMethodLinear( result ) {
  22925. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22926. }
  22927. InterpolantFactoryMethodSmooth( result ) {
  22928. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22929. }
  22930. setInterpolation( interpolation ) {
  22931. let factoryMethod;
  22932. switch ( interpolation ) {
  22933. case InterpolateDiscrete:
  22934. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22935. break;
  22936. case InterpolateLinear:
  22937. factoryMethod = this.InterpolantFactoryMethodLinear;
  22938. break;
  22939. case InterpolateSmooth:
  22940. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22941. break;
  22942. }
  22943. if ( factoryMethod === undefined ) {
  22944. const message = 'unsupported interpolation for ' +
  22945. this.ValueTypeName + ' keyframe track named ' + this.name;
  22946. if ( this.createInterpolant === undefined ) {
  22947. // fall back to default, unless the default itself is messed up
  22948. if ( interpolation !== this.DefaultInterpolation ) {
  22949. this.setInterpolation( this.DefaultInterpolation );
  22950. } else {
  22951. throw new Error( message ); // fatal, in this case
  22952. }
  22953. }
  22954. console.warn( 'THREE.KeyframeTrack:', message );
  22955. return this;
  22956. }
  22957. this.createInterpolant = factoryMethod;
  22958. return this;
  22959. }
  22960. getInterpolation() {
  22961. switch ( this.createInterpolant ) {
  22962. case this.InterpolantFactoryMethodDiscrete:
  22963. return InterpolateDiscrete;
  22964. case this.InterpolantFactoryMethodLinear:
  22965. return InterpolateLinear;
  22966. case this.InterpolantFactoryMethodSmooth:
  22967. return InterpolateSmooth;
  22968. }
  22969. }
  22970. getValueSize() {
  22971. return this.values.length / this.times.length;
  22972. }
  22973. // move all keyframes either forwards or backwards in time
  22974. shift( timeOffset ) {
  22975. if ( timeOffset !== 0.0 ) {
  22976. const times = this.times;
  22977. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22978. times[ i ] += timeOffset;
  22979. }
  22980. }
  22981. return this;
  22982. }
  22983. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22984. scale( timeScale ) {
  22985. if ( timeScale !== 1.0 ) {
  22986. const times = this.times;
  22987. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22988. times[ i ] *= timeScale;
  22989. }
  22990. }
  22991. return this;
  22992. }
  22993. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22994. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22995. trim( startTime, endTime ) {
  22996. const times = this.times,
  22997. nKeys = times.length;
  22998. let from = 0,
  22999. to = nKeys - 1;
  23000. while ( from !== nKeys && times[ from ] < startTime ) {
  23001. ++ from;
  23002. }
  23003. while ( to !== - 1 && times[ to ] > endTime ) {
  23004. -- to;
  23005. }
  23006. ++ to; // inclusive -> exclusive bound
  23007. if ( from !== 0 || to !== nKeys ) {
  23008. // empty tracks are forbidden, so keep at least one keyframe
  23009. if ( from >= to ) {
  23010. to = Math.max( to, 1 );
  23011. from = to - 1;
  23012. }
  23013. const stride = this.getValueSize();
  23014. this.times = arraySlice( times, from, to );
  23015. this.values = arraySlice( this.values, from * stride, to * stride );
  23016. }
  23017. return this;
  23018. }
  23019. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23020. validate() {
  23021. let valid = true;
  23022. const valueSize = this.getValueSize();
  23023. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23024. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23025. valid = false;
  23026. }
  23027. const times = this.times,
  23028. values = this.values,
  23029. nKeys = times.length;
  23030. if ( nKeys === 0 ) {
  23031. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23032. valid = false;
  23033. }
  23034. let prevTime = null;
  23035. for ( let i = 0; i !== nKeys; i ++ ) {
  23036. const currTime = times[ i ];
  23037. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23038. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23039. valid = false;
  23040. break;
  23041. }
  23042. if ( prevTime !== null && prevTime > currTime ) {
  23043. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23044. valid = false;
  23045. break;
  23046. }
  23047. prevTime = currTime;
  23048. }
  23049. if ( values !== undefined ) {
  23050. if ( isTypedArray( values ) ) {
  23051. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23052. const value = values[ i ];
  23053. if ( isNaN( value ) ) {
  23054. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23055. valid = false;
  23056. break;
  23057. }
  23058. }
  23059. }
  23060. }
  23061. return valid;
  23062. }
  23063. // removes equivalent sequential keys as common in morph target sequences
  23064. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23065. optimize() {
  23066. // times or values may be shared with other tracks, so overwriting is unsafe
  23067. const times = arraySlice( this.times ),
  23068. values = arraySlice( this.values ),
  23069. stride = this.getValueSize(),
  23070. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23071. lastIndex = times.length - 1;
  23072. let writeIndex = 1;
  23073. for ( let i = 1; i < lastIndex; ++ i ) {
  23074. let keep = false;
  23075. const time = times[ i ];
  23076. const timeNext = times[ i + 1 ];
  23077. // remove adjacent keyframes scheduled at the same time
  23078. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23079. if ( ! smoothInterpolation ) {
  23080. // remove unnecessary keyframes same as their neighbors
  23081. const offset = i * stride,
  23082. offsetP = offset - stride,
  23083. offsetN = offset + stride;
  23084. for ( let j = 0; j !== stride; ++ j ) {
  23085. const value = values[ offset + j ];
  23086. if ( value !== values[ offsetP + j ] ||
  23087. value !== values[ offsetN + j ] ) {
  23088. keep = true;
  23089. break;
  23090. }
  23091. }
  23092. } else {
  23093. keep = true;
  23094. }
  23095. }
  23096. // in-place compaction
  23097. if ( keep ) {
  23098. if ( i !== writeIndex ) {
  23099. times[ writeIndex ] = times[ i ];
  23100. const readOffset = i * stride,
  23101. writeOffset = writeIndex * stride;
  23102. for ( let j = 0; j !== stride; ++ j ) {
  23103. values[ writeOffset + j ] = values[ readOffset + j ];
  23104. }
  23105. }
  23106. ++ writeIndex;
  23107. }
  23108. }
  23109. // flush last keyframe (compaction looks ahead)
  23110. if ( lastIndex > 0 ) {
  23111. times[ writeIndex ] = times[ lastIndex ];
  23112. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23113. values[ writeOffset + j ] = values[ readOffset + j ];
  23114. }
  23115. ++ writeIndex;
  23116. }
  23117. if ( writeIndex !== times.length ) {
  23118. this.times = arraySlice( times, 0, writeIndex );
  23119. this.values = arraySlice( values, 0, writeIndex * stride );
  23120. } else {
  23121. this.times = times;
  23122. this.values = values;
  23123. }
  23124. return this;
  23125. }
  23126. clone() {
  23127. const times = arraySlice( this.times, 0 );
  23128. const values = arraySlice( this.values, 0 );
  23129. const TypedKeyframeTrack = this.constructor;
  23130. const track = new TypedKeyframeTrack( this.name, times, values );
  23131. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23132. track.createInterpolant = this.createInterpolant;
  23133. return track;
  23134. }
  23135. }
  23136. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23137. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23138. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23139. /**
  23140. * A Track of Boolean keyframe values.
  23141. */
  23142. class BooleanKeyframeTrack extends KeyframeTrack {}
  23143. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23144. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23145. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23146. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23147. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23148. /**
  23149. * A Track of keyframe values that represent color.
  23150. */
  23151. class ColorKeyframeTrack extends KeyframeTrack {}
  23152. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23153. /**
  23154. * A Track of numeric keyframe values.
  23155. */
  23156. class NumberKeyframeTrack extends KeyframeTrack {}
  23157. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23158. /**
  23159. * Spherical linear unit quaternion interpolant.
  23160. */
  23161. class QuaternionLinearInterpolant extends Interpolant {
  23162. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23163. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23164. }
  23165. interpolate_( i1, t0, t, t1 ) {
  23166. const result = this.resultBuffer,
  23167. values = this.sampleValues,
  23168. stride = this.valueSize,
  23169. alpha = ( t - t0 ) / ( t1 - t0 );
  23170. let offset = i1 * stride;
  23171. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23172. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23173. }
  23174. return result;
  23175. }
  23176. }
  23177. /**
  23178. * A Track of quaternion keyframe values.
  23179. */
  23180. class QuaternionKeyframeTrack extends KeyframeTrack {
  23181. InterpolantFactoryMethodLinear( result ) {
  23182. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23183. }
  23184. }
  23185. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23186. // ValueBufferType is inherited
  23187. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23188. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23189. /**
  23190. * A Track that interpolates Strings
  23191. */
  23192. class StringKeyframeTrack extends KeyframeTrack {}
  23193. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23194. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23195. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23196. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23197. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23198. /**
  23199. * A Track of vectored keyframe values.
  23200. */
  23201. class VectorKeyframeTrack extends KeyframeTrack {}
  23202. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23203. class AnimationClip {
  23204. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23205. this.name = name;
  23206. this.tracks = tracks;
  23207. this.duration = duration;
  23208. this.blendMode = blendMode;
  23209. this.uuid = generateUUID();
  23210. // this means it should figure out its duration by scanning the tracks
  23211. if ( this.duration < 0 ) {
  23212. this.resetDuration();
  23213. }
  23214. }
  23215. static parse( json ) {
  23216. const tracks = [],
  23217. jsonTracks = json.tracks,
  23218. frameTime = 1.0 / ( json.fps || 1.0 );
  23219. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23220. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23221. }
  23222. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23223. clip.uuid = json.uuid;
  23224. return clip;
  23225. }
  23226. static toJSON( clip ) {
  23227. const tracks = [],
  23228. clipTracks = clip.tracks;
  23229. const json = {
  23230. 'name': clip.name,
  23231. 'duration': clip.duration,
  23232. 'tracks': tracks,
  23233. 'uuid': clip.uuid,
  23234. 'blendMode': clip.blendMode
  23235. };
  23236. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23237. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23238. }
  23239. return json;
  23240. }
  23241. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23242. const numMorphTargets = morphTargetSequence.length;
  23243. const tracks = [];
  23244. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23245. let times = [];
  23246. let values = [];
  23247. times.push(
  23248. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23249. i,
  23250. ( i + 1 ) % numMorphTargets );
  23251. values.push( 0, 1, 0 );
  23252. const order = getKeyframeOrder( times );
  23253. times = sortedArray( times, 1, order );
  23254. values = sortedArray( values, 1, order );
  23255. // if there is a key at the first frame, duplicate it as the
  23256. // last frame as well for perfect loop.
  23257. if ( ! noLoop && times[ 0 ] === 0 ) {
  23258. times.push( numMorphTargets );
  23259. values.push( values[ 0 ] );
  23260. }
  23261. tracks.push(
  23262. new NumberKeyframeTrack(
  23263. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23264. times, values
  23265. ).scale( 1.0 / fps ) );
  23266. }
  23267. return new this( name, - 1, tracks );
  23268. }
  23269. static findByName( objectOrClipArray, name ) {
  23270. let clipArray = objectOrClipArray;
  23271. if ( ! Array.isArray( objectOrClipArray ) ) {
  23272. const o = objectOrClipArray;
  23273. clipArray = o.geometry && o.geometry.animations || o.animations;
  23274. }
  23275. for ( let i = 0; i < clipArray.length; i ++ ) {
  23276. if ( clipArray[ i ].name === name ) {
  23277. return clipArray[ i ];
  23278. }
  23279. }
  23280. return null;
  23281. }
  23282. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23283. const animationToMorphTargets = {};
  23284. // tested with https://regex101.com/ on trick sequences
  23285. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23286. const pattern = /^([\w-]*?)([\d]+)$/;
  23287. // sort morph target names into animation groups based
  23288. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23289. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23290. const morphTarget = morphTargets[ i ];
  23291. const parts = morphTarget.name.match( pattern );
  23292. if ( parts && parts.length > 1 ) {
  23293. const name = parts[ 1 ];
  23294. let animationMorphTargets = animationToMorphTargets[ name ];
  23295. if ( ! animationMorphTargets ) {
  23296. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23297. }
  23298. animationMorphTargets.push( morphTarget );
  23299. }
  23300. }
  23301. const clips = [];
  23302. for ( const name in animationToMorphTargets ) {
  23303. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23304. }
  23305. return clips;
  23306. }
  23307. // parse the animation.hierarchy format
  23308. static parseAnimation( animation, bones ) {
  23309. if ( ! animation ) {
  23310. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23311. return null;
  23312. }
  23313. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23314. // only return track if there are actually keys.
  23315. if ( animationKeys.length !== 0 ) {
  23316. const times = [];
  23317. const values = [];
  23318. flattenJSON( animationKeys, times, values, propertyName );
  23319. // empty keys are filtered out, so check again
  23320. if ( times.length !== 0 ) {
  23321. destTracks.push( new trackType( trackName, times, values ) );
  23322. }
  23323. }
  23324. };
  23325. const tracks = [];
  23326. const clipName = animation.name || 'default';
  23327. const fps = animation.fps || 30;
  23328. const blendMode = animation.blendMode;
  23329. // automatic length determination in AnimationClip.
  23330. let duration = animation.length || - 1;
  23331. const hierarchyTracks = animation.hierarchy || [];
  23332. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23333. const animationKeys = hierarchyTracks[ h ].keys;
  23334. // skip empty tracks
  23335. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23336. // process morph targets
  23337. if ( animationKeys[ 0 ].morphTargets ) {
  23338. // figure out all morph targets used in this track
  23339. const morphTargetNames = {};
  23340. let k;
  23341. for ( k = 0; k < animationKeys.length; k ++ ) {
  23342. if ( animationKeys[ k ].morphTargets ) {
  23343. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23344. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23345. }
  23346. }
  23347. }
  23348. // create a track for each morph target with all zero
  23349. // morphTargetInfluences except for the keys in which
  23350. // the morphTarget is named.
  23351. for ( const morphTargetName in morphTargetNames ) {
  23352. const times = [];
  23353. const values = [];
  23354. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23355. const animationKey = animationKeys[ k ];
  23356. times.push( animationKey.time );
  23357. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23358. }
  23359. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23360. }
  23361. duration = morphTargetNames.length * fps;
  23362. } else {
  23363. // ...assume skeletal animation
  23364. const boneName = '.bones[' + bones[ h ].name + ']';
  23365. addNonemptyTrack(
  23366. VectorKeyframeTrack, boneName + '.position',
  23367. animationKeys, 'pos', tracks );
  23368. addNonemptyTrack(
  23369. QuaternionKeyframeTrack, boneName + '.quaternion',
  23370. animationKeys, 'rot', tracks );
  23371. addNonemptyTrack(
  23372. VectorKeyframeTrack, boneName + '.scale',
  23373. animationKeys, 'scl', tracks );
  23374. }
  23375. }
  23376. if ( tracks.length === 0 ) {
  23377. return null;
  23378. }
  23379. const clip = new this( clipName, duration, tracks, blendMode );
  23380. return clip;
  23381. }
  23382. resetDuration() {
  23383. const tracks = this.tracks;
  23384. let duration = 0;
  23385. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23386. const track = this.tracks[ i ];
  23387. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23388. }
  23389. this.duration = duration;
  23390. return this;
  23391. }
  23392. trim() {
  23393. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23394. this.tracks[ i ].trim( 0, this.duration );
  23395. }
  23396. return this;
  23397. }
  23398. validate() {
  23399. let valid = true;
  23400. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23401. valid = valid && this.tracks[ i ].validate();
  23402. }
  23403. return valid;
  23404. }
  23405. optimize() {
  23406. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23407. this.tracks[ i ].optimize();
  23408. }
  23409. return this;
  23410. }
  23411. clone() {
  23412. const tracks = [];
  23413. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23414. tracks.push( this.tracks[ i ].clone() );
  23415. }
  23416. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23417. }
  23418. toJSON() {
  23419. return this.constructor.toJSON( this );
  23420. }
  23421. }
  23422. function getTrackTypeForValueTypeName( typeName ) {
  23423. switch ( typeName.toLowerCase() ) {
  23424. case 'scalar':
  23425. case 'double':
  23426. case 'float':
  23427. case 'number':
  23428. case 'integer':
  23429. return NumberKeyframeTrack;
  23430. case 'vector':
  23431. case 'vector2':
  23432. case 'vector3':
  23433. case 'vector4':
  23434. return VectorKeyframeTrack;
  23435. case 'color':
  23436. return ColorKeyframeTrack;
  23437. case 'quaternion':
  23438. return QuaternionKeyframeTrack;
  23439. case 'bool':
  23440. case 'boolean':
  23441. return BooleanKeyframeTrack;
  23442. case 'string':
  23443. return StringKeyframeTrack;
  23444. }
  23445. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23446. }
  23447. function parseKeyframeTrack( json ) {
  23448. if ( json.type === undefined ) {
  23449. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23450. }
  23451. const trackType = getTrackTypeForValueTypeName( json.type );
  23452. if ( json.times === undefined ) {
  23453. const times = [], values = [];
  23454. flattenJSON( json.keys, times, values, 'value' );
  23455. json.times = times;
  23456. json.values = values;
  23457. }
  23458. // derived classes can define a static parse method
  23459. if ( trackType.parse !== undefined ) {
  23460. return trackType.parse( json );
  23461. } else {
  23462. // by default, we assume a constructor compatible with the base
  23463. return new trackType( json.name, json.times, json.values, json.interpolation );
  23464. }
  23465. }
  23466. const Cache = {
  23467. enabled: false,
  23468. files: {},
  23469. add: function ( key, file ) {
  23470. if ( this.enabled === false ) return;
  23471. // console.log( 'THREE.Cache', 'Adding key:', key );
  23472. this.files[ key ] = file;
  23473. },
  23474. get: function ( key ) {
  23475. if ( this.enabled === false ) return;
  23476. // console.log( 'THREE.Cache', 'Checking key:', key );
  23477. return this.files[ key ];
  23478. },
  23479. remove: function ( key ) {
  23480. delete this.files[ key ];
  23481. },
  23482. clear: function () {
  23483. this.files = {};
  23484. }
  23485. };
  23486. class LoadingManager {
  23487. constructor( onLoad, onProgress, onError ) {
  23488. const scope = this;
  23489. let isLoading = false;
  23490. let itemsLoaded = 0;
  23491. let itemsTotal = 0;
  23492. let urlModifier = undefined;
  23493. const handlers = [];
  23494. // Refer to #5689 for the reason why we don't set .onStart
  23495. // in the constructor
  23496. this.onStart = undefined;
  23497. this.onLoad = onLoad;
  23498. this.onProgress = onProgress;
  23499. this.onError = onError;
  23500. this.itemStart = function ( url ) {
  23501. itemsTotal ++;
  23502. if ( isLoading === false ) {
  23503. if ( scope.onStart !== undefined ) {
  23504. scope.onStart( url, itemsLoaded, itemsTotal );
  23505. }
  23506. }
  23507. isLoading = true;
  23508. };
  23509. this.itemEnd = function ( url ) {
  23510. itemsLoaded ++;
  23511. if ( scope.onProgress !== undefined ) {
  23512. scope.onProgress( url, itemsLoaded, itemsTotal );
  23513. }
  23514. if ( itemsLoaded === itemsTotal ) {
  23515. isLoading = false;
  23516. if ( scope.onLoad !== undefined ) {
  23517. scope.onLoad();
  23518. }
  23519. }
  23520. };
  23521. this.itemError = function ( url ) {
  23522. if ( scope.onError !== undefined ) {
  23523. scope.onError( url );
  23524. }
  23525. };
  23526. this.resolveURL = function ( url ) {
  23527. if ( urlModifier ) {
  23528. return urlModifier( url );
  23529. }
  23530. return url;
  23531. };
  23532. this.setURLModifier = function ( transform ) {
  23533. urlModifier = transform;
  23534. return this;
  23535. };
  23536. this.addHandler = function ( regex, loader ) {
  23537. handlers.push( regex, loader );
  23538. return this;
  23539. };
  23540. this.removeHandler = function ( regex ) {
  23541. const index = handlers.indexOf( regex );
  23542. if ( index !== - 1 ) {
  23543. handlers.splice( index, 2 );
  23544. }
  23545. return this;
  23546. };
  23547. this.getHandler = function ( file ) {
  23548. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23549. const regex = handlers[ i ];
  23550. const loader = handlers[ i + 1 ];
  23551. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23552. if ( regex.test( file ) ) {
  23553. return loader;
  23554. }
  23555. }
  23556. return null;
  23557. };
  23558. }
  23559. }
  23560. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23561. class Loader {
  23562. constructor( manager ) {
  23563. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23564. this.crossOrigin = 'anonymous';
  23565. this.withCredentials = false;
  23566. this.path = '';
  23567. this.resourcePath = '';
  23568. this.requestHeader = {};
  23569. }
  23570. load( /* url, onLoad, onProgress, onError */ ) {}
  23571. loadAsync( url, onProgress ) {
  23572. const scope = this;
  23573. return new Promise( function ( resolve, reject ) {
  23574. scope.load( url, resolve, onProgress, reject );
  23575. } );
  23576. }
  23577. parse( /* data */ ) {}
  23578. setCrossOrigin( crossOrigin ) {
  23579. this.crossOrigin = crossOrigin;
  23580. return this;
  23581. }
  23582. setWithCredentials( value ) {
  23583. this.withCredentials = value;
  23584. return this;
  23585. }
  23586. setPath( path ) {
  23587. this.path = path;
  23588. return this;
  23589. }
  23590. setResourcePath( resourcePath ) {
  23591. this.resourcePath = resourcePath;
  23592. return this;
  23593. }
  23594. setRequestHeader( requestHeader ) {
  23595. this.requestHeader = requestHeader;
  23596. return this;
  23597. }
  23598. }
  23599. const loading = {};
  23600. class HttpError extends Error {
  23601. constructor( message, response ) {
  23602. super( message );
  23603. this.response = response;
  23604. }
  23605. }
  23606. class FileLoader extends Loader {
  23607. constructor( manager ) {
  23608. super( manager );
  23609. }
  23610. load( url, onLoad, onProgress, onError ) {
  23611. if ( url === undefined ) url = '';
  23612. if ( this.path !== undefined ) url = this.path + url;
  23613. url = this.manager.resolveURL( url );
  23614. const cached = Cache.get( url );
  23615. if ( cached !== undefined ) {
  23616. this.manager.itemStart( url );
  23617. setTimeout( () => {
  23618. if ( onLoad ) onLoad( cached );
  23619. this.manager.itemEnd( url );
  23620. }, 0 );
  23621. return cached;
  23622. }
  23623. // Check if request is duplicate
  23624. if ( loading[ url ] !== undefined ) {
  23625. loading[ url ].push( {
  23626. onLoad: onLoad,
  23627. onProgress: onProgress,
  23628. onError: onError
  23629. } );
  23630. return;
  23631. }
  23632. // Initialise array for duplicate requests
  23633. loading[ url ] = [];
  23634. loading[ url ].push( {
  23635. onLoad: onLoad,
  23636. onProgress: onProgress,
  23637. onError: onError,
  23638. } );
  23639. // create request
  23640. const req = new Request( url, {
  23641. headers: new Headers( this.requestHeader ),
  23642. credentials: this.withCredentials ? 'include' : 'same-origin',
  23643. // An abort controller could be added within a future PR
  23644. } );
  23645. // record states ( avoid data race )
  23646. const mimeType = this.mimeType;
  23647. const responseType = this.responseType;
  23648. // start the fetch
  23649. fetch( req )
  23650. .then( response => {
  23651. if ( response.status === 200 || response.status === 0 ) {
  23652. // Some browsers return HTTP Status 0 when using non-http protocol
  23653. // e.g. 'file://' or 'data://'. Handle as success.
  23654. if ( response.status === 0 ) {
  23655. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23656. }
  23657. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23658. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23659. return response;
  23660. }
  23661. const callbacks = loading[ url ];
  23662. const reader = response.body.getReader();
  23663. const contentLength = response.headers.get( 'Content-Length' );
  23664. const total = contentLength ? parseInt( contentLength ) : 0;
  23665. const lengthComputable = total !== 0;
  23666. let loaded = 0;
  23667. // periodically read data into the new stream tracking while download progress
  23668. const stream = new ReadableStream( {
  23669. start( controller ) {
  23670. readData();
  23671. function readData() {
  23672. reader.read().then( ( { done, value } ) => {
  23673. if ( done ) {
  23674. controller.close();
  23675. } else {
  23676. loaded += value.byteLength;
  23677. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23678. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23679. const callback = callbacks[ i ];
  23680. if ( callback.onProgress ) callback.onProgress( event );
  23681. }
  23682. controller.enqueue( value );
  23683. readData();
  23684. }
  23685. } );
  23686. }
  23687. }
  23688. } );
  23689. return new Response( stream );
  23690. } else {
  23691. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  23692. }
  23693. } )
  23694. .then( response => {
  23695. switch ( responseType ) {
  23696. case 'arraybuffer':
  23697. return response.arrayBuffer();
  23698. case 'blob':
  23699. return response.blob();
  23700. case 'document':
  23701. return response.text()
  23702. .then( text => {
  23703. const parser = new DOMParser();
  23704. return parser.parseFromString( text, mimeType );
  23705. } );
  23706. case 'json':
  23707. return response.json();
  23708. default:
  23709. if ( mimeType === undefined ) {
  23710. return response.text();
  23711. } else {
  23712. // sniff encoding
  23713. const re = /charset="?([^;"\s]*)"?/i;
  23714. const exec = re.exec( mimeType );
  23715. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23716. const decoder = new TextDecoder( label );
  23717. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23718. }
  23719. }
  23720. } )
  23721. .then( data => {
  23722. // Add to cache only on HTTP success, so that we do not cache
  23723. // error response bodies as proper responses to requests.
  23724. Cache.add( url, data );
  23725. const callbacks = loading[ url ];
  23726. delete loading[ url ];
  23727. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23728. const callback = callbacks[ i ];
  23729. if ( callback.onLoad ) callback.onLoad( data );
  23730. }
  23731. } )
  23732. .catch( err => {
  23733. // Abort errors and other errors are handled the same
  23734. const callbacks = loading[ url ];
  23735. if ( callbacks === undefined ) {
  23736. // When onLoad was called and url was deleted in `loading`
  23737. this.manager.itemError( url );
  23738. throw err;
  23739. }
  23740. delete loading[ url ];
  23741. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23742. const callback = callbacks[ i ];
  23743. if ( callback.onError ) callback.onError( err );
  23744. }
  23745. this.manager.itemError( url );
  23746. } )
  23747. .finally( () => {
  23748. this.manager.itemEnd( url );
  23749. } );
  23750. this.manager.itemStart( url );
  23751. }
  23752. setResponseType( value ) {
  23753. this.responseType = value;
  23754. return this;
  23755. }
  23756. setMimeType( value ) {
  23757. this.mimeType = value;
  23758. return this;
  23759. }
  23760. }
  23761. class AnimationLoader extends Loader {
  23762. constructor( manager ) {
  23763. super( manager );
  23764. }
  23765. load( url, onLoad, onProgress, onError ) {
  23766. const scope = this;
  23767. const loader = new FileLoader( this.manager );
  23768. loader.setPath( this.path );
  23769. loader.setRequestHeader( this.requestHeader );
  23770. loader.setWithCredentials( this.withCredentials );
  23771. loader.load( url, function ( text ) {
  23772. try {
  23773. onLoad( scope.parse( JSON.parse( text ) ) );
  23774. } catch ( e ) {
  23775. if ( onError ) {
  23776. onError( e );
  23777. } else {
  23778. console.error( e );
  23779. }
  23780. scope.manager.itemError( url );
  23781. }
  23782. }, onProgress, onError );
  23783. }
  23784. parse( json ) {
  23785. const animations = [];
  23786. for ( let i = 0; i < json.length; i ++ ) {
  23787. const clip = AnimationClip.parse( json[ i ] );
  23788. animations.push( clip );
  23789. }
  23790. return animations;
  23791. }
  23792. }
  23793. /**
  23794. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23795. *
  23796. * Sub classes have to implement the parse() method which will be used in load().
  23797. */
  23798. class CompressedTextureLoader extends Loader {
  23799. constructor( manager ) {
  23800. super( manager );
  23801. }
  23802. load( url, onLoad, onProgress, onError ) {
  23803. const scope = this;
  23804. const images = [];
  23805. const texture = new CompressedTexture();
  23806. const loader = new FileLoader( this.manager );
  23807. loader.setPath( this.path );
  23808. loader.setResponseType( 'arraybuffer' );
  23809. loader.setRequestHeader( this.requestHeader );
  23810. loader.setWithCredentials( scope.withCredentials );
  23811. let loaded = 0;
  23812. function loadTexture( i ) {
  23813. loader.load( url[ i ], function ( buffer ) {
  23814. const texDatas = scope.parse( buffer, true );
  23815. images[ i ] = {
  23816. width: texDatas.width,
  23817. height: texDatas.height,
  23818. format: texDatas.format,
  23819. mipmaps: texDatas.mipmaps
  23820. };
  23821. loaded += 1;
  23822. if ( loaded === 6 ) {
  23823. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23824. texture.image = images;
  23825. texture.format = texDatas.format;
  23826. texture.needsUpdate = true;
  23827. if ( onLoad ) onLoad( texture );
  23828. }
  23829. }, onProgress, onError );
  23830. }
  23831. if ( Array.isArray( url ) ) {
  23832. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23833. loadTexture( i );
  23834. }
  23835. } else {
  23836. // compressed cubemap texture stored in a single DDS file
  23837. loader.load( url, function ( buffer ) {
  23838. const texDatas = scope.parse( buffer, true );
  23839. if ( texDatas.isCubemap ) {
  23840. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23841. for ( let f = 0; f < faces; f ++ ) {
  23842. images[ f ] = { mipmaps: [] };
  23843. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23844. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23845. images[ f ].format = texDatas.format;
  23846. images[ f ].width = texDatas.width;
  23847. images[ f ].height = texDatas.height;
  23848. }
  23849. }
  23850. texture.image = images;
  23851. } else {
  23852. texture.image.width = texDatas.width;
  23853. texture.image.height = texDatas.height;
  23854. texture.mipmaps = texDatas.mipmaps;
  23855. }
  23856. if ( texDatas.mipmapCount === 1 ) {
  23857. texture.minFilter = LinearFilter;
  23858. }
  23859. texture.format = texDatas.format;
  23860. texture.needsUpdate = true;
  23861. if ( onLoad ) onLoad( texture );
  23862. }, onProgress, onError );
  23863. }
  23864. return texture;
  23865. }
  23866. }
  23867. class ImageLoader extends Loader {
  23868. constructor( manager ) {
  23869. super( manager );
  23870. }
  23871. load( url, onLoad, onProgress, onError ) {
  23872. if ( this.path !== undefined ) url = this.path + url;
  23873. url = this.manager.resolveURL( url );
  23874. const scope = this;
  23875. const cached = Cache.get( url );
  23876. if ( cached !== undefined ) {
  23877. scope.manager.itemStart( url );
  23878. setTimeout( function () {
  23879. if ( onLoad ) onLoad( cached );
  23880. scope.manager.itemEnd( url );
  23881. }, 0 );
  23882. return cached;
  23883. }
  23884. const image = createElementNS( 'img' );
  23885. function onImageLoad() {
  23886. removeEventListeners();
  23887. Cache.add( url, this );
  23888. if ( onLoad ) onLoad( this );
  23889. scope.manager.itemEnd( url );
  23890. }
  23891. function onImageError( event ) {
  23892. removeEventListeners();
  23893. if ( onError ) onError( event );
  23894. scope.manager.itemError( url );
  23895. scope.manager.itemEnd( url );
  23896. }
  23897. function removeEventListeners() {
  23898. image.removeEventListener( 'load', onImageLoad, false );
  23899. image.removeEventListener( 'error', onImageError, false );
  23900. }
  23901. image.addEventListener( 'load', onImageLoad, false );
  23902. image.addEventListener( 'error', onImageError, false );
  23903. if ( url.slice( 0, 5 ) !== 'data:' ) {
  23904. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23905. }
  23906. scope.manager.itemStart( url );
  23907. image.src = url;
  23908. return image;
  23909. }
  23910. }
  23911. class CubeTextureLoader extends Loader {
  23912. constructor( manager ) {
  23913. super( manager );
  23914. }
  23915. load( urls, onLoad, onProgress, onError ) {
  23916. const texture = new CubeTexture();
  23917. const loader = new ImageLoader( this.manager );
  23918. loader.setCrossOrigin( this.crossOrigin );
  23919. loader.setPath( this.path );
  23920. let loaded = 0;
  23921. function loadTexture( i ) {
  23922. loader.load( urls[ i ], function ( image ) {
  23923. texture.images[ i ] = image;
  23924. loaded ++;
  23925. if ( loaded === 6 ) {
  23926. texture.needsUpdate = true;
  23927. if ( onLoad ) onLoad( texture );
  23928. }
  23929. }, undefined, onError );
  23930. }
  23931. for ( let i = 0; i < urls.length; ++ i ) {
  23932. loadTexture( i );
  23933. }
  23934. return texture;
  23935. }
  23936. }
  23937. /**
  23938. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23939. *
  23940. * Sub classes have to implement the parse() method which will be used in load().
  23941. */
  23942. class DataTextureLoader extends Loader {
  23943. constructor( manager ) {
  23944. super( manager );
  23945. }
  23946. load( url, onLoad, onProgress, onError ) {
  23947. const scope = this;
  23948. const texture = new DataTexture();
  23949. const loader = new FileLoader( this.manager );
  23950. loader.setResponseType( 'arraybuffer' );
  23951. loader.setRequestHeader( this.requestHeader );
  23952. loader.setPath( this.path );
  23953. loader.setWithCredentials( scope.withCredentials );
  23954. loader.load( url, function ( buffer ) {
  23955. const texData = scope.parse( buffer );
  23956. if ( ! texData ) return;
  23957. if ( texData.image !== undefined ) {
  23958. texture.image = texData.image;
  23959. } else if ( texData.data !== undefined ) {
  23960. texture.image.width = texData.width;
  23961. texture.image.height = texData.height;
  23962. texture.image.data = texData.data;
  23963. }
  23964. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23965. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23966. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23967. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23968. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23969. if ( texData.encoding !== undefined ) {
  23970. texture.encoding = texData.encoding;
  23971. }
  23972. if ( texData.flipY !== undefined ) {
  23973. texture.flipY = texData.flipY;
  23974. }
  23975. if ( texData.format !== undefined ) {
  23976. texture.format = texData.format;
  23977. }
  23978. if ( texData.type !== undefined ) {
  23979. texture.type = texData.type;
  23980. }
  23981. if ( texData.mipmaps !== undefined ) {
  23982. texture.mipmaps = texData.mipmaps;
  23983. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23984. }
  23985. if ( texData.mipmapCount === 1 ) {
  23986. texture.minFilter = LinearFilter;
  23987. }
  23988. if ( texData.generateMipmaps !== undefined ) {
  23989. texture.generateMipmaps = texData.generateMipmaps;
  23990. }
  23991. texture.needsUpdate = true;
  23992. if ( onLoad ) onLoad( texture, texData );
  23993. }, onProgress, onError );
  23994. return texture;
  23995. }
  23996. }
  23997. class TextureLoader extends Loader {
  23998. constructor( manager ) {
  23999. super( manager );
  24000. }
  24001. load( url, onLoad, onProgress, onError ) {
  24002. const texture = new Texture();
  24003. const loader = new ImageLoader( this.manager );
  24004. loader.setCrossOrigin( this.crossOrigin );
  24005. loader.setPath( this.path );
  24006. loader.load( url, function ( image ) {
  24007. texture.image = image;
  24008. texture.needsUpdate = true;
  24009. if ( onLoad !== undefined ) {
  24010. onLoad( texture );
  24011. }
  24012. }, onProgress, onError );
  24013. return texture;
  24014. }
  24015. }
  24016. class Light extends Object3D {
  24017. constructor( color, intensity = 1 ) {
  24018. super();
  24019. this.isLight = true;
  24020. this.type = 'Light';
  24021. this.color = new Color( color );
  24022. this.intensity = intensity;
  24023. }
  24024. dispose() {
  24025. // Empty here in base class; some subclasses override.
  24026. }
  24027. copy( source, recursive ) {
  24028. super.copy( source, recursive );
  24029. this.color.copy( source.color );
  24030. this.intensity = source.intensity;
  24031. return this;
  24032. }
  24033. toJSON( meta ) {
  24034. const data = super.toJSON( meta );
  24035. data.object.color = this.color.getHex();
  24036. data.object.intensity = this.intensity;
  24037. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24038. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24039. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24040. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24041. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24042. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24043. return data;
  24044. }
  24045. }
  24046. class HemisphereLight extends Light {
  24047. constructor( skyColor, groundColor, intensity ) {
  24048. super( skyColor, intensity );
  24049. this.isHemisphereLight = true;
  24050. this.type = 'HemisphereLight';
  24051. this.position.copy( Object3D.DefaultUp );
  24052. this.updateMatrix();
  24053. this.groundColor = new Color( groundColor );
  24054. }
  24055. copy( source, recursive ) {
  24056. super.copy( source, recursive );
  24057. this.groundColor.copy( source.groundColor );
  24058. return this;
  24059. }
  24060. }
  24061. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24062. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24063. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24064. class LightShadow {
  24065. constructor( camera ) {
  24066. this.camera = camera;
  24067. this.bias = 0;
  24068. this.normalBias = 0;
  24069. this.radius = 1;
  24070. this.blurSamples = 8;
  24071. this.mapSize = new Vector2( 512, 512 );
  24072. this.map = null;
  24073. this.mapPass = null;
  24074. this.matrix = new Matrix4();
  24075. this.autoUpdate = true;
  24076. this.needsUpdate = false;
  24077. this._frustum = new Frustum();
  24078. this._frameExtents = new Vector2( 1, 1 );
  24079. this._viewportCount = 1;
  24080. this._viewports = [
  24081. new Vector4( 0, 0, 1, 1 )
  24082. ];
  24083. }
  24084. getViewportCount() {
  24085. return this._viewportCount;
  24086. }
  24087. getFrustum() {
  24088. return this._frustum;
  24089. }
  24090. updateMatrices( light ) {
  24091. const shadowCamera = this.camera;
  24092. const shadowMatrix = this.matrix;
  24093. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24094. shadowCamera.position.copy( _lightPositionWorld$1 );
  24095. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24096. shadowCamera.lookAt( _lookTarget$1 );
  24097. shadowCamera.updateMatrixWorld();
  24098. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24099. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24100. shadowMatrix.set(
  24101. 0.5, 0.0, 0.0, 0.5,
  24102. 0.0, 0.5, 0.0, 0.5,
  24103. 0.0, 0.0, 0.5, 0.5,
  24104. 0.0, 0.0, 0.0, 1.0
  24105. );
  24106. shadowMatrix.multiply( _projScreenMatrix$1 );
  24107. }
  24108. getViewport( viewportIndex ) {
  24109. return this._viewports[ viewportIndex ];
  24110. }
  24111. getFrameExtents() {
  24112. return this._frameExtents;
  24113. }
  24114. dispose() {
  24115. if ( this.map ) {
  24116. this.map.dispose();
  24117. }
  24118. if ( this.mapPass ) {
  24119. this.mapPass.dispose();
  24120. }
  24121. }
  24122. copy( source ) {
  24123. this.camera = source.camera.clone();
  24124. this.bias = source.bias;
  24125. this.radius = source.radius;
  24126. this.mapSize.copy( source.mapSize );
  24127. return this;
  24128. }
  24129. clone() {
  24130. return new this.constructor().copy( this );
  24131. }
  24132. toJSON() {
  24133. const object = {};
  24134. if ( this.bias !== 0 ) object.bias = this.bias;
  24135. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24136. if ( this.radius !== 1 ) object.radius = this.radius;
  24137. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24138. object.camera = this.camera.toJSON( false ).object;
  24139. delete object.camera.matrix;
  24140. return object;
  24141. }
  24142. }
  24143. class SpotLightShadow extends LightShadow {
  24144. constructor() {
  24145. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24146. this.isSpotLightShadow = true;
  24147. this.focus = 1;
  24148. }
  24149. updateMatrices( light ) {
  24150. const camera = this.camera;
  24151. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24152. const aspect = this.mapSize.width / this.mapSize.height;
  24153. const far = light.distance || camera.far;
  24154. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24155. camera.fov = fov;
  24156. camera.aspect = aspect;
  24157. camera.far = far;
  24158. camera.updateProjectionMatrix();
  24159. }
  24160. super.updateMatrices( light );
  24161. }
  24162. copy( source ) {
  24163. super.copy( source );
  24164. this.focus = source.focus;
  24165. return this;
  24166. }
  24167. }
  24168. class SpotLight extends Light {
  24169. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  24170. super( color, intensity );
  24171. this.isSpotLight = true;
  24172. this.type = 'SpotLight';
  24173. this.position.copy( Object3D.DefaultUp );
  24174. this.updateMatrix();
  24175. this.target = new Object3D();
  24176. this.distance = distance;
  24177. this.angle = angle;
  24178. this.penumbra = penumbra;
  24179. this.decay = decay; // for physically correct lights, should be 2.
  24180. this.map = null;
  24181. this.shadow = new SpotLightShadow();
  24182. }
  24183. get power() {
  24184. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24185. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24186. return this.intensity * Math.PI;
  24187. }
  24188. set power( power ) {
  24189. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24190. this.intensity = power / Math.PI;
  24191. }
  24192. dispose() {
  24193. this.shadow.dispose();
  24194. }
  24195. copy( source, recursive ) {
  24196. super.copy( source, recursive );
  24197. this.distance = source.distance;
  24198. this.angle = source.angle;
  24199. this.penumbra = source.penumbra;
  24200. this.decay = source.decay;
  24201. this.target = source.target.clone();
  24202. this.shadow = source.shadow.clone();
  24203. return this;
  24204. }
  24205. }
  24206. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24207. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24208. const _lookTarget = /*@__PURE__*/ new Vector3();
  24209. class PointLightShadow extends LightShadow {
  24210. constructor() {
  24211. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24212. this.isPointLightShadow = true;
  24213. this._frameExtents = new Vector2( 4, 2 );
  24214. this._viewportCount = 6;
  24215. this._viewports = [
  24216. // These viewports map a cube-map onto a 2D texture with the
  24217. // following orientation:
  24218. //
  24219. // xzXZ
  24220. // y Y
  24221. //
  24222. // X - Positive x direction
  24223. // x - Negative x direction
  24224. // Y - Positive y direction
  24225. // y - Negative y direction
  24226. // Z - Positive z direction
  24227. // z - Negative z direction
  24228. // positive X
  24229. new Vector4( 2, 1, 1, 1 ),
  24230. // negative X
  24231. new Vector4( 0, 1, 1, 1 ),
  24232. // positive Z
  24233. new Vector4( 3, 1, 1, 1 ),
  24234. // negative Z
  24235. new Vector4( 1, 1, 1, 1 ),
  24236. // positive Y
  24237. new Vector4( 3, 0, 1, 1 ),
  24238. // negative Y
  24239. new Vector4( 1, 0, 1, 1 )
  24240. ];
  24241. this._cubeDirections = [
  24242. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24243. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24244. ];
  24245. this._cubeUps = [
  24246. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24247. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24248. ];
  24249. }
  24250. updateMatrices( light, viewportIndex = 0 ) {
  24251. const camera = this.camera;
  24252. const shadowMatrix = this.matrix;
  24253. const far = light.distance || camera.far;
  24254. if ( far !== camera.far ) {
  24255. camera.far = far;
  24256. camera.updateProjectionMatrix();
  24257. }
  24258. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24259. camera.position.copy( _lightPositionWorld );
  24260. _lookTarget.copy( camera.position );
  24261. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24262. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24263. camera.lookAt( _lookTarget );
  24264. camera.updateMatrixWorld();
  24265. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24266. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24267. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24268. }
  24269. }
  24270. class PointLight extends Light {
  24271. constructor( color, intensity, distance = 0, decay = 1 ) {
  24272. super( color, intensity );
  24273. this.isPointLight = true;
  24274. this.type = 'PointLight';
  24275. this.distance = distance;
  24276. this.decay = decay; // for physically correct lights, should be 2.
  24277. this.shadow = new PointLightShadow();
  24278. }
  24279. get power() {
  24280. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24281. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24282. return this.intensity * 4 * Math.PI;
  24283. }
  24284. set power( power ) {
  24285. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24286. this.intensity = power / ( 4 * Math.PI );
  24287. }
  24288. dispose() {
  24289. this.shadow.dispose();
  24290. }
  24291. copy( source, recursive ) {
  24292. super.copy( source, recursive );
  24293. this.distance = source.distance;
  24294. this.decay = source.decay;
  24295. this.shadow = source.shadow.clone();
  24296. return this;
  24297. }
  24298. }
  24299. class DirectionalLightShadow extends LightShadow {
  24300. constructor() {
  24301. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24302. this.isDirectionalLightShadow = true;
  24303. }
  24304. }
  24305. class DirectionalLight extends Light {
  24306. constructor( color, intensity ) {
  24307. super( color, intensity );
  24308. this.isDirectionalLight = true;
  24309. this.type = 'DirectionalLight';
  24310. this.position.copy( Object3D.DefaultUp );
  24311. this.updateMatrix();
  24312. this.target = new Object3D();
  24313. this.shadow = new DirectionalLightShadow();
  24314. }
  24315. dispose() {
  24316. this.shadow.dispose();
  24317. }
  24318. copy( source ) {
  24319. super.copy( source );
  24320. this.target = source.target.clone();
  24321. this.shadow = source.shadow.clone();
  24322. return this;
  24323. }
  24324. }
  24325. class AmbientLight extends Light {
  24326. constructor( color, intensity ) {
  24327. super( color, intensity );
  24328. this.isAmbientLight = true;
  24329. this.type = 'AmbientLight';
  24330. }
  24331. }
  24332. class RectAreaLight extends Light {
  24333. constructor( color, intensity, width = 10, height = 10 ) {
  24334. super( color, intensity );
  24335. this.isRectAreaLight = true;
  24336. this.type = 'RectAreaLight';
  24337. this.width = width;
  24338. this.height = height;
  24339. }
  24340. get power() {
  24341. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24342. return this.intensity * this.width * this.height * Math.PI;
  24343. }
  24344. set power( power ) {
  24345. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24346. this.intensity = power / ( this.width * this.height * Math.PI );
  24347. }
  24348. copy( source ) {
  24349. super.copy( source );
  24350. this.width = source.width;
  24351. this.height = source.height;
  24352. return this;
  24353. }
  24354. toJSON( meta ) {
  24355. const data = super.toJSON( meta );
  24356. data.object.width = this.width;
  24357. data.object.height = this.height;
  24358. return data;
  24359. }
  24360. }
  24361. /**
  24362. * Primary reference:
  24363. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24364. *
  24365. * Secondary reference:
  24366. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24367. */
  24368. // 3-band SH defined by 9 coefficients
  24369. class SphericalHarmonics3 {
  24370. constructor() {
  24371. this.isSphericalHarmonics3 = true;
  24372. this.coefficients = [];
  24373. for ( let i = 0; i < 9; i ++ ) {
  24374. this.coefficients.push( new Vector3() );
  24375. }
  24376. }
  24377. set( coefficients ) {
  24378. for ( let i = 0; i < 9; i ++ ) {
  24379. this.coefficients[ i ].copy( coefficients[ i ] );
  24380. }
  24381. return this;
  24382. }
  24383. zero() {
  24384. for ( let i = 0; i < 9; i ++ ) {
  24385. this.coefficients[ i ].set( 0, 0, 0 );
  24386. }
  24387. return this;
  24388. }
  24389. // get the radiance in the direction of the normal
  24390. // target is a Vector3
  24391. getAt( normal, target ) {
  24392. // normal is assumed to be unit length
  24393. const x = normal.x, y = normal.y, z = normal.z;
  24394. const coeff = this.coefficients;
  24395. // band 0
  24396. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24397. // band 1
  24398. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24399. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24400. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24401. // band 2
  24402. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24403. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24404. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24405. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24406. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24407. return target;
  24408. }
  24409. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24410. // target is a Vector3
  24411. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24412. getIrradianceAt( normal, target ) {
  24413. // normal is assumed to be unit length
  24414. const x = normal.x, y = normal.y, z = normal.z;
  24415. const coeff = this.coefficients;
  24416. // band 0
  24417. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24418. // band 1
  24419. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24420. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24421. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24422. // band 2
  24423. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24424. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24425. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24426. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24427. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24428. return target;
  24429. }
  24430. add( sh ) {
  24431. for ( let i = 0; i < 9; i ++ ) {
  24432. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24433. }
  24434. return this;
  24435. }
  24436. addScaledSH( sh, s ) {
  24437. for ( let i = 0; i < 9; i ++ ) {
  24438. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24439. }
  24440. return this;
  24441. }
  24442. scale( s ) {
  24443. for ( let i = 0; i < 9; i ++ ) {
  24444. this.coefficients[ i ].multiplyScalar( s );
  24445. }
  24446. return this;
  24447. }
  24448. lerp( sh, alpha ) {
  24449. for ( let i = 0; i < 9; i ++ ) {
  24450. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24451. }
  24452. return this;
  24453. }
  24454. equals( sh ) {
  24455. for ( let i = 0; i < 9; i ++ ) {
  24456. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24457. return false;
  24458. }
  24459. }
  24460. return true;
  24461. }
  24462. copy( sh ) {
  24463. return this.set( sh.coefficients );
  24464. }
  24465. clone() {
  24466. return new this.constructor().copy( this );
  24467. }
  24468. fromArray( array, offset = 0 ) {
  24469. const coefficients = this.coefficients;
  24470. for ( let i = 0; i < 9; i ++ ) {
  24471. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24472. }
  24473. return this;
  24474. }
  24475. toArray( array = [], offset = 0 ) {
  24476. const coefficients = this.coefficients;
  24477. for ( let i = 0; i < 9; i ++ ) {
  24478. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24479. }
  24480. return array;
  24481. }
  24482. // evaluate the basis functions
  24483. // shBasis is an Array[ 9 ]
  24484. static getBasisAt( normal, shBasis ) {
  24485. // normal is assumed to be unit length
  24486. const x = normal.x, y = normal.y, z = normal.z;
  24487. // band 0
  24488. shBasis[ 0 ] = 0.282095;
  24489. // band 1
  24490. shBasis[ 1 ] = 0.488603 * y;
  24491. shBasis[ 2 ] = 0.488603 * z;
  24492. shBasis[ 3 ] = 0.488603 * x;
  24493. // band 2
  24494. shBasis[ 4 ] = 1.092548 * x * y;
  24495. shBasis[ 5 ] = 1.092548 * y * z;
  24496. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24497. shBasis[ 7 ] = 1.092548 * x * z;
  24498. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24499. }
  24500. }
  24501. class LightProbe extends Light {
  24502. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24503. super( undefined, intensity );
  24504. this.isLightProbe = true;
  24505. this.sh = sh;
  24506. }
  24507. copy( source ) {
  24508. super.copy( source );
  24509. this.sh.copy( source.sh );
  24510. return this;
  24511. }
  24512. fromJSON( json ) {
  24513. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24514. this.sh.fromArray( json.sh );
  24515. return this;
  24516. }
  24517. toJSON( meta ) {
  24518. const data = super.toJSON( meta );
  24519. data.object.sh = this.sh.toArray();
  24520. return data;
  24521. }
  24522. }
  24523. class MaterialLoader extends Loader {
  24524. constructor( manager ) {
  24525. super( manager );
  24526. this.textures = {};
  24527. }
  24528. load( url, onLoad, onProgress, onError ) {
  24529. const scope = this;
  24530. const loader = new FileLoader( scope.manager );
  24531. loader.setPath( scope.path );
  24532. loader.setRequestHeader( scope.requestHeader );
  24533. loader.setWithCredentials( scope.withCredentials );
  24534. loader.load( url, function ( text ) {
  24535. try {
  24536. onLoad( scope.parse( JSON.parse( text ) ) );
  24537. } catch ( e ) {
  24538. if ( onError ) {
  24539. onError( e );
  24540. } else {
  24541. console.error( e );
  24542. }
  24543. scope.manager.itemError( url );
  24544. }
  24545. }, onProgress, onError );
  24546. }
  24547. parse( json ) {
  24548. const textures = this.textures;
  24549. function getTexture( name ) {
  24550. if ( textures[ name ] === undefined ) {
  24551. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24552. }
  24553. return textures[ name ];
  24554. }
  24555. const material = MaterialLoader.createMaterialFromType( json.type );
  24556. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24557. if ( json.name !== undefined ) material.name = json.name;
  24558. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24559. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24560. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24561. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24562. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24563. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24564. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24565. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24566. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24567. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24568. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24569. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24570. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24571. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24572. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24573. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24574. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24575. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24576. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24577. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24578. if ( json.fog !== undefined ) material.fog = json.fog;
  24579. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24580. if ( json.blending !== undefined ) material.blending = json.blending;
  24581. if ( json.combine !== undefined ) material.combine = json.combine;
  24582. if ( json.side !== undefined ) material.side = json.side;
  24583. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24584. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24585. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24586. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24587. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24588. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24589. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24590. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24591. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24592. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24593. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24594. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24595. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24596. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24597. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24598. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24599. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24600. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24601. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24602. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24603. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24604. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24605. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24606. if ( json.scale !== undefined ) material.scale = json.scale;
  24607. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24608. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24609. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24610. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24611. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24612. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24613. if ( json.visible !== undefined ) material.visible = json.visible;
  24614. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24615. if ( json.userData !== undefined ) material.userData = json.userData;
  24616. if ( json.vertexColors !== undefined ) {
  24617. if ( typeof json.vertexColors === 'number' ) {
  24618. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24619. } else {
  24620. material.vertexColors = json.vertexColors;
  24621. }
  24622. }
  24623. // Shader Material
  24624. if ( json.uniforms !== undefined ) {
  24625. for ( const name in json.uniforms ) {
  24626. const uniform = json.uniforms[ name ];
  24627. material.uniforms[ name ] = {};
  24628. switch ( uniform.type ) {
  24629. case 't':
  24630. material.uniforms[ name ].value = getTexture( uniform.value );
  24631. break;
  24632. case 'c':
  24633. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24634. break;
  24635. case 'v2':
  24636. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24637. break;
  24638. case 'v3':
  24639. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24640. break;
  24641. case 'v4':
  24642. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24643. break;
  24644. case 'm3':
  24645. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24646. break;
  24647. case 'm4':
  24648. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24649. break;
  24650. default:
  24651. material.uniforms[ name ].value = uniform.value;
  24652. }
  24653. }
  24654. }
  24655. if ( json.defines !== undefined ) material.defines = json.defines;
  24656. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24657. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24658. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24659. if ( json.extensions !== undefined ) {
  24660. for ( const key in json.extensions ) {
  24661. material.extensions[ key ] = json.extensions[ key ];
  24662. }
  24663. }
  24664. // for PointsMaterial
  24665. if ( json.size !== undefined ) material.size = json.size;
  24666. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24667. // maps
  24668. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24669. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24670. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24671. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24672. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24673. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24674. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24675. if ( json.normalScale !== undefined ) {
  24676. let normalScale = json.normalScale;
  24677. if ( Array.isArray( normalScale ) === false ) {
  24678. // Blender exporter used to export a scalar. See #7459
  24679. normalScale = [ normalScale, normalScale ];
  24680. }
  24681. material.normalScale = new Vector2().fromArray( normalScale );
  24682. }
  24683. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24684. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24685. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24686. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24687. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24688. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24689. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24690. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24691. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24692. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24693. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24694. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24695. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24696. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24697. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24698. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24699. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24700. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24701. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24702. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24703. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24704. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24705. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24706. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24707. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24708. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24709. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24710. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24711. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24712. return material;
  24713. }
  24714. setTextures( value ) {
  24715. this.textures = value;
  24716. return this;
  24717. }
  24718. static createMaterialFromType( type ) {
  24719. const materialLib = {
  24720. ShadowMaterial,
  24721. SpriteMaterial,
  24722. RawShaderMaterial,
  24723. ShaderMaterial,
  24724. PointsMaterial,
  24725. MeshPhysicalMaterial,
  24726. MeshStandardMaterial,
  24727. MeshPhongMaterial,
  24728. MeshToonMaterial,
  24729. MeshNormalMaterial,
  24730. MeshLambertMaterial,
  24731. MeshDepthMaterial,
  24732. MeshDistanceMaterial,
  24733. MeshBasicMaterial,
  24734. MeshMatcapMaterial,
  24735. LineDashedMaterial,
  24736. LineBasicMaterial,
  24737. Material
  24738. };
  24739. return new materialLib[ type ]();
  24740. }
  24741. }
  24742. class LoaderUtils {
  24743. static decodeText( array ) {
  24744. if ( typeof TextDecoder !== 'undefined' ) {
  24745. return new TextDecoder().decode( array );
  24746. }
  24747. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24748. // throws a "maximum call stack size exceeded" error for large arrays.
  24749. let s = '';
  24750. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24751. // Implicitly assumes little-endian.
  24752. s += String.fromCharCode( array[ i ] );
  24753. }
  24754. try {
  24755. // merges multi-byte utf-8 characters.
  24756. return decodeURIComponent( escape( s ) );
  24757. } catch ( e ) { // see #16358
  24758. return s;
  24759. }
  24760. }
  24761. static extractUrlBase( url ) {
  24762. const index = url.lastIndexOf( '/' );
  24763. if ( index === - 1 ) return './';
  24764. return url.slice( 0, index + 1 );
  24765. }
  24766. static resolveURL( url, path ) {
  24767. // Invalid URL
  24768. if ( typeof url !== 'string' || url === '' ) return '';
  24769. // Host Relative URL
  24770. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24771. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24772. }
  24773. // Absolute URL http://,https://,//
  24774. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24775. // Data URI
  24776. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24777. // Blob URL
  24778. if ( /^blob:.*$/i.test( url ) ) return url;
  24779. // Relative URL
  24780. return path + url;
  24781. }
  24782. }
  24783. class InstancedBufferGeometry extends BufferGeometry {
  24784. constructor() {
  24785. super();
  24786. this.isInstancedBufferGeometry = true;
  24787. this.type = 'InstancedBufferGeometry';
  24788. this.instanceCount = Infinity;
  24789. }
  24790. copy( source ) {
  24791. super.copy( source );
  24792. this.instanceCount = source.instanceCount;
  24793. return this;
  24794. }
  24795. clone() {
  24796. return new this.constructor().copy( this );
  24797. }
  24798. toJSON() {
  24799. const data = super.toJSON( this );
  24800. data.instanceCount = this.instanceCount;
  24801. data.isInstancedBufferGeometry = true;
  24802. return data;
  24803. }
  24804. }
  24805. class BufferGeometryLoader extends Loader {
  24806. constructor( manager ) {
  24807. super( manager );
  24808. }
  24809. load( url, onLoad, onProgress, onError ) {
  24810. const scope = this;
  24811. const loader = new FileLoader( scope.manager );
  24812. loader.setPath( scope.path );
  24813. loader.setRequestHeader( scope.requestHeader );
  24814. loader.setWithCredentials( scope.withCredentials );
  24815. loader.load( url, function ( text ) {
  24816. try {
  24817. onLoad( scope.parse( JSON.parse( text ) ) );
  24818. } catch ( e ) {
  24819. if ( onError ) {
  24820. onError( e );
  24821. } else {
  24822. console.error( e );
  24823. }
  24824. scope.manager.itemError( url );
  24825. }
  24826. }, onProgress, onError );
  24827. }
  24828. parse( json ) {
  24829. const interleavedBufferMap = {};
  24830. const arrayBufferMap = {};
  24831. function getInterleavedBuffer( json, uuid ) {
  24832. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24833. const interleavedBuffers = json.interleavedBuffers;
  24834. const interleavedBuffer = interleavedBuffers[ uuid ];
  24835. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24836. const array = getTypedArray( interleavedBuffer.type, buffer );
  24837. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24838. ib.uuid = interleavedBuffer.uuid;
  24839. interleavedBufferMap[ uuid ] = ib;
  24840. return ib;
  24841. }
  24842. function getArrayBuffer( json, uuid ) {
  24843. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24844. const arrayBuffers = json.arrayBuffers;
  24845. const arrayBuffer = arrayBuffers[ uuid ];
  24846. const ab = new Uint32Array( arrayBuffer ).buffer;
  24847. arrayBufferMap[ uuid ] = ab;
  24848. return ab;
  24849. }
  24850. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24851. const index = json.data.index;
  24852. if ( index !== undefined ) {
  24853. const typedArray = getTypedArray( index.type, index.array );
  24854. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24855. }
  24856. const attributes = json.data.attributes;
  24857. for ( const key in attributes ) {
  24858. const attribute = attributes[ key ];
  24859. let bufferAttribute;
  24860. if ( attribute.isInterleavedBufferAttribute ) {
  24861. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24862. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24863. } else {
  24864. const typedArray = getTypedArray( attribute.type, attribute.array );
  24865. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24866. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24867. }
  24868. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24869. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24870. if ( attribute.updateRange !== undefined ) {
  24871. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24872. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24873. }
  24874. geometry.setAttribute( key, bufferAttribute );
  24875. }
  24876. const morphAttributes = json.data.morphAttributes;
  24877. if ( morphAttributes ) {
  24878. for ( const key in morphAttributes ) {
  24879. const attributeArray = morphAttributes[ key ];
  24880. const array = [];
  24881. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24882. const attribute = attributeArray[ i ];
  24883. let bufferAttribute;
  24884. if ( attribute.isInterleavedBufferAttribute ) {
  24885. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24886. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24887. } else {
  24888. const typedArray = getTypedArray( attribute.type, attribute.array );
  24889. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24890. }
  24891. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24892. array.push( bufferAttribute );
  24893. }
  24894. geometry.morphAttributes[ key ] = array;
  24895. }
  24896. }
  24897. const morphTargetsRelative = json.data.morphTargetsRelative;
  24898. if ( morphTargetsRelative ) {
  24899. geometry.morphTargetsRelative = true;
  24900. }
  24901. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24902. if ( groups !== undefined ) {
  24903. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24904. const group = groups[ i ];
  24905. geometry.addGroup( group.start, group.count, group.materialIndex );
  24906. }
  24907. }
  24908. const boundingSphere = json.data.boundingSphere;
  24909. if ( boundingSphere !== undefined ) {
  24910. const center = new Vector3();
  24911. if ( boundingSphere.center !== undefined ) {
  24912. center.fromArray( boundingSphere.center );
  24913. }
  24914. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24915. }
  24916. if ( json.name ) geometry.name = json.name;
  24917. if ( json.userData ) geometry.userData = json.userData;
  24918. return geometry;
  24919. }
  24920. }
  24921. class ObjectLoader extends Loader {
  24922. constructor( manager ) {
  24923. super( manager );
  24924. }
  24925. load( url, onLoad, onProgress, onError ) {
  24926. const scope = this;
  24927. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24928. this.resourcePath = this.resourcePath || path;
  24929. const loader = new FileLoader( this.manager );
  24930. loader.setPath( this.path );
  24931. loader.setRequestHeader( this.requestHeader );
  24932. loader.setWithCredentials( this.withCredentials );
  24933. loader.load( url, function ( text ) {
  24934. let json = null;
  24935. try {
  24936. json = JSON.parse( text );
  24937. } catch ( error ) {
  24938. if ( onError !== undefined ) onError( error );
  24939. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24940. return;
  24941. }
  24942. const metadata = json.metadata;
  24943. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24944. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24945. return;
  24946. }
  24947. scope.parse( json, onLoad );
  24948. }, onProgress, onError );
  24949. }
  24950. async loadAsync( url, onProgress ) {
  24951. const scope = this;
  24952. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24953. this.resourcePath = this.resourcePath || path;
  24954. const loader = new FileLoader( this.manager );
  24955. loader.setPath( this.path );
  24956. loader.setRequestHeader( this.requestHeader );
  24957. loader.setWithCredentials( this.withCredentials );
  24958. const text = await loader.loadAsync( url, onProgress );
  24959. const json = JSON.parse( text );
  24960. const metadata = json.metadata;
  24961. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24962. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24963. }
  24964. return await scope.parseAsync( json );
  24965. }
  24966. parse( json, onLoad ) {
  24967. const animations = this.parseAnimations( json.animations );
  24968. const shapes = this.parseShapes( json.shapes );
  24969. const geometries = this.parseGeometries( json.geometries, shapes );
  24970. const images = this.parseImages( json.images, function () {
  24971. if ( onLoad !== undefined ) onLoad( object );
  24972. } );
  24973. const textures = this.parseTextures( json.textures, images );
  24974. const materials = this.parseMaterials( json.materials, textures );
  24975. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24976. const skeletons = this.parseSkeletons( json.skeletons, object );
  24977. this.bindSkeletons( object, skeletons );
  24978. //
  24979. if ( onLoad !== undefined ) {
  24980. let hasImages = false;
  24981. for ( const uuid in images ) {
  24982. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  24983. hasImages = true;
  24984. break;
  24985. }
  24986. }
  24987. if ( hasImages === false ) onLoad( object );
  24988. }
  24989. return object;
  24990. }
  24991. async parseAsync( json ) {
  24992. const animations = this.parseAnimations( json.animations );
  24993. const shapes = this.parseShapes( json.shapes );
  24994. const geometries = this.parseGeometries( json.geometries, shapes );
  24995. const images = await this.parseImagesAsync( json.images );
  24996. const textures = this.parseTextures( json.textures, images );
  24997. const materials = this.parseMaterials( json.materials, textures );
  24998. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24999. const skeletons = this.parseSkeletons( json.skeletons, object );
  25000. this.bindSkeletons( object, skeletons );
  25001. return object;
  25002. }
  25003. parseShapes( json ) {
  25004. const shapes = {};
  25005. if ( json !== undefined ) {
  25006. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25007. const shape = new Shape().fromJSON( json[ i ] );
  25008. shapes[ shape.uuid ] = shape;
  25009. }
  25010. }
  25011. return shapes;
  25012. }
  25013. parseSkeletons( json, object ) {
  25014. const skeletons = {};
  25015. const bones = {};
  25016. // generate bone lookup table
  25017. object.traverse( function ( child ) {
  25018. if ( child.isBone ) bones[ child.uuid ] = child;
  25019. } );
  25020. // create skeletons
  25021. if ( json !== undefined ) {
  25022. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25023. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25024. skeletons[ skeleton.uuid ] = skeleton;
  25025. }
  25026. }
  25027. return skeletons;
  25028. }
  25029. parseGeometries( json, shapes ) {
  25030. const geometries = {};
  25031. if ( json !== undefined ) {
  25032. const bufferGeometryLoader = new BufferGeometryLoader();
  25033. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25034. let geometry;
  25035. const data = json[ i ];
  25036. switch ( data.type ) {
  25037. case 'BufferGeometry':
  25038. case 'InstancedBufferGeometry':
  25039. geometry = bufferGeometryLoader.parse( data );
  25040. break;
  25041. default:
  25042. if ( data.type in Geometries ) {
  25043. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25044. } else {
  25045. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25046. }
  25047. }
  25048. geometry.uuid = data.uuid;
  25049. if ( data.name !== undefined ) geometry.name = data.name;
  25050. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25051. geometries[ data.uuid ] = geometry;
  25052. }
  25053. }
  25054. return geometries;
  25055. }
  25056. parseMaterials( json, textures ) {
  25057. const cache = {}; // MultiMaterial
  25058. const materials = {};
  25059. if ( json !== undefined ) {
  25060. const loader = new MaterialLoader();
  25061. loader.setTextures( textures );
  25062. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25063. const data = json[ i ];
  25064. if ( cache[ data.uuid ] === undefined ) {
  25065. cache[ data.uuid ] = loader.parse( data );
  25066. }
  25067. materials[ data.uuid ] = cache[ data.uuid ];
  25068. }
  25069. }
  25070. return materials;
  25071. }
  25072. parseAnimations( json ) {
  25073. const animations = {};
  25074. if ( json !== undefined ) {
  25075. for ( let i = 0; i < json.length; i ++ ) {
  25076. const data = json[ i ];
  25077. const clip = AnimationClip.parse( data );
  25078. animations[ clip.uuid ] = clip;
  25079. }
  25080. }
  25081. return animations;
  25082. }
  25083. parseImages( json, onLoad ) {
  25084. const scope = this;
  25085. const images = {};
  25086. let loader;
  25087. function loadImage( url ) {
  25088. scope.manager.itemStart( url );
  25089. return loader.load( url, function () {
  25090. scope.manager.itemEnd( url );
  25091. }, undefined, function () {
  25092. scope.manager.itemError( url );
  25093. scope.manager.itemEnd( url );
  25094. } );
  25095. }
  25096. function deserializeImage( image ) {
  25097. if ( typeof image === 'string' ) {
  25098. const url = image;
  25099. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25100. return loadImage( path );
  25101. } else {
  25102. if ( image.data ) {
  25103. return {
  25104. data: getTypedArray( image.type, image.data ),
  25105. width: image.width,
  25106. height: image.height
  25107. };
  25108. } else {
  25109. return null;
  25110. }
  25111. }
  25112. }
  25113. if ( json !== undefined && json.length > 0 ) {
  25114. const manager = new LoadingManager( onLoad );
  25115. loader = new ImageLoader( manager );
  25116. loader.setCrossOrigin( this.crossOrigin );
  25117. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25118. const image = json[ i ];
  25119. const url = image.url;
  25120. if ( Array.isArray( url ) ) {
  25121. // load array of images e.g CubeTexture
  25122. const imageArray = [];
  25123. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25124. const currentUrl = url[ j ];
  25125. const deserializedImage = deserializeImage( currentUrl );
  25126. if ( deserializedImage !== null ) {
  25127. if ( deserializedImage instanceof HTMLImageElement ) {
  25128. imageArray.push( deserializedImage );
  25129. } else {
  25130. // special case: handle array of data textures for cube textures
  25131. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25132. }
  25133. }
  25134. }
  25135. images[ image.uuid ] = new Source( imageArray );
  25136. } else {
  25137. // load single image
  25138. const deserializedImage = deserializeImage( image.url );
  25139. images[ image.uuid ] = new Source( deserializedImage );
  25140. }
  25141. }
  25142. }
  25143. return images;
  25144. }
  25145. async parseImagesAsync( json ) {
  25146. const scope = this;
  25147. const images = {};
  25148. let loader;
  25149. async function deserializeImage( image ) {
  25150. if ( typeof image === 'string' ) {
  25151. const url = image;
  25152. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25153. return await loader.loadAsync( path );
  25154. } else {
  25155. if ( image.data ) {
  25156. return {
  25157. data: getTypedArray( image.type, image.data ),
  25158. width: image.width,
  25159. height: image.height
  25160. };
  25161. } else {
  25162. return null;
  25163. }
  25164. }
  25165. }
  25166. if ( json !== undefined && json.length > 0 ) {
  25167. loader = new ImageLoader( this.manager );
  25168. loader.setCrossOrigin( this.crossOrigin );
  25169. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25170. const image = json[ i ];
  25171. const url = image.url;
  25172. if ( Array.isArray( url ) ) {
  25173. // load array of images e.g CubeTexture
  25174. const imageArray = [];
  25175. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25176. const currentUrl = url[ j ];
  25177. const deserializedImage = await deserializeImage( currentUrl );
  25178. if ( deserializedImage !== null ) {
  25179. if ( deserializedImage instanceof HTMLImageElement ) {
  25180. imageArray.push( deserializedImage );
  25181. } else {
  25182. // special case: handle array of data textures for cube textures
  25183. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25184. }
  25185. }
  25186. }
  25187. images[ image.uuid ] = new Source( imageArray );
  25188. } else {
  25189. // load single image
  25190. const deserializedImage = await deserializeImage( image.url );
  25191. images[ image.uuid ] = new Source( deserializedImage );
  25192. }
  25193. }
  25194. }
  25195. return images;
  25196. }
  25197. parseTextures( json, images ) {
  25198. function parseConstant( value, type ) {
  25199. if ( typeof value === 'number' ) return value;
  25200. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25201. return type[ value ];
  25202. }
  25203. const textures = {};
  25204. if ( json !== undefined ) {
  25205. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25206. const data = json[ i ];
  25207. if ( data.image === undefined ) {
  25208. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25209. }
  25210. if ( images[ data.image ] === undefined ) {
  25211. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25212. }
  25213. const source = images[ data.image ];
  25214. const image = source.data;
  25215. let texture;
  25216. if ( Array.isArray( image ) ) {
  25217. texture = new CubeTexture();
  25218. if ( image.length === 6 ) texture.needsUpdate = true;
  25219. } else {
  25220. if ( image && image.data ) {
  25221. texture = new DataTexture();
  25222. } else {
  25223. texture = new Texture();
  25224. }
  25225. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25226. }
  25227. texture.source = source;
  25228. texture.uuid = data.uuid;
  25229. if ( data.name !== undefined ) texture.name = data.name;
  25230. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25231. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25232. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25233. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25234. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25235. if ( data.wrap !== undefined ) {
  25236. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25237. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25238. }
  25239. if ( data.format !== undefined ) texture.format = data.format;
  25240. if ( data.type !== undefined ) texture.type = data.type;
  25241. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25242. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25243. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25244. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25245. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25246. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25247. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25248. if ( data.userData !== undefined ) texture.userData = data.userData;
  25249. textures[ data.uuid ] = texture;
  25250. }
  25251. }
  25252. return textures;
  25253. }
  25254. parseObject( data, geometries, materials, textures, animations ) {
  25255. let object;
  25256. function getGeometry( name ) {
  25257. if ( geometries[ name ] === undefined ) {
  25258. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25259. }
  25260. return geometries[ name ];
  25261. }
  25262. function getMaterial( name ) {
  25263. if ( name === undefined ) return undefined;
  25264. if ( Array.isArray( name ) ) {
  25265. const array = [];
  25266. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25267. const uuid = name[ i ];
  25268. if ( materials[ uuid ] === undefined ) {
  25269. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25270. }
  25271. array.push( materials[ uuid ] );
  25272. }
  25273. return array;
  25274. }
  25275. if ( materials[ name ] === undefined ) {
  25276. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25277. }
  25278. return materials[ name ];
  25279. }
  25280. function getTexture( uuid ) {
  25281. if ( textures[ uuid ] === undefined ) {
  25282. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25283. }
  25284. return textures[ uuid ];
  25285. }
  25286. let geometry, material;
  25287. switch ( data.type ) {
  25288. case 'Scene':
  25289. object = new Scene();
  25290. if ( data.background !== undefined ) {
  25291. if ( Number.isInteger( data.background ) ) {
  25292. object.background = new Color( data.background );
  25293. } else {
  25294. object.background = getTexture( data.background );
  25295. }
  25296. }
  25297. if ( data.environment !== undefined ) {
  25298. object.environment = getTexture( data.environment );
  25299. }
  25300. if ( data.fog !== undefined ) {
  25301. if ( data.fog.type === 'Fog' ) {
  25302. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25303. } else if ( data.fog.type === 'FogExp2' ) {
  25304. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25305. }
  25306. }
  25307. break;
  25308. case 'PerspectiveCamera':
  25309. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25310. if ( data.focus !== undefined ) object.focus = data.focus;
  25311. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25312. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25313. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25314. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25315. break;
  25316. case 'OrthographicCamera':
  25317. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25318. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25319. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25320. break;
  25321. case 'AmbientLight':
  25322. object = new AmbientLight( data.color, data.intensity );
  25323. break;
  25324. case 'DirectionalLight':
  25325. object = new DirectionalLight( data.color, data.intensity );
  25326. break;
  25327. case 'PointLight':
  25328. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25329. break;
  25330. case 'RectAreaLight':
  25331. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25332. break;
  25333. case 'SpotLight':
  25334. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25335. break;
  25336. case 'HemisphereLight':
  25337. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25338. break;
  25339. case 'LightProbe':
  25340. object = new LightProbe().fromJSON( data );
  25341. break;
  25342. case 'SkinnedMesh':
  25343. geometry = getGeometry( data.geometry );
  25344. material = getMaterial( data.material );
  25345. object = new SkinnedMesh( geometry, material );
  25346. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25347. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25348. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25349. break;
  25350. case 'Mesh':
  25351. geometry = getGeometry( data.geometry );
  25352. material = getMaterial( data.material );
  25353. object = new Mesh( geometry, material );
  25354. break;
  25355. case 'InstancedMesh':
  25356. geometry = getGeometry( data.geometry );
  25357. material = getMaterial( data.material );
  25358. const count = data.count;
  25359. const instanceMatrix = data.instanceMatrix;
  25360. const instanceColor = data.instanceColor;
  25361. object = new InstancedMesh( geometry, material, count );
  25362. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25363. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25364. break;
  25365. case 'LOD':
  25366. object = new LOD();
  25367. break;
  25368. case 'Line':
  25369. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25370. break;
  25371. case 'LineLoop':
  25372. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25373. break;
  25374. case 'LineSegments':
  25375. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25376. break;
  25377. case 'PointCloud':
  25378. case 'Points':
  25379. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25380. break;
  25381. case 'Sprite':
  25382. object = new Sprite( getMaterial( data.material ) );
  25383. break;
  25384. case 'Group':
  25385. object = new Group();
  25386. break;
  25387. case 'Bone':
  25388. object = new Bone();
  25389. break;
  25390. default:
  25391. object = new Object3D();
  25392. }
  25393. object.uuid = data.uuid;
  25394. if ( data.name !== undefined ) object.name = data.name;
  25395. if ( data.matrix !== undefined ) {
  25396. object.matrix.fromArray( data.matrix );
  25397. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25398. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25399. } else {
  25400. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25401. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25402. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25403. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25404. }
  25405. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25406. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25407. if ( data.shadow ) {
  25408. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25409. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25410. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25411. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25412. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25413. }
  25414. if ( data.visible !== undefined ) object.visible = data.visible;
  25415. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25416. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25417. if ( data.userData !== undefined ) object.userData = data.userData;
  25418. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25419. if ( data.children !== undefined ) {
  25420. const children = data.children;
  25421. for ( let i = 0; i < children.length; i ++ ) {
  25422. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25423. }
  25424. }
  25425. if ( data.animations !== undefined ) {
  25426. const objectAnimations = data.animations;
  25427. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25428. const uuid = objectAnimations[ i ];
  25429. object.animations.push( animations[ uuid ] );
  25430. }
  25431. }
  25432. if ( data.type === 'LOD' ) {
  25433. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25434. const levels = data.levels;
  25435. for ( let l = 0; l < levels.length; l ++ ) {
  25436. const level = levels[ l ];
  25437. const child = object.getObjectByProperty( 'uuid', level.object );
  25438. if ( child !== undefined ) {
  25439. object.addLevel( child, level.distance );
  25440. }
  25441. }
  25442. }
  25443. return object;
  25444. }
  25445. bindSkeletons( object, skeletons ) {
  25446. if ( Object.keys( skeletons ).length === 0 ) return;
  25447. object.traverse( function ( child ) {
  25448. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25449. const skeleton = skeletons[ child.skeleton ];
  25450. if ( skeleton === undefined ) {
  25451. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25452. } else {
  25453. child.bind( skeleton, child.bindMatrix );
  25454. }
  25455. }
  25456. } );
  25457. }
  25458. }
  25459. const TEXTURE_MAPPING = {
  25460. UVMapping: UVMapping,
  25461. CubeReflectionMapping: CubeReflectionMapping,
  25462. CubeRefractionMapping: CubeRefractionMapping,
  25463. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25464. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25465. CubeUVReflectionMapping: CubeUVReflectionMapping
  25466. };
  25467. const TEXTURE_WRAPPING = {
  25468. RepeatWrapping: RepeatWrapping,
  25469. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25470. MirroredRepeatWrapping: MirroredRepeatWrapping
  25471. };
  25472. const TEXTURE_FILTER = {
  25473. NearestFilter: NearestFilter,
  25474. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25475. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25476. LinearFilter: LinearFilter,
  25477. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25478. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25479. };
  25480. class ImageBitmapLoader extends Loader {
  25481. constructor( manager ) {
  25482. super( manager );
  25483. this.isImageBitmapLoader = true;
  25484. if ( typeof createImageBitmap === 'undefined' ) {
  25485. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25486. }
  25487. if ( typeof fetch === 'undefined' ) {
  25488. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25489. }
  25490. this.options = { premultiplyAlpha: 'none' };
  25491. }
  25492. setOptions( options ) {
  25493. this.options = options;
  25494. return this;
  25495. }
  25496. load( url, onLoad, onProgress, onError ) {
  25497. if ( url === undefined ) url = '';
  25498. if ( this.path !== undefined ) url = this.path + url;
  25499. url = this.manager.resolveURL( url );
  25500. const scope = this;
  25501. const cached = Cache.get( url );
  25502. if ( cached !== undefined ) {
  25503. scope.manager.itemStart( url );
  25504. setTimeout( function () {
  25505. if ( onLoad ) onLoad( cached );
  25506. scope.manager.itemEnd( url );
  25507. }, 0 );
  25508. return cached;
  25509. }
  25510. const fetchOptions = {};
  25511. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25512. fetchOptions.headers = this.requestHeader;
  25513. fetch( url, fetchOptions ).then( function ( res ) {
  25514. return res.blob();
  25515. } ).then( function ( blob ) {
  25516. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25517. } ).then( function ( imageBitmap ) {
  25518. Cache.add( url, imageBitmap );
  25519. if ( onLoad ) onLoad( imageBitmap );
  25520. scope.manager.itemEnd( url );
  25521. } ).catch( function ( e ) {
  25522. if ( onError ) onError( e );
  25523. scope.manager.itemError( url );
  25524. scope.manager.itemEnd( url );
  25525. } );
  25526. scope.manager.itemStart( url );
  25527. }
  25528. }
  25529. let _context;
  25530. const AudioContext = {
  25531. getContext: function () {
  25532. if ( _context === undefined ) {
  25533. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25534. }
  25535. return _context;
  25536. },
  25537. setContext: function ( value ) {
  25538. _context = value;
  25539. }
  25540. };
  25541. class AudioLoader extends Loader {
  25542. constructor( manager ) {
  25543. super( manager );
  25544. }
  25545. load( url, onLoad, onProgress, onError ) {
  25546. const scope = this;
  25547. const loader = new FileLoader( this.manager );
  25548. loader.setResponseType( 'arraybuffer' );
  25549. loader.setPath( this.path );
  25550. loader.setRequestHeader( this.requestHeader );
  25551. loader.setWithCredentials( this.withCredentials );
  25552. loader.load( url, function ( buffer ) {
  25553. try {
  25554. // Create a copy of the buffer. The `decodeAudioData` method
  25555. // detaches the buffer when complete, preventing reuse.
  25556. const bufferCopy = buffer.slice( 0 );
  25557. const context = AudioContext.getContext();
  25558. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25559. onLoad( audioBuffer );
  25560. } );
  25561. } catch ( e ) {
  25562. if ( onError ) {
  25563. onError( e );
  25564. } else {
  25565. console.error( e );
  25566. }
  25567. scope.manager.itemError( url );
  25568. }
  25569. }, onProgress, onError );
  25570. }
  25571. }
  25572. class HemisphereLightProbe extends LightProbe {
  25573. constructor( skyColor, groundColor, intensity = 1 ) {
  25574. super( undefined, intensity );
  25575. this.isHemisphereLightProbe = true;
  25576. const color1 = new Color().set( skyColor );
  25577. const color2 = new Color().set( groundColor );
  25578. const sky = new Vector3( color1.r, color1.g, color1.b );
  25579. const ground = new Vector3( color2.r, color2.g, color2.b );
  25580. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25581. const c0 = Math.sqrt( Math.PI );
  25582. const c1 = c0 * Math.sqrt( 0.75 );
  25583. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25584. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25585. }
  25586. }
  25587. class AmbientLightProbe extends LightProbe {
  25588. constructor( color, intensity = 1 ) {
  25589. super( undefined, intensity );
  25590. this.isAmbientLightProbe = true;
  25591. const color1 = new Color().set( color );
  25592. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25593. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25594. }
  25595. }
  25596. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25597. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25598. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25599. class StereoCamera {
  25600. constructor() {
  25601. this.type = 'StereoCamera';
  25602. this.aspect = 1;
  25603. this.eyeSep = 0.064;
  25604. this.cameraL = new PerspectiveCamera();
  25605. this.cameraL.layers.enable( 1 );
  25606. this.cameraL.matrixAutoUpdate = false;
  25607. this.cameraR = new PerspectiveCamera();
  25608. this.cameraR.layers.enable( 2 );
  25609. this.cameraR.matrixAutoUpdate = false;
  25610. this._cache = {
  25611. focus: null,
  25612. fov: null,
  25613. aspect: null,
  25614. near: null,
  25615. far: null,
  25616. zoom: null,
  25617. eyeSep: null
  25618. };
  25619. }
  25620. update( camera ) {
  25621. const cache = this._cache;
  25622. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25623. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25624. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25625. if ( needsUpdate ) {
  25626. cache.focus = camera.focus;
  25627. cache.fov = camera.fov;
  25628. cache.aspect = camera.aspect * this.aspect;
  25629. cache.near = camera.near;
  25630. cache.far = camera.far;
  25631. cache.zoom = camera.zoom;
  25632. cache.eyeSep = this.eyeSep;
  25633. // Off-axis stereoscopic effect based on
  25634. // http://paulbourke.net/stereographics/stereorender/
  25635. _projectionMatrix.copy( camera.projectionMatrix );
  25636. const eyeSepHalf = cache.eyeSep / 2;
  25637. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25638. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25639. let xmin, xmax;
  25640. // translate xOffset
  25641. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25642. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25643. // for left eye
  25644. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25645. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25646. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25647. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25648. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25649. // for right eye
  25650. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25651. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25652. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25653. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25654. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25655. }
  25656. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25657. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25658. }
  25659. }
  25660. class Clock {
  25661. constructor( autoStart = true ) {
  25662. this.autoStart = autoStart;
  25663. this.startTime = 0;
  25664. this.oldTime = 0;
  25665. this.elapsedTime = 0;
  25666. this.running = false;
  25667. }
  25668. start() {
  25669. this.startTime = now();
  25670. this.oldTime = this.startTime;
  25671. this.elapsedTime = 0;
  25672. this.running = true;
  25673. }
  25674. stop() {
  25675. this.getElapsedTime();
  25676. this.running = false;
  25677. this.autoStart = false;
  25678. }
  25679. getElapsedTime() {
  25680. this.getDelta();
  25681. return this.elapsedTime;
  25682. }
  25683. getDelta() {
  25684. let diff = 0;
  25685. if ( this.autoStart && ! this.running ) {
  25686. this.start();
  25687. return 0;
  25688. }
  25689. if ( this.running ) {
  25690. const newTime = now();
  25691. diff = ( newTime - this.oldTime ) / 1000;
  25692. this.oldTime = newTime;
  25693. this.elapsedTime += diff;
  25694. }
  25695. return diff;
  25696. }
  25697. }
  25698. function now() {
  25699. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25700. }
  25701. const _position$1 = /*@__PURE__*/ new Vector3();
  25702. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25703. const _scale$1 = /*@__PURE__*/ new Vector3();
  25704. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25705. class AudioListener extends Object3D {
  25706. constructor() {
  25707. super();
  25708. this.type = 'AudioListener';
  25709. this.context = AudioContext.getContext();
  25710. this.gain = this.context.createGain();
  25711. this.gain.connect( this.context.destination );
  25712. this.filter = null;
  25713. this.timeDelta = 0;
  25714. // private
  25715. this._clock = new Clock();
  25716. }
  25717. getInput() {
  25718. return this.gain;
  25719. }
  25720. removeFilter() {
  25721. if ( this.filter !== null ) {
  25722. this.gain.disconnect( this.filter );
  25723. this.filter.disconnect( this.context.destination );
  25724. this.gain.connect( this.context.destination );
  25725. this.filter = null;
  25726. }
  25727. return this;
  25728. }
  25729. getFilter() {
  25730. return this.filter;
  25731. }
  25732. setFilter( value ) {
  25733. if ( this.filter !== null ) {
  25734. this.gain.disconnect( this.filter );
  25735. this.filter.disconnect( this.context.destination );
  25736. } else {
  25737. this.gain.disconnect( this.context.destination );
  25738. }
  25739. this.filter = value;
  25740. this.gain.connect( this.filter );
  25741. this.filter.connect( this.context.destination );
  25742. return this;
  25743. }
  25744. getMasterVolume() {
  25745. return this.gain.gain.value;
  25746. }
  25747. setMasterVolume( value ) {
  25748. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25749. return this;
  25750. }
  25751. updateMatrixWorld( force ) {
  25752. super.updateMatrixWorld( force );
  25753. const listener = this.context.listener;
  25754. const up = this.up;
  25755. this.timeDelta = this._clock.getDelta();
  25756. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25757. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25758. if ( listener.positionX ) {
  25759. // code path for Chrome (see #14393)
  25760. const endTime = this.context.currentTime + this.timeDelta;
  25761. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25762. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25763. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25764. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25765. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25766. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25767. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25768. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25769. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25770. } else {
  25771. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25772. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25773. }
  25774. }
  25775. }
  25776. class Audio extends Object3D {
  25777. constructor( listener ) {
  25778. super();
  25779. this.type = 'Audio';
  25780. this.listener = listener;
  25781. this.context = listener.context;
  25782. this.gain = this.context.createGain();
  25783. this.gain.connect( listener.getInput() );
  25784. this.autoplay = false;
  25785. this.buffer = null;
  25786. this.detune = 0;
  25787. this.loop = false;
  25788. this.loopStart = 0;
  25789. this.loopEnd = 0;
  25790. this.offset = 0;
  25791. this.duration = undefined;
  25792. this.playbackRate = 1;
  25793. this.isPlaying = false;
  25794. this.hasPlaybackControl = true;
  25795. this.source = null;
  25796. this.sourceType = 'empty';
  25797. this._startedAt = 0;
  25798. this._progress = 0;
  25799. this._connected = false;
  25800. this.filters = [];
  25801. }
  25802. getOutput() {
  25803. return this.gain;
  25804. }
  25805. setNodeSource( audioNode ) {
  25806. this.hasPlaybackControl = false;
  25807. this.sourceType = 'audioNode';
  25808. this.source = audioNode;
  25809. this.connect();
  25810. return this;
  25811. }
  25812. setMediaElementSource( mediaElement ) {
  25813. this.hasPlaybackControl = false;
  25814. this.sourceType = 'mediaNode';
  25815. this.source = this.context.createMediaElementSource( mediaElement );
  25816. this.connect();
  25817. return this;
  25818. }
  25819. setMediaStreamSource( mediaStream ) {
  25820. this.hasPlaybackControl = false;
  25821. this.sourceType = 'mediaStreamNode';
  25822. this.source = this.context.createMediaStreamSource( mediaStream );
  25823. this.connect();
  25824. return this;
  25825. }
  25826. setBuffer( audioBuffer ) {
  25827. this.buffer = audioBuffer;
  25828. this.sourceType = 'buffer';
  25829. if ( this.autoplay ) this.play();
  25830. return this;
  25831. }
  25832. play( delay = 0 ) {
  25833. if ( this.isPlaying === true ) {
  25834. console.warn( 'THREE.Audio: Audio is already playing.' );
  25835. return;
  25836. }
  25837. if ( this.hasPlaybackControl === false ) {
  25838. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25839. return;
  25840. }
  25841. this._startedAt = this.context.currentTime + delay;
  25842. const source = this.context.createBufferSource();
  25843. source.buffer = this.buffer;
  25844. source.loop = this.loop;
  25845. source.loopStart = this.loopStart;
  25846. source.loopEnd = this.loopEnd;
  25847. source.onended = this.onEnded.bind( this );
  25848. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25849. this.isPlaying = true;
  25850. this.source = source;
  25851. this.setDetune( this.detune );
  25852. this.setPlaybackRate( this.playbackRate );
  25853. return this.connect();
  25854. }
  25855. pause() {
  25856. if ( this.hasPlaybackControl === false ) {
  25857. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25858. return;
  25859. }
  25860. if ( this.isPlaying === true ) {
  25861. // update current progress
  25862. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25863. if ( this.loop === true ) {
  25864. // ensure _progress does not exceed duration with looped audios
  25865. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25866. }
  25867. this.source.stop();
  25868. this.source.onended = null;
  25869. this.isPlaying = false;
  25870. }
  25871. return this;
  25872. }
  25873. stop() {
  25874. if ( this.hasPlaybackControl === false ) {
  25875. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25876. return;
  25877. }
  25878. this._progress = 0;
  25879. this.source.stop();
  25880. this.source.onended = null;
  25881. this.isPlaying = false;
  25882. return this;
  25883. }
  25884. connect() {
  25885. if ( this.filters.length > 0 ) {
  25886. this.source.connect( this.filters[ 0 ] );
  25887. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25888. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25889. }
  25890. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25891. } else {
  25892. this.source.connect( this.getOutput() );
  25893. }
  25894. this._connected = true;
  25895. return this;
  25896. }
  25897. disconnect() {
  25898. if ( this.filters.length > 0 ) {
  25899. this.source.disconnect( this.filters[ 0 ] );
  25900. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25901. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25902. }
  25903. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25904. } else {
  25905. this.source.disconnect( this.getOutput() );
  25906. }
  25907. this._connected = false;
  25908. return this;
  25909. }
  25910. getFilters() {
  25911. return this.filters;
  25912. }
  25913. setFilters( value ) {
  25914. if ( ! value ) value = [];
  25915. if ( this._connected === true ) {
  25916. this.disconnect();
  25917. this.filters = value.slice();
  25918. this.connect();
  25919. } else {
  25920. this.filters = value.slice();
  25921. }
  25922. return this;
  25923. }
  25924. setDetune( value ) {
  25925. this.detune = value;
  25926. if ( this.source.detune === undefined ) return; // only set detune when available
  25927. if ( this.isPlaying === true ) {
  25928. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25929. }
  25930. return this;
  25931. }
  25932. getDetune() {
  25933. return this.detune;
  25934. }
  25935. getFilter() {
  25936. return this.getFilters()[ 0 ];
  25937. }
  25938. setFilter( filter ) {
  25939. return this.setFilters( filter ? [ filter ] : [] );
  25940. }
  25941. setPlaybackRate( value ) {
  25942. if ( this.hasPlaybackControl === false ) {
  25943. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25944. return;
  25945. }
  25946. this.playbackRate = value;
  25947. if ( this.isPlaying === true ) {
  25948. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25949. }
  25950. return this;
  25951. }
  25952. getPlaybackRate() {
  25953. return this.playbackRate;
  25954. }
  25955. onEnded() {
  25956. this.isPlaying = false;
  25957. }
  25958. getLoop() {
  25959. if ( this.hasPlaybackControl === false ) {
  25960. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25961. return false;
  25962. }
  25963. return this.loop;
  25964. }
  25965. setLoop( value ) {
  25966. if ( this.hasPlaybackControl === false ) {
  25967. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25968. return;
  25969. }
  25970. this.loop = value;
  25971. if ( this.isPlaying === true ) {
  25972. this.source.loop = this.loop;
  25973. }
  25974. return this;
  25975. }
  25976. setLoopStart( value ) {
  25977. this.loopStart = value;
  25978. return this;
  25979. }
  25980. setLoopEnd( value ) {
  25981. this.loopEnd = value;
  25982. return this;
  25983. }
  25984. getVolume() {
  25985. return this.gain.gain.value;
  25986. }
  25987. setVolume( value ) {
  25988. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25989. return this;
  25990. }
  25991. }
  25992. const _position = /*@__PURE__*/ new Vector3();
  25993. const _quaternion = /*@__PURE__*/ new Quaternion();
  25994. const _scale = /*@__PURE__*/ new Vector3();
  25995. const _orientation = /*@__PURE__*/ new Vector3();
  25996. class PositionalAudio extends Audio {
  25997. constructor( listener ) {
  25998. super( listener );
  25999. this.panner = this.context.createPanner();
  26000. this.panner.panningModel = 'HRTF';
  26001. this.panner.connect( this.gain );
  26002. }
  26003. disconnect() {
  26004. super.disconnect();
  26005. this.panner.disconnect( this.gain );
  26006. }
  26007. getOutput() {
  26008. return this.panner;
  26009. }
  26010. getRefDistance() {
  26011. return this.panner.refDistance;
  26012. }
  26013. setRefDistance( value ) {
  26014. this.panner.refDistance = value;
  26015. return this;
  26016. }
  26017. getRolloffFactor() {
  26018. return this.panner.rolloffFactor;
  26019. }
  26020. setRolloffFactor( value ) {
  26021. this.panner.rolloffFactor = value;
  26022. return this;
  26023. }
  26024. getDistanceModel() {
  26025. return this.panner.distanceModel;
  26026. }
  26027. setDistanceModel( value ) {
  26028. this.panner.distanceModel = value;
  26029. return this;
  26030. }
  26031. getMaxDistance() {
  26032. return this.panner.maxDistance;
  26033. }
  26034. setMaxDistance( value ) {
  26035. this.panner.maxDistance = value;
  26036. return this;
  26037. }
  26038. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26039. this.panner.coneInnerAngle = coneInnerAngle;
  26040. this.panner.coneOuterAngle = coneOuterAngle;
  26041. this.panner.coneOuterGain = coneOuterGain;
  26042. return this;
  26043. }
  26044. updateMatrixWorld( force ) {
  26045. super.updateMatrixWorld( force );
  26046. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26047. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26048. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26049. const panner = this.panner;
  26050. if ( panner.positionX ) {
  26051. // code path for Chrome and Firefox (see #14393)
  26052. const endTime = this.context.currentTime + this.listener.timeDelta;
  26053. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26054. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26055. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26056. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26057. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26058. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26059. } else {
  26060. panner.setPosition( _position.x, _position.y, _position.z );
  26061. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26062. }
  26063. }
  26064. }
  26065. class AudioAnalyser {
  26066. constructor( audio, fftSize = 2048 ) {
  26067. this.analyser = audio.context.createAnalyser();
  26068. this.analyser.fftSize = fftSize;
  26069. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26070. audio.getOutput().connect( this.analyser );
  26071. }
  26072. getFrequencyData() {
  26073. this.analyser.getByteFrequencyData( this.data );
  26074. return this.data;
  26075. }
  26076. getAverageFrequency() {
  26077. let value = 0;
  26078. const data = this.getFrequencyData();
  26079. for ( let i = 0; i < data.length; i ++ ) {
  26080. value += data[ i ];
  26081. }
  26082. return value / data.length;
  26083. }
  26084. }
  26085. class PropertyMixer {
  26086. constructor( binding, typeName, valueSize ) {
  26087. this.binding = binding;
  26088. this.valueSize = valueSize;
  26089. let mixFunction,
  26090. mixFunctionAdditive,
  26091. setIdentity;
  26092. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26093. //
  26094. // interpolators can use .buffer as their .result
  26095. // the data then goes to 'incoming'
  26096. //
  26097. // 'accu0' and 'accu1' are used frame-interleaved for
  26098. // the cumulative result and are compared to detect
  26099. // changes
  26100. //
  26101. // 'orig' stores the original state of the property
  26102. //
  26103. // 'add' is used for additive cumulative results
  26104. //
  26105. // 'work' is optional and is only present for quaternion types. It is used
  26106. // to store intermediate quaternion multiplication results
  26107. switch ( typeName ) {
  26108. case 'quaternion':
  26109. mixFunction = this._slerp;
  26110. mixFunctionAdditive = this._slerpAdditive;
  26111. setIdentity = this._setAdditiveIdentityQuaternion;
  26112. this.buffer = new Float64Array( valueSize * 6 );
  26113. this._workIndex = 5;
  26114. break;
  26115. case 'string':
  26116. case 'bool':
  26117. mixFunction = this._select;
  26118. // Use the regular mix function and for additive on these types,
  26119. // additive is not relevant for non-numeric types
  26120. mixFunctionAdditive = this._select;
  26121. setIdentity = this._setAdditiveIdentityOther;
  26122. this.buffer = new Array( valueSize * 5 );
  26123. break;
  26124. default:
  26125. mixFunction = this._lerp;
  26126. mixFunctionAdditive = this._lerpAdditive;
  26127. setIdentity = this._setAdditiveIdentityNumeric;
  26128. this.buffer = new Float64Array( valueSize * 5 );
  26129. }
  26130. this._mixBufferRegion = mixFunction;
  26131. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26132. this._setIdentity = setIdentity;
  26133. this._origIndex = 3;
  26134. this._addIndex = 4;
  26135. this.cumulativeWeight = 0;
  26136. this.cumulativeWeightAdditive = 0;
  26137. this.useCount = 0;
  26138. this.referenceCount = 0;
  26139. }
  26140. // accumulate data in the 'incoming' region into 'accu<i>'
  26141. accumulate( accuIndex, weight ) {
  26142. // note: happily accumulating nothing when weight = 0, the caller knows
  26143. // the weight and shouldn't have made the call in the first place
  26144. const buffer = this.buffer,
  26145. stride = this.valueSize,
  26146. offset = accuIndex * stride + stride;
  26147. let currentWeight = this.cumulativeWeight;
  26148. if ( currentWeight === 0 ) {
  26149. // accuN := incoming * weight
  26150. for ( let i = 0; i !== stride; ++ i ) {
  26151. buffer[ offset + i ] = buffer[ i ];
  26152. }
  26153. currentWeight = weight;
  26154. } else {
  26155. // accuN := accuN + incoming * weight
  26156. currentWeight += weight;
  26157. const mix = weight / currentWeight;
  26158. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26159. }
  26160. this.cumulativeWeight = currentWeight;
  26161. }
  26162. // accumulate data in the 'incoming' region into 'add'
  26163. accumulateAdditive( weight ) {
  26164. const buffer = this.buffer,
  26165. stride = this.valueSize,
  26166. offset = stride * this._addIndex;
  26167. if ( this.cumulativeWeightAdditive === 0 ) {
  26168. // add = identity
  26169. this._setIdentity();
  26170. }
  26171. // add := add + incoming * weight
  26172. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26173. this.cumulativeWeightAdditive += weight;
  26174. }
  26175. // apply the state of 'accu<i>' to the binding when accus differ
  26176. apply( accuIndex ) {
  26177. const stride = this.valueSize,
  26178. buffer = this.buffer,
  26179. offset = accuIndex * stride + stride,
  26180. weight = this.cumulativeWeight,
  26181. weightAdditive = this.cumulativeWeightAdditive,
  26182. binding = this.binding;
  26183. this.cumulativeWeight = 0;
  26184. this.cumulativeWeightAdditive = 0;
  26185. if ( weight < 1 ) {
  26186. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26187. const originalValueOffset = stride * this._origIndex;
  26188. this._mixBufferRegion(
  26189. buffer, offset, originalValueOffset, 1 - weight, stride );
  26190. }
  26191. if ( weightAdditive > 0 ) {
  26192. // accuN := accuN + additive accuN
  26193. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26194. }
  26195. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26196. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26197. // value has changed -> update scene graph
  26198. binding.setValue( buffer, offset );
  26199. break;
  26200. }
  26201. }
  26202. }
  26203. // remember the state of the bound property and copy it to both accus
  26204. saveOriginalState() {
  26205. const binding = this.binding;
  26206. const buffer = this.buffer,
  26207. stride = this.valueSize,
  26208. originalValueOffset = stride * this._origIndex;
  26209. binding.getValue( buffer, originalValueOffset );
  26210. // accu[0..1] := orig -- initially detect changes against the original
  26211. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26212. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26213. }
  26214. // Add to identity for additive
  26215. this._setIdentity();
  26216. this.cumulativeWeight = 0;
  26217. this.cumulativeWeightAdditive = 0;
  26218. }
  26219. // apply the state previously taken via 'saveOriginalState' to the binding
  26220. restoreOriginalState() {
  26221. const originalValueOffset = this.valueSize * 3;
  26222. this.binding.setValue( this.buffer, originalValueOffset );
  26223. }
  26224. _setAdditiveIdentityNumeric() {
  26225. const startIndex = this._addIndex * this.valueSize;
  26226. const endIndex = startIndex + this.valueSize;
  26227. for ( let i = startIndex; i < endIndex; i ++ ) {
  26228. this.buffer[ i ] = 0;
  26229. }
  26230. }
  26231. _setAdditiveIdentityQuaternion() {
  26232. this._setAdditiveIdentityNumeric();
  26233. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26234. }
  26235. _setAdditiveIdentityOther() {
  26236. const startIndex = this._origIndex * this.valueSize;
  26237. const targetIndex = this._addIndex * this.valueSize;
  26238. for ( let i = 0; i < this.valueSize; i ++ ) {
  26239. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26240. }
  26241. }
  26242. // mix functions
  26243. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26244. if ( t >= 0.5 ) {
  26245. for ( let i = 0; i !== stride; ++ i ) {
  26246. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26247. }
  26248. }
  26249. }
  26250. _slerp( buffer, dstOffset, srcOffset, t ) {
  26251. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26252. }
  26253. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26254. const workOffset = this._workIndex * stride;
  26255. // Store result in intermediate buffer offset
  26256. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26257. // Slerp to the intermediate result
  26258. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26259. }
  26260. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26261. const s = 1 - t;
  26262. for ( let i = 0; i !== stride; ++ i ) {
  26263. const j = dstOffset + i;
  26264. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26265. }
  26266. }
  26267. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26268. for ( let i = 0; i !== stride; ++ i ) {
  26269. const j = dstOffset + i;
  26270. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26271. }
  26272. }
  26273. }
  26274. // Characters [].:/ are reserved for track binding syntax.
  26275. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26276. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26277. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26278. // only latin characters, and the unicode \p{L} is not yet supported. So
  26279. // instead, we exclude reserved characters and match everything else.
  26280. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26281. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26282. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26283. // be matched to parse the rest of the track name.
  26284. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26285. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26286. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26287. // Object on target node, and accessor. May not contain reserved
  26288. // characters. Accessor may contain any character except closing bracket.
  26289. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26290. // Property and accessor. May not contain reserved characters. Accessor may
  26291. // contain any non-bracket characters.
  26292. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26293. const _trackRe = new RegExp( ''
  26294. + '^'
  26295. + _directoryRe
  26296. + _nodeRe
  26297. + _objectRe
  26298. + _propertyRe
  26299. + '$'
  26300. );
  26301. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26302. class Composite {
  26303. constructor( targetGroup, path, optionalParsedPath ) {
  26304. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26305. this._targetGroup = targetGroup;
  26306. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26307. }
  26308. getValue( array, offset ) {
  26309. this.bind(); // bind all binding
  26310. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26311. binding = this._bindings[ firstValidIndex ];
  26312. // and only call .getValue on the first
  26313. if ( binding !== undefined ) binding.getValue( array, offset );
  26314. }
  26315. setValue( array, offset ) {
  26316. const bindings = this._bindings;
  26317. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26318. bindings[ i ].setValue( array, offset );
  26319. }
  26320. }
  26321. bind() {
  26322. const bindings = this._bindings;
  26323. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26324. bindings[ i ].bind();
  26325. }
  26326. }
  26327. unbind() {
  26328. const bindings = this._bindings;
  26329. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26330. bindings[ i ].unbind();
  26331. }
  26332. }
  26333. }
  26334. // Note: This class uses a State pattern on a per-method basis:
  26335. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26336. // prototype version of these methods with one that represents
  26337. // the bound state. When the property is not found, the methods
  26338. // become no-ops.
  26339. class PropertyBinding {
  26340. constructor( rootNode, path, parsedPath ) {
  26341. this.path = path;
  26342. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26343. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26344. this.rootNode = rootNode;
  26345. // initial state of these methods that calls 'bind'
  26346. this.getValue = this._getValue_unbound;
  26347. this.setValue = this._setValue_unbound;
  26348. }
  26349. static create( root, path, parsedPath ) {
  26350. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26351. return new PropertyBinding( root, path, parsedPath );
  26352. } else {
  26353. return new PropertyBinding.Composite( root, path, parsedPath );
  26354. }
  26355. }
  26356. /**
  26357. * Replaces spaces with underscores and removes unsupported characters from
  26358. * node names, to ensure compatibility with parseTrackName().
  26359. *
  26360. * @param {string} name Node name to be sanitized.
  26361. * @return {string}
  26362. */
  26363. static sanitizeNodeName( name ) {
  26364. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26365. }
  26366. static parseTrackName( trackName ) {
  26367. const matches = _trackRe.exec( trackName );
  26368. if ( matches === null ) {
  26369. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26370. }
  26371. const results = {
  26372. // directoryName: matches[ 1 ], // (tschw) currently unused
  26373. nodeName: matches[ 2 ],
  26374. objectName: matches[ 3 ],
  26375. objectIndex: matches[ 4 ],
  26376. propertyName: matches[ 5 ], // required
  26377. propertyIndex: matches[ 6 ]
  26378. };
  26379. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26380. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26381. const objectName = results.nodeName.substring( lastDot + 1 );
  26382. // Object names must be checked against an allowlist. Otherwise, there
  26383. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26384. // 'bar' could be the objectName, or part of a nodeName (which can
  26385. // include '.' characters).
  26386. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26387. results.nodeName = results.nodeName.substring( 0, lastDot );
  26388. results.objectName = objectName;
  26389. }
  26390. }
  26391. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26392. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26393. }
  26394. return results;
  26395. }
  26396. static findNode( root, nodeName ) {
  26397. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26398. return root;
  26399. }
  26400. // search into skeleton bones.
  26401. if ( root.skeleton ) {
  26402. const bone = root.skeleton.getBoneByName( nodeName );
  26403. if ( bone !== undefined ) {
  26404. return bone;
  26405. }
  26406. }
  26407. // search into node subtree.
  26408. if ( root.children ) {
  26409. const searchNodeSubtree = function ( children ) {
  26410. for ( let i = 0; i < children.length; i ++ ) {
  26411. const childNode = children[ i ];
  26412. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26413. return childNode;
  26414. }
  26415. const result = searchNodeSubtree( childNode.children );
  26416. if ( result ) return result;
  26417. }
  26418. return null;
  26419. };
  26420. const subTreeNode = searchNodeSubtree( root.children );
  26421. if ( subTreeNode ) {
  26422. return subTreeNode;
  26423. }
  26424. }
  26425. return null;
  26426. }
  26427. // these are used to "bind" a nonexistent property
  26428. _getValue_unavailable() {}
  26429. _setValue_unavailable() {}
  26430. // Getters
  26431. _getValue_direct( buffer, offset ) {
  26432. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26433. }
  26434. _getValue_array( buffer, offset ) {
  26435. const source = this.resolvedProperty;
  26436. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26437. buffer[ offset ++ ] = source[ i ];
  26438. }
  26439. }
  26440. _getValue_arrayElement( buffer, offset ) {
  26441. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26442. }
  26443. _getValue_toArray( buffer, offset ) {
  26444. this.resolvedProperty.toArray( buffer, offset );
  26445. }
  26446. // Direct
  26447. _setValue_direct( buffer, offset ) {
  26448. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26449. }
  26450. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26451. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26452. this.targetObject.needsUpdate = true;
  26453. }
  26454. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26455. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26456. this.targetObject.matrixWorldNeedsUpdate = true;
  26457. }
  26458. // EntireArray
  26459. _setValue_array( buffer, offset ) {
  26460. const dest = this.resolvedProperty;
  26461. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26462. dest[ i ] = buffer[ offset ++ ];
  26463. }
  26464. }
  26465. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26466. const dest = this.resolvedProperty;
  26467. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26468. dest[ i ] = buffer[ offset ++ ];
  26469. }
  26470. this.targetObject.needsUpdate = true;
  26471. }
  26472. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26473. const dest = this.resolvedProperty;
  26474. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26475. dest[ i ] = buffer[ offset ++ ];
  26476. }
  26477. this.targetObject.matrixWorldNeedsUpdate = true;
  26478. }
  26479. // ArrayElement
  26480. _setValue_arrayElement( buffer, offset ) {
  26481. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26482. }
  26483. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26484. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26485. this.targetObject.needsUpdate = true;
  26486. }
  26487. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26488. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26489. this.targetObject.matrixWorldNeedsUpdate = true;
  26490. }
  26491. // HasToFromArray
  26492. _setValue_fromArray( buffer, offset ) {
  26493. this.resolvedProperty.fromArray( buffer, offset );
  26494. }
  26495. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26496. this.resolvedProperty.fromArray( buffer, offset );
  26497. this.targetObject.needsUpdate = true;
  26498. }
  26499. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26500. this.resolvedProperty.fromArray( buffer, offset );
  26501. this.targetObject.matrixWorldNeedsUpdate = true;
  26502. }
  26503. _getValue_unbound( targetArray, offset ) {
  26504. this.bind();
  26505. this.getValue( targetArray, offset );
  26506. }
  26507. _setValue_unbound( sourceArray, offset ) {
  26508. this.bind();
  26509. this.setValue( sourceArray, offset );
  26510. }
  26511. // create getter / setter pair for a property in the scene graph
  26512. bind() {
  26513. let targetObject = this.node;
  26514. const parsedPath = this.parsedPath;
  26515. const objectName = parsedPath.objectName;
  26516. const propertyName = parsedPath.propertyName;
  26517. let propertyIndex = parsedPath.propertyIndex;
  26518. if ( ! targetObject ) {
  26519. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26520. this.node = targetObject;
  26521. }
  26522. // set fail state so we can just 'return' on error
  26523. this.getValue = this._getValue_unavailable;
  26524. this.setValue = this._setValue_unavailable;
  26525. // ensure there is a value node
  26526. if ( ! targetObject ) {
  26527. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26528. return;
  26529. }
  26530. if ( objectName ) {
  26531. let objectIndex = parsedPath.objectIndex;
  26532. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26533. switch ( objectName ) {
  26534. case 'materials':
  26535. if ( ! targetObject.material ) {
  26536. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26537. return;
  26538. }
  26539. if ( ! targetObject.material.materials ) {
  26540. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26541. return;
  26542. }
  26543. targetObject = targetObject.material.materials;
  26544. break;
  26545. case 'bones':
  26546. if ( ! targetObject.skeleton ) {
  26547. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26548. return;
  26549. }
  26550. // potential future optimization: skip this if propertyIndex is already an integer
  26551. // and convert the integer string to a true integer.
  26552. targetObject = targetObject.skeleton.bones;
  26553. // support resolving morphTarget names into indices.
  26554. for ( let i = 0; i < targetObject.length; i ++ ) {
  26555. if ( targetObject[ i ].name === objectIndex ) {
  26556. objectIndex = i;
  26557. break;
  26558. }
  26559. }
  26560. break;
  26561. case 'map':
  26562. if ( 'map' in targetObject ) {
  26563. targetObject = targetObject.map;
  26564. break;
  26565. }
  26566. if ( ! targetObject.material ) {
  26567. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26568. return;
  26569. }
  26570. if ( ! targetObject.material.map ) {
  26571. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26572. return;
  26573. }
  26574. targetObject = targetObject.material.map;
  26575. break;
  26576. default:
  26577. if ( targetObject[ objectName ] === undefined ) {
  26578. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26579. return;
  26580. }
  26581. targetObject = targetObject[ objectName ];
  26582. }
  26583. if ( objectIndex !== undefined ) {
  26584. if ( targetObject[ objectIndex ] === undefined ) {
  26585. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26586. return;
  26587. }
  26588. targetObject = targetObject[ objectIndex ];
  26589. }
  26590. }
  26591. // resolve property
  26592. const nodeProperty = targetObject[ propertyName ];
  26593. if ( nodeProperty === undefined ) {
  26594. const nodeName = parsedPath.nodeName;
  26595. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26596. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26597. return;
  26598. }
  26599. // determine versioning scheme
  26600. let versioning = this.Versioning.None;
  26601. this.targetObject = targetObject;
  26602. if ( targetObject.needsUpdate !== undefined ) { // material
  26603. versioning = this.Versioning.NeedsUpdate;
  26604. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26605. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26606. }
  26607. // determine how the property gets bound
  26608. let bindingType = this.BindingType.Direct;
  26609. if ( propertyIndex !== undefined ) {
  26610. // access a sub element of the property array (only primitives are supported right now)
  26611. if ( propertyName === 'morphTargetInfluences' ) {
  26612. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26613. // support resolving morphTarget names into indices.
  26614. if ( ! targetObject.geometry ) {
  26615. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26616. return;
  26617. }
  26618. if ( ! targetObject.geometry.morphAttributes ) {
  26619. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26620. return;
  26621. }
  26622. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26623. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26624. }
  26625. }
  26626. bindingType = this.BindingType.ArrayElement;
  26627. this.resolvedProperty = nodeProperty;
  26628. this.propertyIndex = propertyIndex;
  26629. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26630. // must use copy for Object3D.Euler/Quaternion
  26631. bindingType = this.BindingType.HasFromToArray;
  26632. this.resolvedProperty = nodeProperty;
  26633. } else if ( Array.isArray( nodeProperty ) ) {
  26634. bindingType = this.BindingType.EntireArray;
  26635. this.resolvedProperty = nodeProperty;
  26636. } else {
  26637. this.propertyName = propertyName;
  26638. }
  26639. // select getter / setter
  26640. this.getValue = this.GetterByBindingType[ bindingType ];
  26641. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26642. }
  26643. unbind() {
  26644. this.node = null;
  26645. // back to the prototype version of getValue / setValue
  26646. // note: avoiding to mutate the shape of 'this' via 'delete'
  26647. this.getValue = this._getValue_unbound;
  26648. this.setValue = this._setValue_unbound;
  26649. }
  26650. }
  26651. PropertyBinding.Composite = Composite;
  26652. PropertyBinding.prototype.BindingType = {
  26653. Direct: 0,
  26654. EntireArray: 1,
  26655. ArrayElement: 2,
  26656. HasFromToArray: 3
  26657. };
  26658. PropertyBinding.prototype.Versioning = {
  26659. None: 0,
  26660. NeedsUpdate: 1,
  26661. MatrixWorldNeedsUpdate: 2
  26662. };
  26663. PropertyBinding.prototype.GetterByBindingType = [
  26664. PropertyBinding.prototype._getValue_direct,
  26665. PropertyBinding.prototype._getValue_array,
  26666. PropertyBinding.prototype._getValue_arrayElement,
  26667. PropertyBinding.prototype._getValue_toArray,
  26668. ];
  26669. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26670. [
  26671. // Direct
  26672. PropertyBinding.prototype._setValue_direct,
  26673. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26674. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26675. ], [
  26676. // EntireArray
  26677. PropertyBinding.prototype._setValue_array,
  26678. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26679. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26680. ], [
  26681. // ArrayElement
  26682. PropertyBinding.prototype._setValue_arrayElement,
  26683. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26684. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26685. ], [
  26686. // HasToFromArray
  26687. PropertyBinding.prototype._setValue_fromArray,
  26688. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26689. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26690. ]
  26691. ];
  26692. /**
  26693. *
  26694. * A group of objects that receives a shared animation state.
  26695. *
  26696. * Usage:
  26697. *
  26698. * - Add objects you would otherwise pass as 'root' to the
  26699. * constructor or the .clipAction method of AnimationMixer.
  26700. *
  26701. * - Instead pass this object as 'root'.
  26702. *
  26703. * - You can also add and remove objects later when the mixer
  26704. * is running.
  26705. *
  26706. * Note:
  26707. *
  26708. * Objects of this class appear as one object to the mixer,
  26709. * so cache control of the individual objects must be done
  26710. * on the group.
  26711. *
  26712. * Limitation:
  26713. *
  26714. * - The animated properties must be compatible among the
  26715. * all objects in the group.
  26716. *
  26717. * - A single property can either be controlled through a
  26718. * target group or directly, but not both.
  26719. */
  26720. class AnimationObjectGroup {
  26721. constructor() {
  26722. this.isAnimationObjectGroup = true;
  26723. this.uuid = generateUUID();
  26724. // cached objects followed by the active ones
  26725. this._objects = Array.prototype.slice.call( arguments );
  26726. this.nCachedObjects_ = 0; // threshold
  26727. // note: read by PropertyBinding.Composite
  26728. const indices = {};
  26729. this._indicesByUUID = indices; // for bookkeeping
  26730. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26731. indices[ arguments[ i ].uuid ] = i;
  26732. }
  26733. this._paths = []; // inside: string
  26734. this._parsedPaths = []; // inside: { we don't care, here }
  26735. this._bindings = []; // inside: Array< PropertyBinding >
  26736. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26737. const scope = this;
  26738. this.stats = {
  26739. objects: {
  26740. get total() {
  26741. return scope._objects.length;
  26742. },
  26743. get inUse() {
  26744. return this.total - scope.nCachedObjects_;
  26745. }
  26746. },
  26747. get bindingsPerObject() {
  26748. return scope._bindings.length;
  26749. }
  26750. };
  26751. }
  26752. add() {
  26753. const objects = this._objects,
  26754. indicesByUUID = this._indicesByUUID,
  26755. paths = this._paths,
  26756. parsedPaths = this._parsedPaths,
  26757. bindings = this._bindings,
  26758. nBindings = bindings.length;
  26759. let knownObject = undefined,
  26760. nObjects = objects.length,
  26761. nCachedObjects = this.nCachedObjects_;
  26762. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26763. const object = arguments[ i ],
  26764. uuid = object.uuid;
  26765. let index = indicesByUUID[ uuid ];
  26766. if ( index === undefined ) {
  26767. // unknown object -> add it to the ACTIVE region
  26768. index = nObjects ++;
  26769. indicesByUUID[ uuid ] = index;
  26770. objects.push( object );
  26771. // accounting is done, now do the same for all bindings
  26772. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26773. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26774. }
  26775. } else if ( index < nCachedObjects ) {
  26776. knownObject = objects[ index ];
  26777. // move existing object to the ACTIVE region
  26778. const firstActiveIndex = -- nCachedObjects,
  26779. lastCachedObject = objects[ firstActiveIndex ];
  26780. indicesByUUID[ lastCachedObject.uuid ] = index;
  26781. objects[ index ] = lastCachedObject;
  26782. indicesByUUID[ uuid ] = firstActiveIndex;
  26783. objects[ firstActiveIndex ] = object;
  26784. // accounting is done, now do the same for all bindings
  26785. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26786. const bindingsForPath = bindings[ j ],
  26787. lastCached = bindingsForPath[ firstActiveIndex ];
  26788. let binding = bindingsForPath[ index ];
  26789. bindingsForPath[ index ] = lastCached;
  26790. if ( binding === undefined ) {
  26791. // since we do not bother to create new bindings
  26792. // for objects that are cached, the binding may
  26793. // or may not exist
  26794. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26795. }
  26796. bindingsForPath[ firstActiveIndex ] = binding;
  26797. }
  26798. } else if ( objects[ index ] !== knownObject ) {
  26799. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26800. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26801. } // else the object is already where we want it to be
  26802. } // for arguments
  26803. this.nCachedObjects_ = nCachedObjects;
  26804. }
  26805. remove() {
  26806. const objects = this._objects,
  26807. indicesByUUID = this._indicesByUUID,
  26808. bindings = this._bindings,
  26809. nBindings = bindings.length;
  26810. let nCachedObjects = this.nCachedObjects_;
  26811. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26812. const object = arguments[ i ],
  26813. uuid = object.uuid,
  26814. index = indicesByUUID[ uuid ];
  26815. if ( index !== undefined && index >= nCachedObjects ) {
  26816. // move existing object into the CACHED region
  26817. const lastCachedIndex = nCachedObjects ++,
  26818. firstActiveObject = objects[ lastCachedIndex ];
  26819. indicesByUUID[ firstActiveObject.uuid ] = index;
  26820. objects[ index ] = firstActiveObject;
  26821. indicesByUUID[ uuid ] = lastCachedIndex;
  26822. objects[ lastCachedIndex ] = object;
  26823. // accounting is done, now do the same for all bindings
  26824. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26825. const bindingsForPath = bindings[ j ],
  26826. firstActive = bindingsForPath[ lastCachedIndex ],
  26827. binding = bindingsForPath[ index ];
  26828. bindingsForPath[ index ] = firstActive;
  26829. bindingsForPath[ lastCachedIndex ] = binding;
  26830. }
  26831. }
  26832. } // for arguments
  26833. this.nCachedObjects_ = nCachedObjects;
  26834. }
  26835. // remove & forget
  26836. uncache() {
  26837. const objects = this._objects,
  26838. indicesByUUID = this._indicesByUUID,
  26839. bindings = this._bindings,
  26840. nBindings = bindings.length;
  26841. let nCachedObjects = this.nCachedObjects_,
  26842. nObjects = objects.length;
  26843. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26844. const object = arguments[ i ],
  26845. uuid = object.uuid,
  26846. index = indicesByUUID[ uuid ];
  26847. if ( index !== undefined ) {
  26848. delete indicesByUUID[ uuid ];
  26849. if ( index < nCachedObjects ) {
  26850. // object is cached, shrink the CACHED region
  26851. const firstActiveIndex = -- nCachedObjects,
  26852. lastCachedObject = objects[ firstActiveIndex ],
  26853. lastIndex = -- nObjects,
  26854. lastObject = objects[ lastIndex ];
  26855. // last cached object takes this object's place
  26856. indicesByUUID[ lastCachedObject.uuid ] = index;
  26857. objects[ index ] = lastCachedObject;
  26858. // last object goes to the activated slot and pop
  26859. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26860. objects[ firstActiveIndex ] = lastObject;
  26861. objects.pop();
  26862. // accounting is done, now do the same for all bindings
  26863. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26864. const bindingsForPath = bindings[ j ],
  26865. lastCached = bindingsForPath[ firstActiveIndex ],
  26866. last = bindingsForPath[ lastIndex ];
  26867. bindingsForPath[ index ] = lastCached;
  26868. bindingsForPath[ firstActiveIndex ] = last;
  26869. bindingsForPath.pop();
  26870. }
  26871. } else {
  26872. // object is active, just swap with the last and pop
  26873. const lastIndex = -- nObjects,
  26874. lastObject = objects[ lastIndex ];
  26875. if ( lastIndex > 0 ) {
  26876. indicesByUUID[ lastObject.uuid ] = index;
  26877. }
  26878. objects[ index ] = lastObject;
  26879. objects.pop();
  26880. // accounting is done, now do the same for all bindings
  26881. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26882. const bindingsForPath = bindings[ j ];
  26883. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26884. bindingsForPath.pop();
  26885. }
  26886. } // cached or active
  26887. } // if object is known
  26888. } // for arguments
  26889. this.nCachedObjects_ = nCachedObjects;
  26890. }
  26891. // Internal interface used by befriended PropertyBinding.Composite:
  26892. subscribe_( path, parsedPath ) {
  26893. // returns an array of bindings for the given path that is changed
  26894. // according to the contained objects in the group
  26895. const indicesByPath = this._bindingsIndicesByPath;
  26896. let index = indicesByPath[ path ];
  26897. const bindings = this._bindings;
  26898. if ( index !== undefined ) return bindings[ index ];
  26899. const paths = this._paths,
  26900. parsedPaths = this._parsedPaths,
  26901. objects = this._objects,
  26902. nObjects = objects.length,
  26903. nCachedObjects = this.nCachedObjects_,
  26904. bindingsForPath = new Array( nObjects );
  26905. index = bindings.length;
  26906. indicesByPath[ path ] = index;
  26907. paths.push( path );
  26908. parsedPaths.push( parsedPath );
  26909. bindings.push( bindingsForPath );
  26910. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26911. const object = objects[ i ];
  26912. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26913. }
  26914. return bindingsForPath;
  26915. }
  26916. unsubscribe_( path ) {
  26917. // tells the group to forget about a property path and no longer
  26918. // update the array previously obtained with 'subscribe_'
  26919. const indicesByPath = this._bindingsIndicesByPath,
  26920. index = indicesByPath[ path ];
  26921. if ( index !== undefined ) {
  26922. const paths = this._paths,
  26923. parsedPaths = this._parsedPaths,
  26924. bindings = this._bindings,
  26925. lastBindingsIndex = bindings.length - 1,
  26926. lastBindings = bindings[ lastBindingsIndex ],
  26927. lastBindingsPath = path[ lastBindingsIndex ];
  26928. indicesByPath[ lastBindingsPath ] = index;
  26929. bindings[ index ] = lastBindings;
  26930. bindings.pop();
  26931. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26932. parsedPaths.pop();
  26933. paths[ index ] = paths[ lastBindingsIndex ];
  26934. paths.pop();
  26935. }
  26936. }
  26937. }
  26938. class AnimationAction {
  26939. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26940. this._mixer = mixer;
  26941. this._clip = clip;
  26942. this._localRoot = localRoot;
  26943. this.blendMode = blendMode;
  26944. const tracks = clip.tracks,
  26945. nTracks = tracks.length,
  26946. interpolants = new Array( nTracks );
  26947. const interpolantSettings = {
  26948. endingStart: ZeroCurvatureEnding,
  26949. endingEnd: ZeroCurvatureEnding
  26950. };
  26951. for ( let i = 0; i !== nTracks; ++ i ) {
  26952. const interpolant = tracks[ i ].createInterpolant( null );
  26953. interpolants[ i ] = interpolant;
  26954. interpolant.settings = interpolantSettings;
  26955. }
  26956. this._interpolantSettings = interpolantSettings;
  26957. this._interpolants = interpolants; // bound by the mixer
  26958. // inside: PropertyMixer (managed by the mixer)
  26959. this._propertyBindings = new Array( nTracks );
  26960. this._cacheIndex = null; // for the memory manager
  26961. this._byClipCacheIndex = null; // for the memory manager
  26962. this._timeScaleInterpolant = null;
  26963. this._weightInterpolant = null;
  26964. this.loop = LoopRepeat;
  26965. this._loopCount = - 1;
  26966. // global mixer time when the action is to be started
  26967. // it's set back to 'null' upon start of the action
  26968. this._startTime = null;
  26969. // scaled local time of the action
  26970. // gets clamped or wrapped to 0..clip.duration according to loop
  26971. this.time = 0;
  26972. this.timeScale = 1;
  26973. this._effectiveTimeScale = 1;
  26974. this.weight = 1;
  26975. this._effectiveWeight = 1;
  26976. this.repetitions = Infinity; // no. of repetitions when looping
  26977. this.paused = false; // true -> zero effective time scale
  26978. this.enabled = true; // false -> zero effective weight
  26979. this.clampWhenFinished = false;// keep feeding the last frame?
  26980. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26981. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26982. }
  26983. // State & Scheduling
  26984. play() {
  26985. this._mixer._activateAction( this );
  26986. return this;
  26987. }
  26988. stop() {
  26989. this._mixer._deactivateAction( this );
  26990. return this.reset();
  26991. }
  26992. reset() {
  26993. this.paused = false;
  26994. this.enabled = true;
  26995. this.time = 0; // restart clip
  26996. this._loopCount = - 1;// forget previous loops
  26997. this._startTime = null;// forget scheduling
  26998. return this.stopFading().stopWarping();
  26999. }
  27000. isRunning() {
  27001. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27002. this._startTime === null && this._mixer._isActiveAction( this );
  27003. }
  27004. // return true when play has been called
  27005. isScheduled() {
  27006. return this._mixer._isActiveAction( this );
  27007. }
  27008. startAt( time ) {
  27009. this._startTime = time;
  27010. return this;
  27011. }
  27012. setLoop( mode, repetitions ) {
  27013. this.loop = mode;
  27014. this.repetitions = repetitions;
  27015. return this;
  27016. }
  27017. // Weight
  27018. // set the weight stopping any scheduled fading
  27019. // although .enabled = false yields an effective weight of zero, this
  27020. // method does *not* change .enabled, because it would be confusing
  27021. setEffectiveWeight( weight ) {
  27022. this.weight = weight;
  27023. // note: same logic as when updated at runtime
  27024. this._effectiveWeight = this.enabled ? weight : 0;
  27025. return this.stopFading();
  27026. }
  27027. // return the weight considering fading and .enabled
  27028. getEffectiveWeight() {
  27029. return this._effectiveWeight;
  27030. }
  27031. fadeIn( duration ) {
  27032. return this._scheduleFading( duration, 0, 1 );
  27033. }
  27034. fadeOut( duration ) {
  27035. return this._scheduleFading( duration, 1, 0 );
  27036. }
  27037. crossFadeFrom( fadeOutAction, duration, warp ) {
  27038. fadeOutAction.fadeOut( duration );
  27039. this.fadeIn( duration );
  27040. if ( warp ) {
  27041. const fadeInDuration = this._clip.duration,
  27042. fadeOutDuration = fadeOutAction._clip.duration,
  27043. startEndRatio = fadeOutDuration / fadeInDuration,
  27044. endStartRatio = fadeInDuration / fadeOutDuration;
  27045. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27046. this.warp( endStartRatio, 1.0, duration );
  27047. }
  27048. return this;
  27049. }
  27050. crossFadeTo( fadeInAction, duration, warp ) {
  27051. return fadeInAction.crossFadeFrom( this, duration, warp );
  27052. }
  27053. stopFading() {
  27054. const weightInterpolant = this._weightInterpolant;
  27055. if ( weightInterpolant !== null ) {
  27056. this._weightInterpolant = null;
  27057. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27058. }
  27059. return this;
  27060. }
  27061. // Time Scale Control
  27062. // set the time scale stopping any scheduled warping
  27063. // although .paused = true yields an effective time scale of zero, this
  27064. // method does *not* change .paused, because it would be confusing
  27065. setEffectiveTimeScale( timeScale ) {
  27066. this.timeScale = timeScale;
  27067. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27068. return this.stopWarping();
  27069. }
  27070. // return the time scale considering warping and .paused
  27071. getEffectiveTimeScale() {
  27072. return this._effectiveTimeScale;
  27073. }
  27074. setDuration( duration ) {
  27075. this.timeScale = this._clip.duration / duration;
  27076. return this.stopWarping();
  27077. }
  27078. syncWith( action ) {
  27079. this.time = action.time;
  27080. this.timeScale = action.timeScale;
  27081. return this.stopWarping();
  27082. }
  27083. halt( duration ) {
  27084. return this.warp( this._effectiveTimeScale, 0, duration );
  27085. }
  27086. warp( startTimeScale, endTimeScale, duration ) {
  27087. const mixer = this._mixer,
  27088. now = mixer.time,
  27089. timeScale = this.timeScale;
  27090. let interpolant = this._timeScaleInterpolant;
  27091. if ( interpolant === null ) {
  27092. interpolant = mixer._lendControlInterpolant();
  27093. this._timeScaleInterpolant = interpolant;
  27094. }
  27095. const times = interpolant.parameterPositions,
  27096. values = interpolant.sampleValues;
  27097. times[ 0 ] = now;
  27098. times[ 1 ] = now + duration;
  27099. values[ 0 ] = startTimeScale / timeScale;
  27100. values[ 1 ] = endTimeScale / timeScale;
  27101. return this;
  27102. }
  27103. stopWarping() {
  27104. const timeScaleInterpolant = this._timeScaleInterpolant;
  27105. if ( timeScaleInterpolant !== null ) {
  27106. this._timeScaleInterpolant = null;
  27107. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27108. }
  27109. return this;
  27110. }
  27111. // Object Accessors
  27112. getMixer() {
  27113. return this._mixer;
  27114. }
  27115. getClip() {
  27116. return this._clip;
  27117. }
  27118. getRoot() {
  27119. return this._localRoot || this._mixer._root;
  27120. }
  27121. // Interna
  27122. _update( time, deltaTime, timeDirection, accuIndex ) {
  27123. // called by the mixer
  27124. if ( ! this.enabled ) {
  27125. // call ._updateWeight() to update ._effectiveWeight
  27126. this._updateWeight( time );
  27127. return;
  27128. }
  27129. const startTime = this._startTime;
  27130. if ( startTime !== null ) {
  27131. // check for scheduled start of action
  27132. const timeRunning = ( time - startTime ) * timeDirection;
  27133. if ( timeRunning < 0 || timeDirection === 0 ) {
  27134. deltaTime = 0;
  27135. } else {
  27136. this._startTime = null; // unschedule
  27137. deltaTime = timeDirection * timeRunning;
  27138. }
  27139. }
  27140. // apply time scale and advance time
  27141. deltaTime *= this._updateTimeScale( time );
  27142. const clipTime = this._updateTime( deltaTime );
  27143. // note: _updateTime may disable the action resulting in
  27144. // an effective weight of 0
  27145. const weight = this._updateWeight( time );
  27146. if ( weight > 0 ) {
  27147. const interpolants = this._interpolants;
  27148. const propertyMixers = this._propertyBindings;
  27149. switch ( this.blendMode ) {
  27150. case AdditiveAnimationBlendMode:
  27151. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27152. interpolants[ j ].evaluate( clipTime );
  27153. propertyMixers[ j ].accumulateAdditive( weight );
  27154. }
  27155. break;
  27156. case NormalAnimationBlendMode:
  27157. default:
  27158. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27159. interpolants[ j ].evaluate( clipTime );
  27160. propertyMixers[ j ].accumulate( accuIndex, weight );
  27161. }
  27162. }
  27163. }
  27164. }
  27165. _updateWeight( time ) {
  27166. let weight = 0;
  27167. if ( this.enabled ) {
  27168. weight = this.weight;
  27169. const interpolant = this._weightInterpolant;
  27170. if ( interpolant !== null ) {
  27171. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27172. weight *= interpolantValue;
  27173. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27174. this.stopFading();
  27175. if ( interpolantValue === 0 ) {
  27176. // faded out, disable
  27177. this.enabled = false;
  27178. }
  27179. }
  27180. }
  27181. }
  27182. this._effectiveWeight = weight;
  27183. return weight;
  27184. }
  27185. _updateTimeScale( time ) {
  27186. let timeScale = 0;
  27187. if ( ! this.paused ) {
  27188. timeScale = this.timeScale;
  27189. const interpolant = this._timeScaleInterpolant;
  27190. if ( interpolant !== null ) {
  27191. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27192. timeScale *= interpolantValue;
  27193. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27194. this.stopWarping();
  27195. if ( timeScale === 0 ) {
  27196. // motion has halted, pause
  27197. this.paused = true;
  27198. } else {
  27199. // warp done - apply final time scale
  27200. this.timeScale = timeScale;
  27201. }
  27202. }
  27203. }
  27204. }
  27205. this._effectiveTimeScale = timeScale;
  27206. return timeScale;
  27207. }
  27208. _updateTime( deltaTime ) {
  27209. const duration = this._clip.duration;
  27210. const loop = this.loop;
  27211. let time = this.time + deltaTime;
  27212. let loopCount = this._loopCount;
  27213. const pingPong = ( loop === LoopPingPong );
  27214. if ( deltaTime === 0 ) {
  27215. if ( loopCount === - 1 ) return time;
  27216. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27217. }
  27218. if ( loop === LoopOnce ) {
  27219. if ( loopCount === - 1 ) {
  27220. // just started
  27221. this._loopCount = 0;
  27222. this._setEndings( true, true, false );
  27223. }
  27224. handle_stop: {
  27225. if ( time >= duration ) {
  27226. time = duration;
  27227. } else if ( time < 0 ) {
  27228. time = 0;
  27229. } else {
  27230. this.time = time;
  27231. break handle_stop;
  27232. }
  27233. if ( this.clampWhenFinished ) this.paused = true;
  27234. else this.enabled = false;
  27235. this.time = time;
  27236. this._mixer.dispatchEvent( {
  27237. type: 'finished', action: this,
  27238. direction: deltaTime < 0 ? - 1 : 1
  27239. } );
  27240. }
  27241. } else { // repetitive Repeat or PingPong
  27242. if ( loopCount === - 1 ) {
  27243. // just started
  27244. if ( deltaTime >= 0 ) {
  27245. loopCount = 0;
  27246. this._setEndings( true, this.repetitions === 0, pingPong );
  27247. } else {
  27248. // when looping in reverse direction, the initial
  27249. // transition through zero counts as a repetition,
  27250. // so leave loopCount at -1
  27251. this._setEndings( this.repetitions === 0, true, pingPong );
  27252. }
  27253. }
  27254. if ( time >= duration || time < 0 ) {
  27255. // wrap around
  27256. const loopDelta = Math.floor( time / duration ); // signed
  27257. time -= duration * loopDelta;
  27258. loopCount += Math.abs( loopDelta );
  27259. const pending = this.repetitions - loopCount;
  27260. if ( pending <= 0 ) {
  27261. // have to stop (switch state, clamp time, fire event)
  27262. if ( this.clampWhenFinished ) this.paused = true;
  27263. else this.enabled = false;
  27264. time = deltaTime > 0 ? duration : 0;
  27265. this.time = time;
  27266. this._mixer.dispatchEvent( {
  27267. type: 'finished', action: this,
  27268. direction: deltaTime > 0 ? 1 : - 1
  27269. } );
  27270. } else {
  27271. // keep running
  27272. if ( pending === 1 ) {
  27273. // entering the last round
  27274. const atStart = deltaTime < 0;
  27275. this._setEndings( atStart, ! atStart, pingPong );
  27276. } else {
  27277. this._setEndings( false, false, pingPong );
  27278. }
  27279. this._loopCount = loopCount;
  27280. this.time = time;
  27281. this._mixer.dispatchEvent( {
  27282. type: 'loop', action: this, loopDelta: loopDelta
  27283. } );
  27284. }
  27285. } else {
  27286. this.time = time;
  27287. }
  27288. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27289. // invert time for the "pong round"
  27290. return duration - time;
  27291. }
  27292. }
  27293. return time;
  27294. }
  27295. _setEndings( atStart, atEnd, pingPong ) {
  27296. const settings = this._interpolantSettings;
  27297. if ( pingPong ) {
  27298. settings.endingStart = ZeroSlopeEnding;
  27299. settings.endingEnd = ZeroSlopeEnding;
  27300. } else {
  27301. // assuming for LoopOnce atStart == atEnd == true
  27302. if ( atStart ) {
  27303. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27304. } else {
  27305. settings.endingStart = WrapAroundEnding;
  27306. }
  27307. if ( atEnd ) {
  27308. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27309. } else {
  27310. settings.endingEnd = WrapAroundEnding;
  27311. }
  27312. }
  27313. }
  27314. _scheduleFading( duration, weightNow, weightThen ) {
  27315. const mixer = this._mixer, now = mixer.time;
  27316. let interpolant = this._weightInterpolant;
  27317. if ( interpolant === null ) {
  27318. interpolant = mixer._lendControlInterpolant();
  27319. this._weightInterpolant = interpolant;
  27320. }
  27321. const times = interpolant.parameterPositions,
  27322. values = interpolant.sampleValues;
  27323. times[ 0 ] = now;
  27324. values[ 0 ] = weightNow;
  27325. times[ 1 ] = now + duration;
  27326. values[ 1 ] = weightThen;
  27327. return this;
  27328. }
  27329. }
  27330. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27331. class AnimationMixer extends EventDispatcher {
  27332. constructor( root ) {
  27333. super();
  27334. this._root = root;
  27335. this._initMemoryManager();
  27336. this._accuIndex = 0;
  27337. this.time = 0;
  27338. this.timeScale = 1.0;
  27339. }
  27340. _bindAction( action, prototypeAction ) {
  27341. const root = action._localRoot || this._root,
  27342. tracks = action._clip.tracks,
  27343. nTracks = tracks.length,
  27344. bindings = action._propertyBindings,
  27345. interpolants = action._interpolants,
  27346. rootUuid = root.uuid,
  27347. bindingsByRoot = this._bindingsByRootAndName;
  27348. let bindingsByName = bindingsByRoot[ rootUuid ];
  27349. if ( bindingsByName === undefined ) {
  27350. bindingsByName = {};
  27351. bindingsByRoot[ rootUuid ] = bindingsByName;
  27352. }
  27353. for ( let i = 0; i !== nTracks; ++ i ) {
  27354. const track = tracks[ i ],
  27355. trackName = track.name;
  27356. let binding = bindingsByName[ trackName ];
  27357. if ( binding !== undefined ) {
  27358. ++ binding.referenceCount;
  27359. bindings[ i ] = binding;
  27360. } else {
  27361. binding = bindings[ i ];
  27362. if ( binding !== undefined ) {
  27363. // existing binding, make sure the cache knows
  27364. if ( binding._cacheIndex === null ) {
  27365. ++ binding.referenceCount;
  27366. this._addInactiveBinding( binding, rootUuid, trackName );
  27367. }
  27368. continue;
  27369. }
  27370. const path = prototypeAction && prototypeAction.
  27371. _propertyBindings[ i ].binding.parsedPath;
  27372. binding = new PropertyMixer(
  27373. PropertyBinding.create( root, trackName, path ),
  27374. track.ValueTypeName, track.getValueSize() );
  27375. ++ binding.referenceCount;
  27376. this._addInactiveBinding( binding, rootUuid, trackName );
  27377. bindings[ i ] = binding;
  27378. }
  27379. interpolants[ i ].resultBuffer = binding.buffer;
  27380. }
  27381. }
  27382. _activateAction( action ) {
  27383. if ( ! this._isActiveAction( action ) ) {
  27384. if ( action._cacheIndex === null ) {
  27385. // this action has been forgotten by the cache, but the user
  27386. // appears to be still using it -> rebind
  27387. const rootUuid = ( action._localRoot || this._root ).uuid,
  27388. clipUuid = action._clip.uuid,
  27389. actionsForClip = this._actionsByClip[ clipUuid ];
  27390. this._bindAction( action,
  27391. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27392. this._addInactiveAction( action, clipUuid, rootUuid );
  27393. }
  27394. const bindings = action._propertyBindings;
  27395. // increment reference counts / sort out state
  27396. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27397. const binding = bindings[ i ];
  27398. if ( binding.useCount ++ === 0 ) {
  27399. this._lendBinding( binding );
  27400. binding.saveOriginalState();
  27401. }
  27402. }
  27403. this._lendAction( action );
  27404. }
  27405. }
  27406. _deactivateAction( action ) {
  27407. if ( this._isActiveAction( action ) ) {
  27408. const bindings = action._propertyBindings;
  27409. // decrement reference counts / sort out state
  27410. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27411. const binding = bindings[ i ];
  27412. if ( -- binding.useCount === 0 ) {
  27413. binding.restoreOriginalState();
  27414. this._takeBackBinding( binding );
  27415. }
  27416. }
  27417. this._takeBackAction( action );
  27418. }
  27419. }
  27420. // Memory manager
  27421. _initMemoryManager() {
  27422. this._actions = []; // 'nActiveActions' followed by inactive ones
  27423. this._nActiveActions = 0;
  27424. this._actionsByClip = {};
  27425. // inside:
  27426. // {
  27427. // knownActions: Array< AnimationAction > - used as prototypes
  27428. // actionByRoot: AnimationAction - lookup
  27429. // }
  27430. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27431. this._nActiveBindings = 0;
  27432. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27433. this._controlInterpolants = []; // same game as above
  27434. this._nActiveControlInterpolants = 0;
  27435. const scope = this;
  27436. this.stats = {
  27437. actions: {
  27438. get total() {
  27439. return scope._actions.length;
  27440. },
  27441. get inUse() {
  27442. return scope._nActiveActions;
  27443. }
  27444. },
  27445. bindings: {
  27446. get total() {
  27447. return scope._bindings.length;
  27448. },
  27449. get inUse() {
  27450. return scope._nActiveBindings;
  27451. }
  27452. },
  27453. controlInterpolants: {
  27454. get total() {
  27455. return scope._controlInterpolants.length;
  27456. },
  27457. get inUse() {
  27458. return scope._nActiveControlInterpolants;
  27459. }
  27460. }
  27461. };
  27462. }
  27463. // Memory management for AnimationAction objects
  27464. _isActiveAction( action ) {
  27465. const index = action._cacheIndex;
  27466. return index !== null && index < this._nActiveActions;
  27467. }
  27468. _addInactiveAction( action, clipUuid, rootUuid ) {
  27469. const actions = this._actions,
  27470. actionsByClip = this._actionsByClip;
  27471. let actionsForClip = actionsByClip[ clipUuid ];
  27472. if ( actionsForClip === undefined ) {
  27473. actionsForClip = {
  27474. knownActions: [ action ],
  27475. actionByRoot: {}
  27476. };
  27477. action._byClipCacheIndex = 0;
  27478. actionsByClip[ clipUuid ] = actionsForClip;
  27479. } else {
  27480. const knownActions = actionsForClip.knownActions;
  27481. action._byClipCacheIndex = knownActions.length;
  27482. knownActions.push( action );
  27483. }
  27484. action._cacheIndex = actions.length;
  27485. actions.push( action );
  27486. actionsForClip.actionByRoot[ rootUuid ] = action;
  27487. }
  27488. _removeInactiveAction( action ) {
  27489. const actions = this._actions,
  27490. lastInactiveAction = actions[ actions.length - 1 ],
  27491. cacheIndex = action._cacheIndex;
  27492. lastInactiveAction._cacheIndex = cacheIndex;
  27493. actions[ cacheIndex ] = lastInactiveAction;
  27494. actions.pop();
  27495. action._cacheIndex = null;
  27496. const clipUuid = action._clip.uuid,
  27497. actionsByClip = this._actionsByClip,
  27498. actionsForClip = actionsByClip[ clipUuid ],
  27499. knownActionsForClip = actionsForClip.knownActions,
  27500. lastKnownAction =
  27501. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27502. byClipCacheIndex = action._byClipCacheIndex;
  27503. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27504. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27505. knownActionsForClip.pop();
  27506. action._byClipCacheIndex = null;
  27507. const actionByRoot = actionsForClip.actionByRoot,
  27508. rootUuid = ( action._localRoot || this._root ).uuid;
  27509. delete actionByRoot[ rootUuid ];
  27510. if ( knownActionsForClip.length === 0 ) {
  27511. delete actionsByClip[ clipUuid ];
  27512. }
  27513. this._removeInactiveBindingsForAction( action );
  27514. }
  27515. _removeInactiveBindingsForAction( action ) {
  27516. const bindings = action._propertyBindings;
  27517. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27518. const binding = bindings[ i ];
  27519. if ( -- binding.referenceCount === 0 ) {
  27520. this._removeInactiveBinding( binding );
  27521. }
  27522. }
  27523. }
  27524. _lendAction( action ) {
  27525. // [ active actions | inactive actions ]
  27526. // [ active actions >| inactive actions ]
  27527. // s a
  27528. // <-swap->
  27529. // a s
  27530. const actions = this._actions,
  27531. prevIndex = action._cacheIndex,
  27532. lastActiveIndex = this._nActiveActions ++,
  27533. firstInactiveAction = actions[ lastActiveIndex ];
  27534. action._cacheIndex = lastActiveIndex;
  27535. actions[ lastActiveIndex ] = action;
  27536. firstInactiveAction._cacheIndex = prevIndex;
  27537. actions[ prevIndex ] = firstInactiveAction;
  27538. }
  27539. _takeBackAction( action ) {
  27540. // [ active actions | inactive actions ]
  27541. // [ active actions |< inactive actions ]
  27542. // a s
  27543. // <-swap->
  27544. // s a
  27545. const actions = this._actions,
  27546. prevIndex = action._cacheIndex,
  27547. firstInactiveIndex = -- this._nActiveActions,
  27548. lastActiveAction = actions[ firstInactiveIndex ];
  27549. action._cacheIndex = firstInactiveIndex;
  27550. actions[ firstInactiveIndex ] = action;
  27551. lastActiveAction._cacheIndex = prevIndex;
  27552. actions[ prevIndex ] = lastActiveAction;
  27553. }
  27554. // Memory management for PropertyMixer objects
  27555. _addInactiveBinding( binding, rootUuid, trackName ) {
  27556. const bindingsByRoot = this._bindingsByRootAndName,
  27557. bindings = this._bindings;
  27558. let bindingByName = bindingsByRoot[ rootUuid ];
  27559. if ( bindingByName === undefined ) {
  27560. bindingByName = {};
  27561. bindingsByRoot[ rootUuid ] = bindingByName;
  27562. }
  27563. bindingByName[ trackName ] = binding;
  27564. binding._cacheIndex = bindings.length;
  27565. bindings.push( binding );
  27566. }
  27567. _removeInactiveBinding( binding ) {
  27568. const bindings = this._bindings,
  27569. propBinding = binding.binding,
  27570. rootUuid = propBinding.rootNode.uuid,
  27571. trackName = propBinding.path,
  27572. bindingsByRoot = this._bindingsByRootAndName,
  27573. bindingByName = bindingsByRoot[ rootUuid ],
  27574. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27575. cacheIndex = binding._cacheIndex;
  27576. lastInactiveBinding._cacheIndex = cacheIndex;
  27577. bindings[ cacheIndex ] = lastInactiveBinding;
  27578. bindings.pop();
  27579. delete bindingByName[ trackName ];
  27580. if ( Object.keys( bindingByName ).length === 0 ) {
  27581. delete bindingsByRoot[ rootUuid ];
  27582. }
  27583. }
  27584. _lendBinding( binding ) {
  27585. const bindings = this._bindings,
  27586. prevIndex = binding._cacheIndex,
  27587. lastActiveIndex = this._nActiveBindings ++,
  27588. firstInactiveBinding = bindings[ lastActiveIndex ];
  27589. binding._cacheIndex = lastActiveIndex;
  27590. bindings[ lastActiveIndex ] = binding;
  27591. firstInactiveBinding._cacheIndex = prevIndex;
  27592. bindings[ prevIndex ] = firstInactiveBinding;
  27593. }
  27594. _takeBackBinding( binding ) {
  27595. const bindings = this._bindings,
  27596. prevIndex = binding._cacheIndex,
  27597. firstInactiveIndex = -- this._nActiveBindings,
  27598. lastActiveBinding = bindings[ firstInactiveIndex ];
  27599. binding._cacheIndex = firstInactiveIndex;
  27600. bindings[ firstInactiveIndex ] = binding;
  27601. lastActiveBinding._cacheIndex = prevIndex;
  27602. bindings[ prevIndex ] = lastActiveBinding;
  27603. }
  27604. // Memory management of Interpolants for weight and time scale
  27605. _lendControlInterpolant() {
  27606. const interpolants = this._controlInterpolants,
  27607. lastActiveIndex = this._nActiveControlInterpolants ++;
  27608. let interpolant = interpolants[ lastActiveIndex ];
  27609. if ( interpolant === undefined ) {
  27610. interpolant = new LinearInterpolant(
  27611. new Float32Array( 2 ), new Float32Array( 2 ),
  27612. 1, _controlInterpolantsResultBuffer );
  27613. interpolant.__cacheIndex = lastActiveIndex;
  27614. interpolants[ lastActiveIndex ] = interpolant;
  27615. }
  27616. return interpolant;
  27617. }
  27618. _takeBackControlInterpolant( interpolant ) {
  27619. const interpolants = this._controlInterpolants,
  27620. prevIndex = interpolant.__cacheIndex,
  27621. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27622. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27623. interpolant.__cacheIndex = firstInactiveIndex;
  27624. interpolants[ firstInactiveIndex ] = interpolant;
  27625. lastActiveInterpolant.__cacheIndex = prevIndex;
  27626. interpolants[ prevIndex ] = lastActiveInterpolant;
  27627. }
  27628. // return an action for a clip optionally using a custom root target
  27629. // object (this method allocates a lot of dynamic memory in case a
  27630. // previously unknown clip/root combination is specified)
  27631. clipAction( clip, optionalRoot, blendMode ) {
  27632. const root = optionalRoot || this._root,
  27633. rootUuid = root.uuid;
  27634. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27635. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27636. const actionsForClip = this._actionsByClip[ clipUuid ];
  27637. let prototypeAction = null;
  27638. if ( blendMode === undefined ) {
  27639. if ( clipObject !== null ) {
  27640. blendMode = clipObject.blendMode;
  27641. } else {
  27642. blendMode = NormalAnimationBlendMode;
  27643. }
  27644. }
  27645. if ( actionsForClip !== undefined ) {
  27646. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27647. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27648. return existingAction;
  27649. }
  27650. // we know the clip, so we don't have to parse all
  27651. // the bindings again but can just copy
  27652. prototypeAction = actionsForClip.knownActions[ 0 ];
  27653. // also, take the clip from the prototype action
  27654. if ( clipObject === null )
  27655. clipObject = prototypeAction._clip;
  27656. }
  27657. // clip must be known when specified via string
  27658. if ( clipObject === null ) return null;
  27659. // allocate all resources required to run it
  27660. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27661. this._bindAction( newAction, prototypeAction );
  27662. // and make the action known to the memory manager
  27663. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27664. return newAction;
  27665. }
  27666. // get an existing action
  27667. existingAction( clip, optionalRoot ) {
  27668. const root = optionalRoot || this._root,
  27669. rootUuid = root.uuid,
  27670. clipObject = typeof clip === 'string' ?
  27671. AnimationClip.findByName( root, clip ) : clip,
  27672. clipUuid = clipObject ? clipObject.uuid : clip,
  27673. actionsForClip = this._actionsByClip[ clipUuid ];
  27674. if ( actionsForClip !== undefined ) {
  27675. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27676. }
  27677. return null;
  27678. }
  27679. // deactivates all previously scheduled actions
  27680. stopAllAction() {
  27681. const actions = this._actions,
  27682. nActions = this._nActiveActions;
  27683. for ( let i = nActions - 1; i >= 0; -- i ) {
  27684. actions[ i ].stop();
  27685. }
  27686. return this;
  27687. }
  27688. // advance the time and update apply the animation
  27689. update( deltaTime ) {
  27690. deltaTime *= this.timeScale;
  27691. const actions = this._actions,
  27692. nActions = this._nActiveActions,
  27693. time = this.time += deltaTime,
  27694. timeDirection = Math.sign( deltaTime ),
  27695. accuIndex = this._accuIndex ^= 1;
  27696. // run active actions
  27697. for ( let i = 0; i !== nActions; ++ i ) {
  27698. const action = actions[ i ];
  27699. action._update( time, deltaTime, timeDirection, accuIndex );
  27700. }
  27701. // update scene graph
  27702. const bindings = this._bindings,
  27703. nBindings = this._nActiveBindings;
  27704. for ( let i = 0; i !== nBindings; ++ i ) {
  27705. bindings[ i ].apply( accuIndex );
  27706. }
  27707. return this;
  27708. }
  27709. // Allows you to seek to a specific time in an animation.
  27710. setTime( timeInSeconds ) {
  27711. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27712. for ( let i = 0; i < this._actions.length; i ++ ) {
  27713. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27714. }
  27715. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27716. }
  27717. // return this mixer's root target object
  27718. getRoot() {
  27719. return this._root;
  27720. }
  27721. // free all resources specific to a particular clip
  27722. uncacheClip( clip ) {
  27723. const actions = this._actions,
  27724. clipUuid = clip.uuid,
  27725. actionsByClip = this._actionsByClip,
  27726. actionsForClip = actionsByClip[ clipUuid ];
  27727. if ( actionsForClip !== undefined ) {
  27728. // note: just calling _removeInactiveAction would mess up the
  27729. // iteration state and also require updating the state we can
  27730. // just throw away
  27731. const actionsToRemove = actionsForClip.knownActions;
  27732. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27733. const action = actionsToRemove[ i ];
  27734. this._deactivateAction( action );
  27735. const cacheIndex = action._cacheIndex,
  27736. lastInactiveAction = actions[ actions.length - 1 ];
  27737. action._cacheIndex = null;
  27738. action._byClipCacheIndex = null;
  27739. lastInactiveAction._cacheIndex = cacheIndex;
  27740. actions[ cacheIndex ] = lastInactiveAction;
  27741. actions.pop();
  27742. this._removeInactiveBindingsForAction( action );
  27743. }
  27744. delete actionsByClip[ clipUuid ];
  27745. }
  27746. }
  27747. // free all resources specific to a particular root target object
  27748. uncacheRoot( root ) {
  27749. const rootUuid = root.uuid,
  27750. actionsByClip = this._actionsByClip;
  27751. for ( const clipUuid in actionsByClip ) {
  27752. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27753. action = actionByRoot[ rootUuid ];
  27754. if ( action !== undefined ) {
  27755. this._deactivateAction( action );
  27756. this._removeInactiveAction( action );
  27757. }
  27758. }
  27759. const bindingsByRoot = this._bindingsByRootAndName,
  27760. bindingByName = bindingsByRoot[ rootUuid ];
  27761. if ( bindingByName !== undefined ) {
  27762. for ( const trackName in bindingByName ) {
  27763. const binding = bindingByName[ trackName ];
  27764. binding.restoreOriginalState();
  27765. this._removeInactiveBinding( binding );
  27766. }
  27767. }
  27768. }
  27769. // remove a targeted clip from the cache
  27770. uncacheAction( clip, optionalRoot ) {
  27771. const action = this.existingAction( clip, optionalRoot );
  27772. if ( action !== null ) {
  27773. this._deactivateAction( action );
  27774. this._removeInactiveAction( action );
  27775. }
  27776. }
  27777. }
  27778. class Uniform {
  27779. constructor( value ) {
  27780. this.value = value;
  27781. }
  27782. clone() {
  27783. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27784. }
  27785. }
  27786. let id = 0;
  27787. class UniformsGroup extends EventDispatcher {
  27788. constructor() {
  27789. super();
  27790. this.isUniformsGroup = true;
  27791. Object.defineProperty( this, 'id', { value: id ++ } );
  27792. this.name = '';
  27793. this.usage = StaticDrawUsage;
  27794. this.uniforms = [];
  27795. }
  27796. add( uniform ) {
  27797. this.uniforms.push( uniform );
  27798. return this;
  27799. }
  27800. remove( uniform ) {
  27801. const index = this.uniforms.indexOf( uniform );
  27802. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  27803. return this;
  27804. }
  27805. setName( name ) {
  27806. this.name = name;
  27807. return this;
  27808. }
  27809. setUsage( value ) {
  27810. this.usage = value;
  27811. return this;
  27812. }
  27813. dispose() {
  27814. this.dispatchEvent( { type: 'dispose' } );
  27815. return this;
  27816. }
  27817. copy( source ) {
  27818. this.name = source.name;
  27819. this.usage = source.usage;
  27820. const uniformsSource = source.uniforms;
  27821. this.uniforms.length = 0;
  27822. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  27823. this.uniforms.push( uniformsSource[ i ].clone() );
  27824. }
  27825. return this;
  27826. }
  27827. clone() {
  27828. return new this.constructor().copy( this );
  27829. }
  27830. }
  27831. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27832. constructor( array, stride, meshPerAttribute = 1 ) {
  27833. super( array, stride );
  27834. this.isInstancedInterleavedBuffer = true;
  27835. this.meshPerAttribute = meshPerAttribute;
  27836. }
  27837. copy( source ) {
  27838. super.copy( source );
  27839. this.meshPerAttribute = source.meshPerAttribute;
  27840. return this;
  27841. }
  27842. clone( data ) {
  27843. const ib = super.clone( data );
  27844. ib.meshPerAttribute = this.meshPerAttribute;
  27845. return ib;
  27846. }
  27847. toJSON( data ) {
  27848. const json = super.toJSON( data );
  27849. json.isInstancedInterleavedBuffer = true;
  27850. json.meshPerAttribute = this.meshPerAttribute;
  27851. return json;
  27852. }
  27853. }
  27854. class GLBufferAttribute {
  27855. constructor( buffer, type, itemSize, elementSize, count ) {
  27856. this.isGLBufferAttribute = true;
  27857. this.buffer = buffer;
  27858. this.type = type;
  27859. this.itemSize = itemSize;
  27860. this.elementSize = elementSize;
  27861. this.count = count;
  27862. this.version = 0;
  27863. }
  27864. set needsUpdate( value ) {
  27865. if ( value === true ) this.version ++;
  27866. }
  27867. setBuffer( buffer ) {
  27868. this.buffer = buffer;
  27869. return this;
  27870. }
  27871. setType( type, elementSize ) {
  27872. this.type = type;
  27873. this.elementSize = elementSize;
  27874. return this;
  27875. }
  27876. setItemSize( itemSize ) {
  27877. this.itemSize = itemSize;
  27878. return this;
  27879. }
  27880. setCount( count ) {
  27881. this.count = count;
  27882. return this;
  27883. }
  27884. }
  27885. class Raycaster {
  27886. constructor( origin, direction, near = 0, far = Infinity ) {
  27887. this.ray = new Ray( origin, direction );
  27888. // direction is assumed to be normalized (for accurate distance calculations)
  27889. this.near = near;
  27890. this.far = far;
  27891. this.camera = null;
  27892. this.layers = new Layers();
  27893. this.params = {
  27894. Mesh: {},
  27895. Line: { threshold: 1 },
  27896. LOD: {},
  27897. Points: { threshold: 1 },
  27898. Sprite: {}
  27899. };
  27900. }
  27901. set( origin, direction ) {
  27902. // direction is assumed to be normalized (for accurate distance calculations)
  27903. this.ray.set( origin, direction );
  27904. }
  27905. setFromCamera( coords, camera ) {
  27906. if ( camera.isPerspectiveCamera ) {
  27907. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27908. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27909. this.camera = camera;
  27910. } else if ( camera.isOrthographicCamera ) {
  27911. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27912. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27913. this.camera = camera;
  27914. } else {
  27915. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27916. }
  27917. }
  27918. intersectObject( object, recursive = true, intersects = [] ) {
  27919. intersectObject( object, this, intersects, recursive );
  27920. intersects.sort( ascSort );
  27921. return intersects;
  27922. }
  27923. intersectObjects( objects, recursive = true, intersects = [] ) {
  27924. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27925. intersectObject( objects[ i ], this, intersects, recursive );
  27926. }
  27927. intersects.sort( ascSort );
  27928. return intersects;
  27929. }
  27930. }
  27931. function ascSort( a, b ) {
  27932. return a.distance - b.distance;
  27933. }
  27934. function intersectObject( object, raycaster, intersects, recursive ) {
  27935. if ( object.layers.test( raycaster.layers ) ) {
  27936. object.raycast( raycaster, intersects );
  27937. }
  27938. if ( recursive === true ) {
  27939. const children = object.children;
  27940. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27941. intersectObject( children[ i ], raycaster, intersects, true );
  27942. }
  27943. }
  27944. }
  27945. /**
  27946. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27947. *
  27948. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27949. * The azimuthal angle (theta) is measured from the positive z-axis.
  27950. */
  27951. class Spherical {
  27952. constructor( radius = 1, phi = 0, theta = 0 ) {
  27953. this.radius = radius;
  27954. this.phi = phi; // polar angle
  27955. this.theta = theta; // azimuthal angle
  27956. return this;
  27957. }
  27958. set( radius, phi, theta ) {
  27959. this.radius = radius;
  27960. this.phi = phi;
  27961. this.theta = theta;
  27962. return this;
  27963. }
  27964. copy( other ) {
  27965. this.radius = other.radius;
  27966. this.phi = other.phi;
  27967. this.theta = other.theta;
  27968. return this;
  27969. }
  27970. // restrict phi to be between EPS and PI-EPS
  27971. makeSafe() {
  27972. const EPS = 0.000001;
  27973. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27974. return this;
  27975. }
  27976. setFromVector3( v ) {
  27977. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27978. }
  27979. setFromCartesianCoords( x, y, z ) {
  27980. this.radius = Math.sqrt( x * x + y * y + z * z );
  27981. if ( this.radius === 0 ) {
  27982. this.theta = 0;
  27983. this.phi = 0;
  27984. } else {
  27985. this.theta = Math.atan2( x, z );
  27986. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27987. }
  27988. return this;
  27989. }
  27990. clone() {
  27991. return new this.constructor().copy( this );
  27992. }
  27993. }
  27994. /**
  27995. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27996. */
  27997. class Cylindrical {
  27998. constructor( radius = 1, theta = 0, y = 0 ) {
  27999. this.radius = radius; // distance from the origin to a point in the x-z plane
  28000. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28001. this.y = y; // height above the x-z plane
  28002. return this;
  28003. }
  28004. set( radius, theta, y ) {
  28005. this.radius = radius;
  28006. this.theta = theta;
  28007. this.y = y;
  28008. return this;
  28009. }
  28010. copy( other ) {
  28011. this.radius = other.radius;
  28012. this.theta = other.theta;
  28013. this.y = other.y;
  28014. return this;
  28015. }
  28016. setFromVector3( v ) {
  28017. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28018. }
  28019. setFromCartesianCoords( x, y, z ) {
  28020. this.radius = Math.sqrt( x * x + z * z );
  28021. this.theta = Math.atan2( x, z );
  28022. this.y = y;
  28023. return this;
  28024. }
  28025. clone() {
  28026. return new this.constructor().copy( this );
  28027. }
  28028. }
  28029. const _vector$4 = /*@__PURE__*/ new Vector2();
  28030. class Box2 {
  28031. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28032. this.isBox2 = true;
  28033. this.min = min;
  28034. this.max = max;
  28035. }
  28036. set( min, max ) {
  28037. this.min.copy( min );
  28038. this.max.copy( max );
  28039. return this;
  28040. }
  28041. setFromPoints( points ) {
  28042. this.makeEmpty();
  28043. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28044. this.expandByPoint( points[ i ] );
  28045. }
  28046. return this;
  28047. }
  28048. setFromCenterAndSize( center, size ) {
  28049. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28050. this.min.copy( center ).sub( halfSize );
  28051. this.max.copy( center ).add( halfSize );
  28052. return this;
  28053. }
  28054. clone() {
  28055. return new this.constructor().copy( this );
  28056. }
  28057. copy( box ) {
  28058. this.min.copy( box.min );
  28059. this.max.copy( box.max );
  28060. return this;
  28061. }
  28062. makeEmpty() {
  28063. this.min.x = this.min.y = + Infinity;
  28064. this.max.x = this.max.y = - Infinity;
  28065. return this;
  28066. }
  28067. isEmpty() {
  28068. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28069. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28070. }
  28071. getCenter( target ) {
  28072. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28073. }
  28074. getSize( target ) {
  28075. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28076. }
  28077. expandByPoint( point ) {
  28078. this.min.min( point );
  28079. this.max.max( point );
  28080. return this;
  28081. }
  28082. expandByVector( vector ) {
  28083. this.min.sub( vector );
  28084. this.max.add( vector );
  28085. return this;
  28086. }
  28087. expandByScalar( scalar ) {
  28088. this.min.addScalar( - scalar );
  28089. this.max.addScalar( scalar );
  28090. return this;
  28091. }
  28092. containsPoint( point ) {
  28093. return point.x < this.min.x || point.x > this.max.x ||
  28094. point.y < this.min.y || point.y > this.max.y ? false : true;
  28095. }
  28096. containsBox( box ) {
  28097. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28098. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28099. }
  28100. getParameter( point, target ) {
  28101. // This can potentially have a divide by zero if the box
  28102. // has a size dimension of 0.
  28103. return target.set(
  28104. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28105. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28106. );
  28107. }
  28108. intersectsBox( box ) {
  28109. // using 4 splitting planes to rule out intersections
  28110. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28111. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28112. }
  28113. clampPoint( point, target ) {
  28114. return target.copy( point ).clamp( this.min, this.max );
  28115. }
  28116. distanceToPoint( point ) {
  28117. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28118. return clampedPoint.sub( point ).length();
  28119. }
  28120. intersect( box ) {
  28121. this.min.max( box.min );
  28122. this.max.min( box.max );
  28123. return this;
  28124. }
  28125. union( box ) {
  28126. this.min.min( box.min );
  28127. this.max.max( box.max );
  28128. return this;
  28129. }
  28130. translate( offset ) {
  28131. this.min.add( offset );
  28132. this.max.add( offset );
  28133. return this;
  28134. }
  28135. equals( box ) {
  28136. return box.min.equals( this.min ) && box.max.equals( this.max );
  28137. }
  28138. }
  28139. const _startP = /*@__PURE__*/ new Vector3();
  28140. const _startEnd = /*@__PURE__*/ new Vector3();
  28141. class Line3 {
  28142. constructor( start = new Vector3(), end = new Vector3() ) {
  28143. this.start = start;
  28144. this.end = end;
  28145. }
  28146. set( start, end ) {
  28147. this.start.copy( start );
  28148. this.end.copy( end );
  28149. return this;
  28150. }
  28151. copy( line ) {
  28152. this.start.copy( line.start );
  28153. this.end.copy( line.end );
  28154. return this;
  28155. }
  28156. getCenter( target ) {
  28157. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28158. }
  28159. delta( target ) {
  28160. return target.subVectors( this.end, this.start );
  28161. }
  28162. distanceSq() {
  28163. return this.start.distanceToSquared( this.end );
  28164. }
  28165. distance() {
  28166. return this.start.distanceTo( this.end );
  28167. }
  28168. at( t, target ) {
  28169. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28170. }
  28171. closestPointToPointParameter( point, clampToLine ) {
  28172. _startP.subVectors( point, this.start );
  28173. _startEnd.subVectors( this.end, this.start );
  28174. const startEnd2 = _startEnd.dot( _startEnd );
  28175. const startEnd_startP = _startEnd.dot( _startP );
  28176. let t = startEnd_startP / startEnd2;
  28177. if ( clampToLine ) {
  28178. t = clamp( t, 0, 1 );
  28179. }
  28180. return t;
  28181. }
  28182. closestPointToPoint( point, clampToLine, target ) {
  28183. const t = this.closestPointToPointParameter( point, clampToLine );
  28184. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28185. }
  28186. applyMatrix4( matrix ) {
  28187. this.start.applyMatrix4( matrix );
  28188. this.end.applyMatrix4( matrix );
  28189. return this;
  28190. }
  28191. equals( line ) {
  28192. return line.start.equals( this.start ) && line.end.equals( this.end );
  28193. }
  28194. clone() {
  28195. return new this.constructor().copy( this );
  28196. }
  28197. }
  28198. const _vector$3 = /*@__PURE__*/ new Vector3();
  28199. class SpotLightHelper extends Object3D {
  28200. constructor( light, color ) {
  28201. super();
  28202. this.light = light;
  28203. this.light.updateMatrixWorld();
  28204. this.matrix = light.matrixWorld;
  28205. this.matrixAutoUpdate = false;
  28206. this.color = color;
  28207. const geometry = new BufferGeometry();
  28208. const positions = [
  28209. 0, 0, 0, 0, 0, 1,
  28210. 0, 0, 0, 1, 0, 1,
  28211. 0, 0, 0, - 1, 0, 1,
  28212. 0, 0, 0, 0, 1, 1,
  28213. 0, 0, 0, 0, - 1, 1
  28214. ];
  28215. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28216. const p1 = ( i / l ) * Math.PI * 2;
  28217. const p2 = ( j / l ) * Math.PI * 2;
  28218. positions.push(
  28219. Math.cos( p1 ), Math.sin( p1 ), 1,
  28220. Math.cos( p2 ), Math.sin( p2 ), 1
  28221. );
  28222. }
  28223. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28224. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28225. this.cone = new LineSegments( geometry, material );
  28226. this.add( this.cone );
  28227. this.update();
  28228. }
  28229. dispose() {
  28230. this.cone.geometry.dispose();
  28231. this.cone.material.dispose();
  28232. }
  28233. update() {
  28234. this.light.updateMatrixWorld();
  28235. const coneLength = this.light.distance ? this.light.distance : 1000;
  28236. const coneWidth = coneLength * Math.tan( this.light.angle );
  28237. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28238. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28239. this.cone.lookAt( _vector$3 );
  28240. if ( this.color !== undefined ) {
  28241. this.cone.material.color.set( this.color );
  28242. } else {
  28243. this.cone.material.color.copy( this.light.color );
  28244. }
  28245. }
  28246. }
  28247. const _vector$2 = /*@__PURE__*/ new Vector3();
  28248. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28249. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28250. class SkeletonHelper extends LineSegments {
  28251. constructor( object ) {
  28252. const bones = getBoneList( object );
  28253. const geometry = new BufferGeometry();
  28254. const vertices = [];
  28255. const colors = [];
  28256. const color1 = new Color( 0, 0, 1 );
  28257. const color2 = new Color( 0, 1, 0 );
  28258. for ( let i = 0; i < bones.length; i ++ ) {
  28259. const bone = bones[ i ];
  28260. if ( bone.parent && bone.parent.isBone ) {
  28261. vertices.push( 0, 0, 0 );
  28262. vertices.push( 0, 0, 0 );
  28263. colors.push( color1.r, color1.g, color1.b );
  28264. colors.push( color2.r, color2.g, color2.b );
  28265. }
  28266. }
  28267. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28268. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28269. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28270. super( geometry, material );
  28271. this.isSkeletonHelper = true;
  28272. this.type = 'SkeletonHelper';
  28273. this.root = object;
  28274. this.bones = bones;
  28275. this.matrix = object.matrixWorld;
  28276. this.matrixAutoUpdate = false;
  28277. }
  28278. updateMatrixWorld( force ) {
  28279. const bones = this.bones;
  28280. const geometry = this.geometry;
  28281. const position = geometry.getAttribute( 'position' );
  28282. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28283. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28284. const bone = bones[ i ];
  28285. if ( bone.parent && bone.parent.isBone ) {
  28286. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28287. _vector$2.setFromMatrixPosition( _boneMatrix );
  28288. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28289. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28290. _vector$2.setFromMatrixPosition( _boneMatrix );
  28291. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28292. j += 2;
  28293. }
  28294. }
  28295. geometry.getAttribute( 'position' ).needsUpdate = true;
  28296. super.updateMatrixWorld( force );
  28297. }
  28298. dispose() {
  28299. this.geometry.dispose();
  28300. this.material.dispose();
  28301. }
  28302. }
  28303. function getBoneList( object ) {
  28304. const boneList = [];
  28305. if ( object.isBone === true ) {
  28306. boneList.push( object );
  28307. }
  28308. for ( let i = 0; i < object.children.length; i ++ ) {
  28309. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28310. }
  28311. return boneList;
  28312. }
  28313. class PointLightHelper extends Mesh {
  28314. constructor( light, sphereSize, color ) {
  28315. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28316. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28317. super( geometry, material );
  28318. this.light = light;
  28319. this.light.updateMatrixWorld();
  28320. this.color = color;
  28321. this.type = 'PointLightHelper';
  28322. this.matrix = this.light.matrixWorld;
  28323. this.matrixAutoUpdate = false;
  28324. this.update();
  28325. /*
  28326. // TODO: delete this comment?
  28327. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28328. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28329. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28330. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28331. const d = light.distance;
  28332. if ( d === 0.0 ) {
  28333. this.lightDistance.visible = false;
  28334. } else {
  28335. this.lightDistance.scale.set( d, d, d );
  28336. }
  28337. this.add( this.lightDistance );
  28338. */
  28339. }
  28340. dispose() {
  28341. this.geometry.dispose();
  28342. this.material.dispose();
  28343. }
  28344. update() {
  28345. if ( this.color !== undefined ) {
  28346. this.material.color.set( this.color );
  28347. } else {
  28348. this.material.color.copy( this.light.color );
  28349. }
  28350. /*
  28351. const d = this.light.distance;
  28352. if ( d === 0.0 ) {
  28353. this.lightDistance.visible = false;
  28354. } else {
  28355. this.lightDistance.visible = true;
  28356. this.lightDistance.scale.set( d, d, d );
  28357. }
  28358. */
  28359. }
  28360. }
  28361. const _vector$1 = /*@__PURE__*/ new Vector3();
  28362. const _color1 = /*@__PURE__*/ new Color();
  28363. const _color2 = /*@__PURE__*/ new Color();
  28364. class HemisphereLightHelper extends Object3D {
  28365. constructor( light, size, color ) {
  28366. super();
  28367. this.light = light;
  28368. this.light.updateMatrixWorld();
  28369. this.matrix = light.matrixWorld;
  28370. this.matrixAutoUpdate = false;
  28371. this.color = color;
  28372. const geometry = new OctahedronGeometry( size );
  28373. geometry.rotateY( Math.PI * 0.5 );
  28374. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28375. if ( this.color === undefined ) this.material.vertexColors = true;
  28376. const position = geometry.getAttribute( 'position' );
  28377. const colors = new Float32Array( position.count * 3 );
  28378. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28379. this.add( new Mesh( geometry, this.material ) );
  28380. this.update();
  28381. }
  28382. dispose() {
  28383. this.children[ 0 ].geometry.dispose();
  28384. this.children[ 0 ].material.dispose();
  28385. }
  28386. update() {
  28387. const mesh = this.children[ 0 ];
  28388. if ( this.color !== undefined ) {
  28389. this.material.color.set( this.color );
  28390. } else {
  28391. const colors = mesh.geometry.getAttribute( 'color' );
  28392. _color1.copy( this.light.color );
  28393. _color2.copy( this.light.groundColor );
  28394. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28395. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28396. colors.setXYZ( i, color.r, color.g, color.b );
  28397. }
  28398. colors.needsUpdate = true;
  28399. }
  28400. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28401. }
  28402. }
  28403. class GridHelper extends LineSegments {
  28404. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28405. color1 = new Color( color1 );
  28406. color2 = new Color( color2 );
  28407. const center = divisions / 2;
  28408. const step = size / divisions;
  28409. const halfSize = size / 2;
  28410. const vertices = [], colors = [];
  28411. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28412. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28413. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28414. const color = i === center ? color1 : color2;
  28415. color.toArray( colors, j ); j += 3;
  28416. color.toArray( colors, j ); j += 3;
  28417. color.toArray( colors, j ); j += 3;
  28418. color.toArray( colors, j ); j += 3;
  28419. }
  28420. const geometry = new BufferGeometry();
  28421. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28422. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28423. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28424. super( geometry, material );
  28425. this.type = 'GridHelper';
  28426. }
  28427. dispose() {
  28428. this.geometry.dispose();
  28429. this.material.dispose();
  28430. }
  28431. }
  28432. class PolarGridHelper extends LineSegments {
  28433. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28434. color1 = new Color( color1 );
  28435. color2 = new Color( color2 );
  28436. const vertices = [];
  28437. const colors = [];
  28438. // create the sectors
  28439. if ( sectors > 1 ) {
  28440. for ( let i = 0; i < sectors; i ++ ) {
  28441. const v = ( i / sectors ) * ( Math.PI * 2 );
  28442. const x = Math.sin( v ) * radius;
  28443. const z = Math.cos( v ) * radius;
  28444. vertices.push( 0, 0, 0 );
  28445. vertices.push( x, 0, z );
  28446. const color = ( i & 1 ) ? color1 : color2;
  28447. colors.push( color.r, color.g, color.b );
  28448. colors.push( color.r, color.g, color.b );
  28449. }
  28450. }
  28451. // create the rings
  28452. for ( let i = 0; i < rings; i ++ ) {
  28453. const color = ( i & 1 ) ? color1 : color2;
  28454. const r = radius - ( radius / rings * i );
  28455. for ( let j = 0; j < divisions; j ++ ) {
  28456. // first vertex
  28457. let v = ( j / divisions ) * ( Math.PI * 2 );
  28458. let x = Math.sin( v ) * r;
  28459. let z = Math.cos( v ) * r;
  28460. vertices.push( x, 0, z );
  28461. colors.push( color.r, color.g, color.b );
  28462. // second vertex
  28463. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28464. x = Math.sin( v ) * r;
  28465. z = Math.cos( v ) * r;
  28466. vertices.push( x, 0, z );
  28467. colors.push( color.r, color.g, color.b );
  28468. }
  28469. }
  28470. const geometry = new BufferGeometry();
  28471. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28472. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28473. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28474. super( geometry, material );
  28475. this.type = 'PolarGridHelper';
  28476. }
  28477. dispose() {
  28478. this.geometry.dispose();
  28479. this.material.dispose();
  28480. }
  28481. }
  28482. const _v1 = /*@__PURE__*/ new Vector3();
  28483. const _v2 = /*@__PURE__*/ new Vector3();
  28484. const _v3 = /*@__PURE__*/ new Vector3();
  28485. class DirectionalLightHelper extends Object3D {
  28486. constructor( light, size, color ) {
  28487. super();
  28488. this.light = light;
  28489. this.light.updateMatrixWorld();
  28490. this.matrix = light.matrixWorld;
  28491. this.matrixAutoUpdate = false;
  28492. this.color = color;
  28493. if ( size === undefined ) size = 1;
  28494. let geometry = new BufferGeometry();
  28495. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28496. - size, size, 0,
  28497. size, size, 0,
  28498. size, - size, 0,
  28499. - size, - size, 0,
  28500. - size, size, 0
  28501. ], 3 ) );
  28502. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28503. this.lightPlane = new Line( geometry, material );
  28504. this.add( this.lightPlane );
  28505. geometry = new BufferGeometry();
  28506. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28507. this.targetLine = new Line( geometry, material );
  28508. this.add( this.targetLine );
  28509. this.update();
  28510. }
  28511. dispose() {
  28512. this.lightPlane.geometry.dispose();
  28513. this.lightPlane.material.dispose();
  28514. this.targetLine.geometry.dispose();
  28515. this.targetLine.material.dispose();
  28516. }
  28517. update() {
  28518. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28519. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28520. _v3.subVectors( _v2, _v1 );
  28521. this.lightPlane.lookAt( _v2 );
  28522. if ( this.color !== undefined ) {
  28523. this.lightPlane.material.color.set( this.color );
  28524. this.targetLine.material.color.set( this.color );
  28525. } else {
  28526. this.lightPlane.material.color.copy( this.light.color );
  28527. this.targetLine.material.color.copy( this.light.color );
  28528. }
  28529. this.targetLine.lookAt( _v2 );
  28530. this.targetLine.scale.z = _v3.length();
  28531. }
  28532. }
  28533. const _vector = /*@__PURE__*/ new Vector3();
  28534. const _camera = /*@__PURE__*/ new Camera();
  28535. /**
  28536. * - shows frustum, line of sight and up of the camera
  28537. * - suitable for fast updates
  28538. * - based on frustum visualization in lightgl.js shadowmap example
  28539. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28540. */
  28541. class CameraHelper extends LineSegments {
  28542. constructor( camera ) {
  28543. const geometry = new BufferGeometry();
  28544. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28545. const vertices = [];
  28546. const colors = [];
  28547. const pointMap = {};
  28548. // near
  28549. addLine( 'n1', 'n2' );
  28550. addLine( 'n2', 'n4' );
  28551. addLine( 'n4', 'n3' );
  28552. addLine( 'n3', 'n1' );
  28553. // far
  28554. addLine( 'f1', 'f2' );
  28555. addLine( 'f2', 'f4' );
  28556. addLine( 'f4', 'f3' );
  28557. addLine( 'f3', 'f1' );
  28558. // sides
  28559. addLine( 'n1', 'f1' );
  28560. addLine( 'n2', 'f2' );
  28561. addLine( 'n3', 'f3' );
  28562. addLine( 'n4', 'f4' );
  28563. // cone
  28564. addLine( 'p', 'n1' );
  28565. addLine( 'p', 'n2' );
  28566. addLine( 'p', 'n3' );
  28567. addLine( 'p', 'n4' );
  28568. // up
  28569. addLine( 'u1', 'u2' );
  28570. addLine( 'u2', 'u3' );
  28571. addLine( 'u3', 'u1' );
  28572. // target
  28573. addLine( 'c', 't' );
  28574. addLine( 'p', 'c' );
  28575. // cross
  28576. addLine( 'cn1', 'cn2' );
  28577. addLine( 'cn3', 'cn4' );
  28578. addLine( 'cf1', 'cf2' );
  28579. addLine( 'cf3', 'cf4' );
  28580. function addLine( a, b ) {
  28581. addPoint( a );
  28582. addPoint( b );
  28583. }
  28584. function addPoint( id ) {
  28585. vertices.push( 0, 0, 0 );
  28586. colors.push( 0, 0, 0 );
  28587. if ( pointMap[ id ] === undefined ) {
  28588. pointMap[ id ] = [];
  28589. }
  28590. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28591. }
  28592. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28593. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28594. super( geometry, material );
  28595. this.type = 'CameraHelper';
  28596. this.camera = camera;
  28597. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28598. this.matrix = camera.matrixWorld;
  28599. this.matrixAutoUpdate = false;
  28600. this.pointMap = pointMap;
  28601. this.update();
  28602. // colors
  28603. const colorFrustum = new Color( 0xffaa00 );
  28604. const colorCone = new Color( 0xff0000 );
  28605. const colorUp = new Color( 0x00aaff );
  28606. const colorTarget = new Color( 0xffffff );
  28607. const colorCross = new Color( 0x333333 );
  28608. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28609. }
  28610. setColors( frustum, cone, up, target, cross ) {
  28611. const geometry = this.geometry;
  28612. const colorAttribute = geometry.getAttribute( 'color' );
  28613. // near
  28614. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  28615. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  28616. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  28617. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  28618. // far
  28619. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  28620. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  28621. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  28622. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  28623. // sides
  28624. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  28625. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  28626. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  28627. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  28628. // cone
  28629. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  28630. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  28631. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  28632. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  28633. // up
  28634. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  28635. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  28636. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  28637. // target
  28638. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  28639. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  28640. // cross
  28641. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  28642. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  28643. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  28644. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  28645. colorAttribute.needsUpdate = true;
  28646. }
  28647. update() {
  28648. const geometry = this.geometry;
  28649. const pointMap = this.pointMap;
  28650. const w = 1, h = 1;
  28651. // we need just camera projection matrix inverse
  28652. // world matrix must be identity
  28653. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28654. // center / target
  28655. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28656. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28657. // near
  28658. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28659. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28660. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28661. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28662. // far
  28663. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28664. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28665. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28666. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28667. // up
  28668. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28669. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28670. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28671. // cross
  28672. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28673. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28674. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28675. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28676. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28677. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28678. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28679. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28680. geometry.getAttribute( 'position' ).needsUpdate = true;
  28681. }
  28682. dispose() {
  28683. this.geometry.dispose();
  28684. this.material.dispose();
  28685. }
  28686. }
  28687. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28688. _vector.set( x, y, z ).unproject( camera );
  28689. const points = pointMap[ point ];
  28690. if ( points !== undefined ) {
  28691. const position = geometry.getAttribute( 'position' );
  28692. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28693. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28694. }
  28695. }
  28696. }
  28697. const _box = /*@__PURE__*/ new Box3();
  28698. class BoxHelper extends LineSegments {
  28699. constructor( object, color = 0xffff00 ) {
  28700. 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 ] );
  28701. const positions = new Float32Array( 8 * 3 );
  28702. const geometry = new BufferGeometry();
  28703. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28704. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28705. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28706. this.object = object;
  28707. this.type = 'BoxHelper';
  28708. this.matrixAutoUpdate = false;
  28709. this.update();
  28710. }
  28711. update( object ) {
  28712. if ( object !== undefined ) {
  28713. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28714. }
  28715. if ( this.object !== undefined ) {
  28716. _box.setFromObject( this.object );
  28717. }
  28718. if ( _box.isEmpty() ) return;
  28719. const min = _box.min;
  28720. const max = _box.max;
  28721. /*
  28722. 5____4
  28723. 1/___0/|
  28724. | 6__|_7
  28725. 2/___3/
  28726. 0: max.x, max.y, max.z
  28727. 1: min.x, max.y, max.z
  28728. 2: min.x, min.y, max.z
  28729. 3: max.x, min.y, max.z
  28730. 4: max.x, max.y, min.z
  28731. 5: min.x, max.y, min.z
  28732. 6: min.x, min.y, min.z
  28733. 7: max.x, min.y, min.z
  28734. */
  28735. const position = this.geometry.attributes.position;
  28736. const array = position.array;
  28737. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28738. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28739. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28740. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28741. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28742. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28743. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28744. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28745. position.needsUpdate = true;
  28746. this.geometry.computeBoundingSphere();
  28747. }
  28748. setFromObject( object ) {
  28749. this.object = object;
  28750. this.update();
  28751. return this;
  28752. }
  28753. copy( source, recursive ) {
  28754. super.copy( source, recursive );
  28755. this.object = source.object;
  28756. return this;
  28757. }
  28758. dispose() {
  28759. this.geometry.dispose();
  28760. this.material.dispose();
  28761. }
  28762. }
  28763. class Box3Helper extends LineSegments {
  28764. constructor( box, color = 0xffff00 ) {
  28765. 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 ] );
  28766. 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 ];
  28767. const geometry = new BufferGeometry();
  28768. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28769. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28770. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28771. this.box = box;
  28772. this.type = 'Box3Helper';
  28773. this.geometry.computeBoundingSphere();
  28774. }
  28775. updateMatrixWorld( force ) {
  28776. const box = this.box;
  28777. if ( box.isEmpty() ) return;
  28778. box.getCenter( this.position );
  28779. box.getSize( this.scale );
  28780. this.scale.multiplyScalar( 0.5 );
  28781. super.updateMatrixWorld( force );
  28782. }
  28783. dispose() {
  28784. this.geometry.dispose();
  28785. this.material.dispose();
  28786. }
  28787. }
  28788. class PlaneHelper extends Line {
  28789. constructor( plane, size = 1, hex = 0xffff00 ) {
  28790. const color = hex;
  28791. 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 ];
  28792. const geometry = new BufferGeometry();
  28793. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28794. geometry.computeBoundingSphere();
  28795. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28796. this.type = 'PlaneHelper';
  28797. this.plane = plane;
  28798. this.size = size;
  28799. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  28800. const geometry2 = new BufferGeometry();
  28801. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28802. geometry2.computeBoundingSphere();
  28803. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28804. }
  28805. updateMatrixWorld( force ) {
  28806. this.position.set( 0, 0, 0 );
  28807. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  28808. this.lookAt( this.plane.normal );
  28809. this.translateZ( - this.plane.constant );
  28810. super.updateMatrixWorld( force );
  28811. }
  28812. dispose() {
  28813. this.geometry.dispose();
  28814. this.material.dispose();
  28815. this.children[ 0 ].geometry.dispose();
  28816. this.children[ 0 ].material.dispose();
  28817. }
  28818. }
  28819. const _axis = /*@__PURE__*/ new Vector3();
  28820. let _lineGeometry, _coneGeometry;
  28821. class ArrowHelper extends Object3D {
  28822. // dir is assumed to be normalized
  28823. 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 ) {
  28824. super();
  28825. this.type = 'ArrowHelper';
  28826. if ( _lineGeometry === undefined ) {
  28827. _lineGeometry = new BufferGeometry();
  28828. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28829. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28830. _coneGeometry.translate( 0, - 0.5, 0 );
  28831. }
  28832. this.position.copy( origin );
  28833. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28834. this.line.matrixAutoUpdate = false;
  28835. this.add( this.line );
  28836. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28837. this.cone.matrixAutoUpdate = false;
  28838. this.add( this.cone );
  28839. this.setDirection( dir );
  28840. this.setLength( length, headLength, headWidth );
  28841. }
  28842. setDirection( dir ) {
  28843. // dir is assumed to be normalized
  28844. if ( dir.y > 0.99999 ) {
  28845. this.quaternion.set( 0, 0, 0, 1 );
  28846. } else if ( dir.y < - 0.99999 ) {
  28847. this.quaternion.set( 1, 0, 0, 0 );
  28848. } else {
  28849. _axis.set( dir.z, 0, - dir.x ).normalize();
  28850. const radians = Math.acos( dir.y );
  28851. this.quaternion.setFromAxisAngle( _axis, radians );
  28852. }
  28853. }
  28854. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28855. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28856. this.line.updateMatrix();
  28857. this.cone.scale.set( headWidth, headLength, headWidth );
  28858. this.cone.position.y = length;
  28859. this.cone.updateMatrix();
  28860. }
  28861. setColor( color ) {
  28862. this.line.material.color.set( color );
  28863. this.cone.material.color.set( color );
  28864. }
  28865. copy( source ) {
  28866. super.copy( source, false );
  28867. this.line.copy( source.line );
  28868. this.cone.copy( source.cone );
  28869. return this;
  28870. }
  28871. dispose() {
  28872. this.line.geometry.dispose();
  28873. this.line.material.dispose();
  28874. this.cone.geometry.dispose();
  28875. this.cone.material.dispose();
  28876. }
  28877. }
  28878. class AxesHelper extends LineSegments {
  28879. constructor( size = 1 ) {
  28880. const vertices = [
  28881. 0, 0, 0, size, 0, 0,
  28882. 0, 0, 0, 0, size, 0,
  28883. 0, 0, 0, 0, 0, size
  28884. ];
  28885. const colors = [
  28886. 1, 0, 0, 1, 0.6, 0,
  28887. 0, 1, 0, 0.6, 1, 0,
  28888. 0, 0, 1, 0, 0.6, 1
  28889. ];
  28890. const geometry = new BufferGeometry();
  28891. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28892. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28893. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28894. super( geometry, material );
  28895. this.type = 'AxesHelper';
  28896. }
  28897. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28898. const color = new Color();
  28899. const array = this.geometry.attributes.color.array;
  28900. color.set( xAxisColor );
  28901. color.toArray( array, 0 );
  28902. color.toArray( array, 3 );
  28903. color.set( yAxisColor );
  28904. color.toArray( array, 6 );
  28905. color.toArray( array, 9 );
  28906. color.set( zAxisColor );
  28907. color.toArray( array, 12 );
  28908. color.toArray( array, 15 );
  28909. this.geometry.attributes.color.needsUpdate = true;
  28910. return this;
  28911. }
  28912. dispose() {
  28913. this.geometry.dispose();
  28914. this.material.dispose();
  28915. }
  28916. }
  28917. class ShapePath {
  28918. constructor() {
  28919. this.type = 'ShapePath';
  28920. this.color = new Color();
  28921. this.subPaths = [];
  28922. this.currentPath = null;
  28923. }
  28924. moveTo( x, y ) {
  28925. this.currentPath = new Path();
  28926. this.subPaths.push( this.currentPath );
  28927. this.currentPath.moveTo( x, y );
  28928. return this;
  28929. }
  28930. lineTo( x, y ) {
  28931. this.currentPath.lineTo( x, y );
  28932. return this;
  28933. }
  28934. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  28935. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28936. return this;
  28937. }
  28938. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28939. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28940. return this;
  28941. }
  28942. splineThru( pts ) {
  28943. this.currentPath.splineThru( pts );
  28944. return this;
  28945. }
  28946. toShapes( isCCW ) {
  28947. function toShapesNoHoles( inSubpaths ) {
  28948. const shapes = [];
  28949. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28950. const tmpPath = inSubpaths[ i ];
  28951. const tmpShape = new Shape();
  28952. tmpShape.curves = tmpPath.curves;
  28953. shapes.push( tmpShape );
  28954. }
  28955. return shapes;
  28956. }
  28957. function isPointInsidePolygon( inPt, inPolygon ) {
  28958. const polyLen = inPolygon.length;
  28959. // inPt on polygon contour => immediate success or
  28960. // toggling of inside/outside at every single! intersection point of an edge
  28961. // with the horizontal line through inPt, left of inPt
  28962. // not counting lowerY endpoints of edges and whole edges on that line
  28963. let inside = false;
  28964. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28965. let edgeLowPt = inPolygon[ p ];
  28966. let edgeHighPt = inPolygon[ q ];
  28967. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28968. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28969. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28970. // not parallel
  28971. if ( edgeDy < 0 ) {
  28972. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28973. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28974. }
  28975. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28976. if ( inPt.y === edgeLowPt.y ) {
  28977. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28978. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28979. } else {
  28980. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28981. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28982. if ( perpEdge < 0 ) continue;
  28983. inside = ! inside; // true intersection left of inPt
  28984. }
  28985. } else {
  28986. // parallel or collinear
  28987. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28988. // edge lies on the same horizontal line as inPt
  28989. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28990. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28991. // continue;
  28992. }
  28993. }
  28994. return inside;
  28995. }
  28996. const isClockWise = ShapeUtils.isClockWise;
  28997. const subPaths = this.subPaths;
  28998. if ( subPaths.length === 0 ) return [];
  28999. let solid, tmpPath, tmpShape;
  29000. const shapes = [];
  29001. if ( subPaths.length === 1 ) {
  29002. tmpPath = subPaths[ 0 ];
  29003. tmpShape = new Shape();
  29004. tmpShape.curves = tmpPath.curves;
  29005. shapes.push( tmpShape );
  29006. return shapes;
  29007. }
  29008. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29009. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29010. // console.log("Holes first", holesFirst);
  29011. const betterShapeHoles = [];
  29012. const newShapes = [];
  29013. let newShapeHoles = [];
  29014. let mainIdx = 0;
  29015. let tmpPoints;
  29016. newShapes[ mainIdx ] = undefined;
  29017. newShapeHoles[ mainIdx ] = [];
  29018. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29019. tmpPath = subPaths[ i ];
  29020. tmpPoints = tmpPath.getPoints();
  29021. solid = isClockWise( tmpPoints );
  29022. solid = isCCW ? ! solid : solid;
  29023. if ( solid ) {
  29024. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29025. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29026. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29027. if ( holesFirst ) mainIdx ++;
  29028. newShapeHoles[ mainIdx ] = [];
  29029. //console.log('cw', i);
  29030. } else {
  29031. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29032. //console.log('ccw', i);
  29033. }
  29034. }
  29035. // only Holes? -> probably all Shapes with wrong orientation
  29036. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29037. if ( newShapes.length > 1 ) {
  29038. let ambiguous = false;
  29039. let toChange = 0;
  29040. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29041. betterShapeHoles[ sIdx ] = [];
  29042. }
  29043. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29044. const sho = newShapeHoles[ sIdx ];
  29045. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29046. const ho = sho[ hIdx ];
  29047. let hole_unassigned = true;
  29048. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29049. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29050. if ( sIdx !== s2Idx ) toChange ++;
  29051. if ( hole_unassigned ) {
  29052. hole_unassigned = false;
  29053. betterShapeHoles[ s2Idx ].push( ho );
  29054. } else {
  29055. ambiguous = true;
  29056. }
  29057. }
  29058. }
  29059. if ( hole_unassigned ) {
  29060. betterShapeHoles[ sIdx ].push( ho );
  29061. }
  29062. }
  29063. }
  29064. if ( toChange > 0 && ambiguous === false ) {
  29065. newShapeHoles = betterShapeHoles;
  29066. }
  29067. }
  29068. let tmpHoles;
  29069. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29070. tmpShape = newShapes[ i ].s;
  29071. shapes.push( tmpShape );
  29072. tmpHoles = newShapeHoles[ i ];
  29073. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29074. tmpShape.holes.push( tmpHoles[ j ].h );
  29075. }
  29076. }
  29077. //console.log("shape", shapes);
  29078. return shapes;
  29079. }
  29080. }
  29081. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29082. const _tables = /*@__PURE__*/ _generateTables();
  29083. function _generateTables() {
  29084. // float32 to float16 helpers
  29085. const buffer = new ArrayBuffer( 4 );
  29086. const floatView = new Float32Array( buffer );
  29087. const uint32View = new Uint32Array( buffer );
  29088. const baseTable = new Uint32Array( 512 );
  29089. const shiftTable = new Uint32Array( 512 );
  29090. for ( let i = 0; i < 256; ++ i ) {
  29091. const e = i - 127;
  29092. // very small number (0, -0)
  29093. if ( e < - 27 ) {
  29094. baseTable[ i ] = 0x0000;
  29095. baseTable[ i | 0x100 ] = 0x8000;
  29096. shiftTable[ i ] = 24;
  29097. shiftTable[ i | 0x100 ] = 24;
  29098. // small number (denorm)
  29099. } else if ( e < - 14 ) {
  29100. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29101. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29102. shiftTable[ i ] = - e - 1;
  29103. shiftTable[ i | 0x100 ] = - e - 1;
  29104. // normal number
  29105. } else if ( e <= 15 ) {
  29106. baseTable[ i ] = ( e + 15 ) << 10;
  29107. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29108. shiftTable[ i ] = 13;
  29109. shiftTable[ i | 0x100 ] = 13;
  29110. // large number (Infinity, -Infinity)
  29111. } else if ( e < 128 ) {
  29112. baseTable[ i ] = 0x7c00;
  29113. baseTable[ i | 0x100 ] = 0xfc00;
  29114. shiftTable[ i ] = 24;
  29115. shiftTable[ i | 0x100 ] = 24;
  29116. // stay (NaN, Infinity, -Infinity)
  29117. } else {
  29118. baseTable[ i ] = 0x7c00;
  29119. baseTable[ i | 0x100 ] = 0xfc00;
  29120. shiftTable[ i ] = 13;
  29121. shiftTable[ i | 0x100 ] = 13;
  29122. }
  29123. }
  29124. // float16 to float32 helpers
  29125. const mantissaTable = new Uint32Array( 2048 );
  29126. const exponentTable = new Uint32Array( 64 );
  29127. const offsetTable = new Uint32Array( 64 );
  29128. for ( let i = 1; i < 1024; ++ i ) {
  29129. let m = i << 13; // zero pad mantissa bits
  29130. let e = 0; // zero exponent
  29131. // normalized
  29132. while ( ( m & 0x00800000 ) === 0 ) {
  29133. m <<= 1;
  29134. e -= 0x00800000; // decrement exponent
  29135. }
  29136. m &= ~ 0x00800000; // clear leading 1 bit
  29137. e += 0x38800000; // adjust bias
  29138. mantissaTable[ i ] = m | e;
  29139. }
  29140. for ( let i = 1024; i < 2048; ++ i ) {
  29141. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29142. }
  29143. for ( let i = 1; i < 31; ++ i ) {
  29144. exponentTable[ i ] = i << 23;
  29145. }
  29146. exponentTable[ 31 ] = 0x47800000;
  29147. exponentTable[ 32 ] = 0x80000000;
  29148. for ( let i = 33; i < 63; ++ i ) {
  29149. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29150. }
  29151. exponentTable[ 63 ] = 0xc7800000;
  29152. for ( let i = 1; i < 64; ++ i ) {
  29153. if ( i !== 32 ) {
  29154. offsetTable[ i ] = 1024;
  29155. }
  29156. }
  29157. return {
  29158. floatView: floatView,
  29159. uint32View: uint32View,
  29160. baseTable: baseTable,
  29161. shiftTable: shiftTable,
  29162. mantissaTable: mantissaTable,
  29163. exponentTable: exponentTable,
  29164. offsetTable: offsetTable
  29165. };
  29166. }
  29167. // float32 to float16
  29168. function toHalfFloat( val ) {
  29169. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29170. val = clamp( val, - 65504, 65504 );
  29171. _tables.floatView[ 0 ] = val;
  29172. const f = _tables.uint32View[ 0 ];
  29173. const e = ( f >> 23 ) & 0x1ff;
  29174. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29175. }
  29176. // float16 to float32
  29177. function fromHalfFloat( val ) {
  29178. const m = val >> 10;
  29179. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29180. return _tables.floatView[ 0 ];
  29181. }
  29182. var DataUtils = /*#__PURE__*/Object.freeze({
  29183. __proto__: null,
  29184. toHalfFloat: toHalfFloat,
  29185. fromHalfFloat: fromHalfFloat
  29186. });
  29187. // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  29188. function ImmediateRenderObject() {
  29189. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29190. }
  29191. // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  29192. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  29193. constructor( width, height, options ) {
  29194. console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' );
  29195. super( width, height, options );
  29196. this.samples = 4;
  29197. }
  29198. }
  29199. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29200. class DataTexture2DArray extends DataArrayTexture {
  29201. constructor( data, width, height, depth ) {
  29202. console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' );
  29203. super( data, width, height, depth );
  29204. }
  29205. }
  29206. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29207. class DataTexture3D extends Data3DTexture {
  29208. constructor( data, width, height, depth ) {
  29209. console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' );
  29210. super( data, width, height, depth );
  29211. }
  29212. }
  29213. // r144
  29214. class BoxBufferGeometry extends BoxGeometry {
  29215. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29216. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29217. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29218. }
  29219. }
  29220. // r144
  29221. class CapsuleBufferGeometry extends CapsuleGeometry {
  29222. constructor( radius, length, capSegments, radialSegments ) {
  29223. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29224. super( radius, length, capSegments, radialSegments );
  29225. }
  29226. }
  29227. // r144
  29228. class CircleBufferGeometry extends CircleGeometry {
  29229. constructor( radius, segments, thetaStart, thetaLength ) {
  29230. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29231. super( radius, segments, thetaStart, thetaLength );
  29232. }
  29233. }
  29234. // r144
  29235. class ConeBufferGeometry extends ConeGeometry {
  29236. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29237. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29238. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29239. }
  29240. }
  29241. // r144
  29242. class CylinderBufferGeometry extends CylinderGeometry {
  29243. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29244. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29245. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29246. }
  29247. }
  29248. // r144
  29249. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29250. constructor( radius, detail ) {
  29251. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29252. super( radius, detail );
  29253. }
  29254. }
  29255. // r144
  29256. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29257. constructor( shapes, options ) {
  29258. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29259. super( shapes, options );
  29260. }
  29261. }
  29262. // r144
  29263. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29264. constructor( radius, detail ) {
  29265. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29266. super( radius, detail );
  29267. }
  29268. }
  29269. // r144
  29270. class LatheBufferGeometry extends LatheGeometry {
  29271. constructor( points, segments, phiStart, phiLength ) {
  29272. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29273. super( points, segments, phiStart, phiLength );
  29274. }
  29275. }
  29276. // r144
  29277. class OctahedronBufferGeometry extends OctahedronGeometry {
  29278. constructor( radius, detail ) {
  29279. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29280. super( radius, detail );
  29281. }
  29282. }
  29283. // r144
  29284. class PlaneBufferGeometry extends PlaneGeometry {
  29285. constructor( width, height, widthSegments, heightSegments ) {
  29286. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29287. super( width, height, widthSegments, heightSegments );
  29288. }
  29289. }
  29290. // r144
  29291. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29292. constructor( vertices, indices, radius, detail ) {
  29293. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29294. super( vertices, indices, radius, detail );
  29295. }
  29296. }
  29297. // r144
  29298. class RingBufferGeometry extends RingGeometry {
  29299. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29300. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29301. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29302. }
  29303. }
  29304. // r144
  29305. class ShapeBufferGeometry extends ShapeGeometry {
  29306. constructor( shapes, curveSegments ) {
  29307. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29308. super( shapes, curveSegments );
  29309. }
  29310. }
  29311. // r144
  29312. class SphereBufferGeometry extends SphereGeometry {
  29313. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29314. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29315. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29316. }
  29317. }
  29318. // r144
  29319. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29320. constructor( radius, detail ) {
  29321. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29322. super( radius, detail );
  29323. }
  29324. }
  29325. // r144
  29326. class TorusBufferGeometry extends TorusGeometry {
  29327. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29328. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29329. super( radius, tube, radialSegments, tubularSegments, arc );
  29330. }
  29331. }
  29332. // r144
  29333. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29334. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29335. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29336. super( radius, tube, tubularSegments, radialSegments, p, q );
  29337. }
  29338. }
  29339. // r144
  29340. class TubeBufferGeometry extends TubeGeometry {
  29341. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29342. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29343. super( path, tubularSegments, radius, radialSegments, closed );
  29344. }
  29345. }
  29346. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29347. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29348. revision: REVISION,
  29349. } } ) );
  29350. }
  29351. if ( typeof window !== 'undefined' ) {
  29352. if ( window.__THREE__ ) {
  29353. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29354. } else {
  29355. window.__THREE__ = REVISION;
  29356. }
  29357. }
  29358. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SRGBColorSpace, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };